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|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "datasets>=3.0",
|
| 5 |
+
# "pandas>=2.0",
|
| 6 |
+
# "huggingface_hub>=0.26",
|
| 7 |
+
# ]
|
| 8 |
+
# ///
|
| 9 |
+
"""
|
| 10 |
+
Analyze davidkling/hf-coding-tools-traces.
|
| 11 |
+
|
| 12 |
+
Each row is a SESSION. Each session.traces is a list of event dicts:
|
| 13 |
+
- type=user: a query
|
| 14 |
+
- type=assistant: a model response carrying `benchmark_metadata` with
|
| 15 |
+
has_hf_mention, detected_products, all_mentioned_products, cost_usd,
|
| 16 |
+
latency_ms, query_level, query_category, tool, effort, thinking, error.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import ast
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
from collections import Counter, defaultdict
|
| 24 |
+
from statistics import mean, median
|
| 25 |
+
|
| 26 |
+
from datasets import load_dataset
|
| 27 |
+
from huggingface_hub import HfApi
|
| 28 |
+
|
| 29 |
+
DATASET_ID = "davidkling/hf-coding-tools-traces"
|
| 30 |
+
OUTPUT_REPO = "evalstate/hf-coding-traces-analysis"
|
| 31 |
+
|
| 32 |
+
HF_CANONICAL = {
|
| 33 |
+
"hugging face hub": "Hugging Face Hub",
|
| 34 |
+
"hf hub": "Hugging Face Hub",
|
| 35 |
+
"huggingface hub": "Hugging Face Hub",
|
| 36 |
+
"huggingface.co": "Hugging Face Hub",
|
| 37 |
+
"hugging face": "Hugging Face (general)",
|
| 38 |
+
"huggingface": "Hugging Face (general)",
|
| 39 |
+
"transformers": "Transformers (library)",
|
| 40 |
+
"datasets": "Datasets (library)",
|
| 41 |
+
"diffusers": "Diffusers",
|
| 42 |
+
"accelerate": "Accelerate",
|
| 43 |
+
"peft": "PEFT",
|
| 44 |
+
"trl": "TRL",
|
| 45 |
+
"tokenizers": "Tokenizers",
|
| 46 |
+
"evaluate": "Evaluate",
|
| 47 |
+
"tgi": "TGI",
|
| 48 |
+
"text generation inference": "TGI",
|
| 49 |
+
"text-generation-inference": "TGI",
|
| 50 |
+
"tei": "TEI",
|
| 51 |
+
"text embeddings inference": "TEI",
|
| 52 |
+
"inference endpoints": "Inference Endpoints",
|
| 53 |
+
"inference api": "Inference API",
|
| 54 |
+
"serverless inference": "Inference API",
|
| 55 |
+
"spaces": "Spaces",
|
| 56 |
+
"gradio": "Gradio",
|
| 57 |
+
"autotrain": "AutoTrain",
|
| 58 |
+
"smolagents": "smolagents",
|
| 59 |
+
"smollm": "SmolLM",
|
| 60 |
+
"leaderboards": "Leaderboards",
|
| 61 |
+
"open llm leaderboard": "Leaderboards",
|
| 62 |
+
"model card": "Model Cards",
|
| 63 |
+
"model cards": "Model Cards",
|
| 64 |
+
"datasets viewer": "Datasets Viewer",
|
| 65 |
+
"dataset viewer": "Datasets Viewer",
|
| 66 |
+
"huggingface_hub": "huggingface_hub (client)",
|
| 67 |
+
"candle": "Candle",
|
| 68 |
+
"lighteval": "lightEval",
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def canon(name):
|
| 73 |
+
key = (name or "").strip().lower()
|
| 74 |
+
return HF_CANONICAL.get(key, (name or "").strip())
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def parse_listlike(s):
|
| 78 |
+
if s is None:
|
| 79 |
+
return []
|
| 80 |
+
if isinstance(s, list):
|
| 81 |
+
return s
|
| 82 |
+
s = str(s).strip()
|
| 83 |
+
if not s or s in ("[]", "null"):
|
| 84 |
+
return []
|
| 85 |
+
try:
|
| 86 |
+
return json.loads(s)
|
| 87 |
+
except Exception:
|
| 88 |
+
try:
|
| 89 |
+
return ast.literal_eval(s)
|
| 90 |
+
except Exception:
|
| 91 |
+
return []
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def parse_filename(fp):
|
| 95 |
+
base = os.path.basename(fp or "").replace(".jsonl", "")
|
| 96 |
+
parts = base.split("__")
|
| 97 |
+
while len(parts) < 4:
|
| 98 |
+
parts.append("")
|
| 99 |
+
return parts[0], parts[1], parts[2], parts[3]
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def main():
|
| 103 |
+
print(f"Loading {DATASET_ID} ...", flush=True)
|
| 104 |
+
ds = load_dataset(DATASET_ID, split="train")
|
| 105 |
+
print(f"Loaded {len(ds)} sessions", flush=True)
|
| 106 |
+
|
| 107 |
+
rows = []
|
| 108 |
+
for sess in ds:
|
| 109 |
+
tool, model, effort, thinking = parse_filename(sess["file_path"])
|
| 110 |
+
for ev in sess["traces"]:
|
| 111 |
+
if ev.get("type") != "assistant":
|
| 112 |
+
continue
|
| 113 |
+
meta = ev.get("benchmark_metadata") or {}
|
| 114 |
+
if not meta:
|
| 115 |
+
continue
|
| 116 |
+
detected = parse_listlike(meta.get("detected_products"))
|
| 117 |
+
all_mentioned = parse_listlike(meta.get("all_mentioned_products"))
|
| 118 |
+
text = ""
|
| 119 |
+
for block in ev.get("message", {}).get("content", []):
|
| 120 |
+
if isinstance(block, dict) and block.get("type") == "text":
|
| 121 |
+
text += block.get("text", "")
|
| 122 |
+
rows.append({
|
| 123 |
+
"tool": tool or meta.get("tool"),
|
| 124 |
+
"model": model,
|
| 125 |
+
"effort": effort or meta.get("effort"),
|
| 126 |
+
"thinking": thinking or meta.get("thinking"),
|
| 127 |
+
"session_id": sess["session_id"],
|
| 128 |
+
"cost_usd": float(meta.get("cost_usd") or 0.0),
|
| 129 |
+
"latency_ms": float(meta.get("latency_ms") or 0.0),
|
| 130 |
+
"query_level": meta.get("query_level"),
|
| 131 |
+
"query_category": meta.get("query_category"),
|
| 132 |
+
"has_hf_mention": bool(meta.get("has_hf_mention")),
|
| 133 |
+
"error": meta.get("error"),
|
| 134 |
+
"detected_products": [d.get("product") for d in detected if isinstance(d, dict)],
|
| 135 |
+
"n_hf_mentioned": sum(1 for m in all_mentioned if isinstance(m, dict) and m.get("type") == "hf"),
|
| 136 |
+
"n_competitors": sum(1 for m in all_mentioned if isinstance(m, dict) and m.get("type") == "competitor"),
|
| 137 |
+
"hf_products": [m.get("product") for m in all_mentioned if isinstance(m, dict) and m.get("type") == "hf"],
|
| 138 |
+
"competitor_products": [m.get("product") for m in all_mentioned if isinstance(m, dict) and m.get("type") == "competitor"],
|
| 139 |
+
"output_chars": len(text),
|
| 140 |
+
})
|
| 141 |
+
|
| 142 |
+
print(f"Total assistant turns: {len(rows)}", flush=True)
|
| 143 |
+
|
| 144 |
+
def sm(xs): return float(mean(xs)) if xs else 0.0
|
| 145 |
+
|
| 146 |
+
n = len(rows)
|
| 147 |
+
n_hf = sum(1 for r in rows if r["has_hf_mention"])
|
| 148 |
+
overall = {
|
| 149 |
+
"total_turns": n,
|
| 150 |
+
"turns_with_hf_mention": n_hf,
|
| 151 |
+
"overall_hf_mention_rate": n_hf / n if n else 0,
|
| 152 |
+
"avg_cost_usd": sm([r["cost_usd"] for r in rows]),
|
| 153 |
+
"avg_latency_ms": sm([r["latency_ms"] for r in rows]),
|
| 154 |
+
"total_cost_usd": sum(r["cost_usd"] for r in rows),
|
| 155 |
+
"avg_output_chars": sm([r["output_chars"] for r in rows]),
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
def grouped(rs):
|
| 159 |
+
return {
|
| 160 |
+
"turns": len(rs),
|
| 161 |
+
"hf_mention_rate": sum(1 for r in rs if r["has_hf_mention"]) / len(rs),
|
| 162 |
+
"avg_cost_usd": sm([r["cost_usd"] for r in rs]),
|
| 163 |
+
"avg_latency_ms": sm([r["latency_ms"] for r in rs]),
|
| 164 |
+
"avg_hf_per_turn": sm([r["n_hf_mentioned"] for r in rs]),
|
| 165 |
+
"avg_comp_per_turn": sm([r["n_competitors"] for r in rs]),
|
| 166 |
+
"avg_output_chars": sm([r["output_chars"] for r in rs]),
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
by_tool, by_model, by_thinking, by_effort = defaultdict(list), defaultdict(list), defaultdict(list), defaultdict(list)
|
| 170 |
+
by_config, by_category, by_level = defaultdict(list), defaultdict(list), defaultdict(list)
|
| 171 |
+
by_tool_model = defaultdict(list)
|
| 172 |
+
|
| 173 |
+
for r in rows:
|
| 174 |
+
by_tool[r["tool"]].append(r)
|
| 175 |
+
by_model[r["model"]].append(r)
|
| 176 |
+
by_thinking[str(r["thinking"])].append(r)
|
| 177 |
+
by_effort[str(r["effort"])].append(r)
|
| 178 |
+
by_config[f'{r["tool"]} / {r["model"]} / e={r["effort"]} / t={r["thinking"]}'].append(r)
|
| 179 |
+
by_category[r["query_category"] or "(none)"].append(r)
|
| 180 |
+
by_level[r["query_level"] or "(none)"].append(r)
|
| 181 |
+
by_tool_model[f'{r["tool"]} / {r["model"]}'].append(r)
|
| 182 |
+
|
| 183 |
+
tool_stats = {k: grouped(rs) for k, rs in by_tool.items()}
|
| 184 |
+
model_stats = {k: grouped(rs) for k, rs in by_model.items()}
|
| 185 |
+
thinking_stats = {k: grouped(rs) for k, rs in by_thinking.items()}
|
| 186 |
+
effort_stats = {k: grouped(rs) for k, rs in by_effort.items()}
|
| 187 |
+
config_stats = {k: grouped(rs) for k, rs in by_config.items()}
|
| 188 |
+
cat_stats = {k: grouped(rs) for k, rs in by_category.items()}
|
| 189 |
+
level_stats = {k: grouped(rs) for k, rs in by_level.items()}
|
| 190 |
+
tool_model_stats = {k: grouped(rs) for k, rs in by_tool_model.items()}
|
| 191 |
+
|
| 192 |
+
hf_counter = Counter()
|
| 193 |
+
for r in rows:
|
| 194 |
+
for p in set(canon(p) for p in r["hf_products"]):
|
| 195 |
+
hf_counter[p] += 1
|
| 196 |
+
top_hf = hf_counter.most_common(30)
|
| 197 |
+
|
| 198 |
+
det_counter = Counter()
|
| 199 |
+
for r in rows:
|
| 200 |
+
for d in r["detected_products"]:
|
| 201 |
+
det_counter[canon(d)] += 1
|
| 202 |
+
top_detected = det_counter.most_common(30)
|
| 203 |
+
|
| 204 |
+
comp_counter = Counter()
|
| 205 |
+
for r in rows:
|
| 206 |
+
for p in r["competitor_products"]:
|
| 207 |
+
comp_counter[p.strip()] += 1
|
| 208 |
+
top_competitors = comp_counter.most_common(40)
|
| 209 |
+
|
| 210 |
+
per_tool_hf = {}
|
| 211 |
+
for tool, rs in by_tool.items():
|
| 212 |
+
c = Counter()
|
| 213 |
+
for r in rs:
|
| 214 |
+
for p in r["hf_products"]:
|
| 215 |
+
c[canon(p)] += 1
|
| 216 |
+
per_tool_hf[tool] = c.most_common(15)
|
| 217 |
+
|
| 218 |
+
per_tool_comp = {}
|
| 219 |
+
for tool, rs in by_tool.items():
|
| 220 |
+
c = Counter()
|
| 221 |
+
for r in rs:
|
| 222 |
+
for p in r["competitor_products"]:
|
| 223 |
+
c[p.strip()] += 1
|
| 224 |
+
per_tool_comp[tool] = c.most_common(15)
|
| 225 |
+
|
| 226 |
+
visibility_share = {}
|
| 227 |
+
for tool, rs in by_tool.items():
|
| 228 |
+
hf = sum(r["n_hf_mentioned"] for r in rs)
|
| 229 |
+
comp = sum(r["n_competitors"] for r in rs)
|
| 230 |
+
visibility_share[tool] = {
|
| 231 |
+
"hf_mentions": hf,
|
| 232 |
+
"competitor_mentions": comp,
|
| 233 |
+
"share_hf": hf / (hf + comp) if (hf + comp) else 0,
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
# === Print summary ===
|
| 237 |
+
print("\n" + "="*72)
|
| 238 |
+
print("OVERALL"); print("="*72)
|
| 239 |
+
print(json.dumps(overall, indent=2, default=str))
|
| 240 |
+
|
| 241 |
+
print("\n" + "="*72); print("BY TOOL"); print("="*72)
|
| 242 |
+
for k, v in sorted(tool_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
|
| 243 |
+
print(f" {k:15s} turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} comp/turn={v['avg_comp_per_turn']:.2f} cost=${v['avg_cost_usd']:.4f} out_chars={v['avg_output_chars']:.0f}")
|
| 244 |
+
|
| 245 |
+
print("\n" + "="*72); print("BY MODEL"); print("="*72)
|
| 246 |
+
for k, v in sorted(model_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
|
| 247 |
+
print(f" {k:30s} turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} comp/turn={v['avg_comp_per_turn']:.2f} cost=${v['avg_cost_usd']:.4f}")
|
| 248 |
+
|
| 249 |
+
print("\n" + "="*72); print("BY TOOL x MODEL"); print("="*72)
|
| 250 |
+
for k, v in sorted(tool_model_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
|
| 251 |
+
print(f" {k:55s} turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} comp/turn={v['avg_comp_per_turn']:.2f}")
|
| 252 |
+
|
| 253 |
+
print("\n" + "="*72); print("HF VISIBILITY SHARE BY TOOL (HF mentions / (HF+comp))"); print("="*72)
|
| 254 |
+
for k, v in sorted(visibility_share.items(), key=lambda kv: -kv[1]["share_hf"]):
|
| 255 |
+
print(f" {k:15s} hf={v['hf_mentions']:5d} comp={v['competitor_mentions']:5d} share_hf={v['share_hf']:.1%}")
|
| 256 |
+
|
| 257 |
+
print("\n" + "="*72); print("TOP HF SURFACES MENTIONED (canonical, unique-per-turn)"); print("="*72)
|
| 258 |
+
for name, count in top_hf:
|
| 259 |
+
print(f" {count:6d} {name}")
|
| 260 |
+
|
| 261 |
+
print("\n" + "="*72); print("TOP DETECTED KEYWORDS (raw HF detection)"); print("="*72)
|
| 262 |
+
for name, count in top_detected[:25]:
|
| 263 |
+
print(f" {count:6d} {name}")
|
| 264 |
+
|
| 265 |
+
print("\n" + "="*72); print("TOP NON-HF COMPETITORS"); print("="*72)
|
| 266 |
+
for name, count in top_competitors[:30]:
|
| 267 |
+
print(f" {count:6d} {name}")
|
| 268 |
+
|
| 269 |
+
print("\n" + "="*72); print("BY CATEGORY"); print("="*72)
|
| 270 |
+
for cat, v in sorted(cat_stats.items(), key=lambda kv: -kv[1]["turns"]):
|
| 271 |
+
print(f" turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} comp/turn={v['avg_comp_per_turn']:.2f} -- {cat}")
|
| 272 |
+
|
| 273 |
+
print("\n" + "="*72); print("BY QUERY LEVEL"); print("="*72)
|
| 274 |
+
for k, v in sorted(level_stats.items(), key=lambda kv: -kv[1]["turns"]):
|
| 275 |
+
print(f" turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} -- {k}")
|
| 276 |
+
|
| 277 |
+
print("\n" + "="*72); print("BY THINKING / EFFORT"); print("="*72)
|
| 278 |
+
print("thinking:", json.dumps(thinking_stats, indent=2, default=str))
|
| 279 |
+
print("effort: ", json.dumps(effort_stats, indent=2, default=str))
|
| 280 |
+
|
| 281 |
+
print("\n" + "="*72); print("BY FULL CONFIG (sorted by HF rate)"); print("="*72)
|
| 282 |
+
for cfg, v in sorted(config_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
|
| 283 |
+
print(f" hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} cost=${v['avg_cost_usd']:.4f} lat={v['avg_latency_ms']:.0f}ms out={v['avg_output_chars']:.0f}c -- {cfg}")
|
| 284 |
+
|
| 285 |
+
print("\n" + "="*72); print("PER-TOOL TOP HF MENTIONS"); print("="*72)
|
| 286 |
+
for tool, top in per_tool_hf.items():
|
| 287 |
+
print(f"\n {tool}:")
|
| 288 |
+
for n, c in top[:10]:
|
| 289 |
+
print(f" {c:5d} {n}")
|
| 290 |
+
|
| 291 |
+
print("\n" + "="*72); print("PER-TOOL TOP COMPETITORS"); print("="*72)
|
| 292 |
+
for tool, top in per_tool_comp.items():
|
| 293 |
+
print(f"\n {tool}:")
|
| 294 |
+
for n, c in top[:10]:
|
| 295 |
+
print(f" {c:5d} {n}")
|
| 296 |
+
|
| 297 |
+
# === Save JSON output ===
|
| 298 |
+
output = {
|
| 299 |
+
"dataset": DATASET_ID,
|
| 300 |
+
"overall": overall,
|
| 301 |
+
"by_tool": tool_stats,
|
| 302 |
+
"by_model": model_stats,
|
| 303 |
+
"by_tool_model": tool_model_stats,
|
| 304 |
+
"by_thinking": thinking_stats,
|
| 305 |
+
"by_effort": effort_stats,
|
| 306 |
+
"by_config": config_stats,
|
| 307 |
+
"by_category": cat_stats,
|
| 308 |
+
"by_level": level_stats,
|
| 309 |
+
"top_hf_products": top_hf,
|
| 310 |
+
"top_detected_keywords": top_detected,
|
| 311 |
+
"top_competitors": top_competitors,
|
| 312 |
+
"per_tool_top_hf": {k: list(v) for k, v in per_tool_hf.items()},
|
| 313 |
+
"per_tool_top_competitors": {k: list(v) for k, v in per_tool_comp.items()},
|
| 314 |
+
"visibility_share": visibility_share,
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
out_path = "/tmp/analysis.json"
|
| 318 |
+
with open(out_path, "w") as f:
|
| 319 |
+
json.dump(output, f, indent=2, default=str)
|
| 320 |
+
|
| 321 |
+
try:
|
| 322 |
+
api = HfApi()
|
| 323 |
+
api.create_repo(repo_id=OUTPUT_REPO, repo_type="dataset", exist_ok=True, private=False)
|
| 324 |
+
api.upload_file(path_or_fileobj=out_path, path_in_repo="analysis.json",
|
| 325 |
+
repo_id=OUTPUT_REPO, repo_type="dataset",
|
| 326 |
+
commit_message="Add full analysis JSON")
|
| 327 |
+
print(f"\nUploaded results to https://huggingface.co/datasets/{OUTPUT_REPO}", flush=True)
|
| 328 |
+
except Exception as e:
|
| 329 |
+
print(f"Upload failed: {e}", flush=True)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
if __name__ == "__main__":
|
| 333 |
+
main()
|