File size: 15,817 Bytes
9d92df5 050cae0 9d92df5 02dcb08 9d92df5 050cae0 9d92df5 02dcb08 050cae0 9d92df5 050cae0 02dcb08 9d92df5 02dcb08 050cae0 02dcb08 050cae0 02dcb08 9d92df5 02dcb08 050cae0 02dcb08 9d92df5 02dcb08 050cae0 02dcb08 050cae0 9d92df5 02dcb08 9d92df5 050cae0 9d92df5 02dcb08 9d92df5 050cae0 02dcb08 9d92df5 050cae0 9d92df5 02dcb08 050cae0 9d92df5 050cae0 9d92df5 050cae0 9d92df5 050cae0 9d92df5 02dcb08 9d92df5 02dcb08 9d92df5 | 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | # /// script
# requires-python = ">=3.11"
# dependencies = [
# "pandas>=2.0",
# "pyarrow>=14",
# "huggingface_hub>=0.26",
# ]
# ///
"""Analyze davidkling/hf-coding-tools-traces from the parquet export."""
from __future__ import annotations
import ast
import json
import os
from collections import Counter, defaultdict
from statistics import mean
import pyarrow.parquet as pq
from huggingface_hub import HfApi, hf_hub_download
DATASET_ID = "davidkling/hf-coding-tools-traces"
OUTPUT_REPO = "evalstate/hf-coding-traces-analysis"
HF_CANONICAL = {
"hugging face hub": "Hugging Face Hub",
"hf hub": "Hugging Face Hub",
"huggingface hub": "Hugging Face Hub",
"huggingface.co": "Hugging Face Hub",
"hugging face": "Hugging Face (general)",
"huggingface": "Hugging Face (general)",
"transformers": "Transformers (library)",
"datasets": "Datasets (library)",
"diffusers": "Diffusers",
"accelerate": "Accelerate",
"peft": "PEFT",
"trl": "TRL",
"tokenizers": "Tokenizers",
"evaluate": "Evaluate",
"tgi": "TGI",
"text generation inference": "TGI",
"text-generation-inference": "TGI",
"tei": "TEI",
"text embeddings inference": "TEI",
"inference endpoints": "Inference Endpoints",
"inference api": "Inference API",
"serverless inference": "Inference API",
"spaces": "Spaces",
"gradio": "Gradio",
"autotrain": "AutoTrain",
"smolagents": "smolagents",
"smollm": "SmolLM",
"leaderboards": "Leaderboards",
"open llm leaderboard": "Leaderboards",
"model card": "Model Cards",
"model cards": "Model Cards",
"datasets viewer": "Datasets Viewer",
"dataset viewer": "Datasets Viewer",
"huggingface_hub": "huggingface_hub (client)",
"candle": "Candle",
"lighteval": "lightEval",
}
def canon(name):
key = (name or "").strip().lower()
return HF_CANONICAL.get(key, (name or "").strip())
def parse_listlike(s):
if s is None:
return []
if isinstance(s, list):
return s
s = str(s).strip()
if not s or s in ("[]", "null"):
return []
try:
return json.loads(s)
except Exception:
try:
return ast.literal_eval(s)
except Exception:
return []
def parse_filename(fp):
base = os.path.basename(fp or "").replace(".jsonl", "")
parts = base.split("__")
while len(parts) < 4:
parts.append("")
return parts[0], parts[1], parts[2], parts[3]
def main():
print(f"Downloading parquet from {DATASET_ID} ...", flush=True)
pq_path = hf_hub_download(
repo_id=DATASET_ID,
repo_type="dataset",
filename="default/train/0000.parquet",
revision="refs/convert/parquet",
)
print(f"Parquet at {pq_path}", flush=True)
table = pq.read_table(pq_path)
print(f"Schema:\n{table.schema}", flush=True)
print(f"Rows: {table.num_rows}", flush=True)
# Convert to pure Python via to_pylist for max compatibility.
sessions = table.to_pylist()
print(f"Sessions converted to {len(sessions)} python dicts", flush=True)
# Diagnostic on first session
s0 = sessions[0]
print(f"First session keys: {list(s0.keys())}", flush=True)
traces0 = s0.get("traces") or []
print(f"First session: {len(traces0)} trace events; type of first ev = {type(traces0[0]).__name__}", flush=True)
if traces0:
ev0 = traces0[0]
if isinstance(ev0, str):
print("Traces are JSON strings — will parse.", flush=True)
elif isinstance(ev0, dict):
print(f"First event keys: {list(ev0.keys())[:12]}", flush=True)
print(f"First event type field: {ev0.get('type')}", flush=True)
rows = []
for sess in sessions:
tool, model, effort, thinking = parse_filename(sess.get("file_path", ""))
traces = sess.get("traces") or []
for raw in traces:
ev = raw
if isinstance(ev, str):
try:
ev = json.loads(ev)
except Exception:
continue
if not isinstance(ev, dict):
continue
if ev.get("type") != "assistant":
continue
meta = ev.get("benchmark_metadata")
if isinstance(meta, str):
try:
meta = json.loads(meta)
except Exception:
meta = None
if not meta:
continue
detected = parse_listlike(meta.get("detected_products"))
all_mentioned = parse_listlike(meta.get("all_mentioned_products"))
text = ""
msg = ev.get("message") or {}
if isinstance(msg, str):
try:
msg = json.loads(msg)
except Exception:
msg = {}
if isinstance(msg, dict):
for block in (msg.get("content") or []):
if isinstance(block, dict) and block.get("type") == "text":
text += block.get("text", "") or ""
rows.append({
"tool": tool or meta.get("tool"),
"model": model,
"effort": effort or meta.get("effort"),
"thinking": thinking or meta.get("thinking"),
"session_id": sess.get("session_id"),
"cost_usd": float(meta.get("cost_usd") or 0.0),
"latency_ms": float(meta.get("latency_ms") or 0.0),
"query_level": meta.get("query_level"),
"query_category": meta.get("query_category"),
"has_hf_mention": bool(meta.get("has_hf_mention")),
"error": meta.get("error"),
"detected_products": [d.get("product") for d in detected if isinstance(d, dict)],
"n_hf_mentioned": sum(1 for m in all_mentioned if isinstance(m, dict) and m.get("type") == "hf"),
"n_competitors": sum(1 for m in all_mentioned if isinstance(m, dict) and m.get("type") == "competitor"),
"hf_products": [m.get("product") for m in all_mentioned if isinstance(m, dict) and m.get("type") == "hf"],
"competitor_products": [m.get("product") for m in all_mentioned if isinstance(m, dict) and m.get("type") == "competitor"],
"output_chars": len(text),
})
print(f"Total assistant turns: {len(rows)}", flush=True)
if not rows:
print("WARNING: zero rows extracted — diagnose schema.", flush=True)
return
def sm(xs): return float(mean(xs)) if xs else 0.0
n = len(rows)
n_hf = sum(1 for r in rows if r["has_hf_mention"])
overall = {
"total_turns": n,
"turns_with_hf_mention": n_hf,
"overall_hf_mention_rate": n_hf / n if n else 0,
"avg_cost_usd": sm([r["cost_usd"] for r in rows]),
"avg_latency_ms": sm([r["latency_ms"] for r in rows]),
"total_cost_usd": sum(r["cost_usd"] for r in rows),
"avg_output_chars": sm([r["output_chars"] for r in rows]),
}
def grouped(rs):
return {
"turns": len(rs),
"hf_mention_rate": sum(1 for r in rs if r["has_hf_mention"]) / len(rs),
"avg_cost_usd": sm([r["cost_usd"] for r in rs]),
"avg_latency_ms": sm([r["latency_ms"] for r in rs]),
"avg_hf_per_turn": sm([r["n_hf_mentioned"] for r in rs]),
"avg_comp_per_turn": sm([r["n_competitors"] for r in rs]),
"avg_output_chars": sm([r["output_chars"] for r in rs]),
}
by_tool, by_model = defaultdict(list), defaultdict(list)
by_thinking, by_effort = defaultdict(list), defaultdict(list)
by_config, by_category, by_level = defaultdict(list), defaultdict(list), defaultdict(list)
by_tool_model = defaultdict(list)
for r in rows:
by_tool[r["tool"]].append(r)
by_model[r["model"]].append(r)
by_thinking[str(r["thinking"])].append(r)
by_effort[str(r["effort"])].append(r)
by_config[f'{r["tool"]} / {r["model"]} / e={r["effort"]} / t={r["thinking"]}'].append(r)
by_category[r["query_category"] or "(none)"].append(r)
by_level[r["query_level"] or "(none)"].append(r)
by_tool_model[f'{r["tool"]} / {r["model"]}'].append(r)
tool_stats = {k: grouped(rs) for k, rs in by_tool.items()}
model_stats = {k: grouped(rs) for k, rs in by_model.items()}
thinking_stats = {k: grouped(rs) for k, rs in by_thinking.items()}
effort_stats = {k: grouped(rs) for k, rs in by_effort.items()}
config_stats = {k: grouped(rs) for k, rs in by_config.items()}
cat_stats = {k: grouped(rs) for k, rs in by_category.items()}
level_stats = {k: grouped(rs) for k, rs in by_level.items()}
tool_model_stats = {k: grouped(rs) for k, rs in by_tool_model.items()}
hf_counter = Counter()
for r in rows:
for p in set(canon(p) for p in r["hf_products"]):
hf_counter[p] += 1
top_hf = hf_counter.most_common(30)
det_counter = Counter()
for r in rows:
for d in r["detected_products"]:
det_counter[canon(d)] += 1
top_detected = det_counter.most_common(30)
comp_counter = Counter()
for r in rows:
for p in r["competitor_products"]:
comp_counter[(p or "").strip()] += 1
top_competitors = comp_counter.most_common(50)
per_tool_hf = {}
for tool, rs in by_tool.items():
c = Counter()
for r in rs:
for p in r["hf_products"]:
c[canon(p)] += 1
per_tool_hf[tool] = c.most_common(15)
per_tool_comp = {}
for tool, rs in by_tool.items():
c = Counter()
for r in rs:
for p in r["competitor_products"]:
c[(p or "").strip()] += 1
per_tool_comp[tool] = c.most_common(15)
visibility_share = {}
for tool, rs in by_tool.items():
hf = sum(r["n_hf_mentioned"] for r in rs)
comp = sum(r["n_competitors"] for r in rs)
visibility_share[tool] = {
"hf_mentions": hf,
"competitor_mentions": comp,
"share_hf": hf / (hf + comp) if (hf + comp) else 0,
}
# Per-category x per-tool breakdown for top categories
top_cats = sorted(cat_stats.items(), key=lambda kv: -kv[1]["turns"])[:12]
cat_x_tool = {}
for cat_name, _ in top_cats:
cat_x_tool[cat_name] = {}
cat_rows = by_category[cat_name]
local_by_tool = defaultdict(list)
for r in cat_rows:
local_by_tool[r["tool"]].append(r)
for tool, rs in local_by_tool.items():
cat_x_tool[cat_name][tool] = {
"turns": len(rs),
"hf_rate": sum(1 for r in rs if r["has_hf_mention"]) / len(rs),
"hf_per_turn": sm([r["n_hf_mentioned"] for r in rs]),
}
# === Print ===
print("\n" + "="*72); print("OVERALL"); print("="*72)
print(json.dumps(overall, indent=2, default=str))
print("\n" + "="*72); print("BY TOOL"); print("="*72)
for k, v in sorted(tool_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
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}")
print("\n" + "="*72); print("BY MODEL"); print("="*72)
for k, v in sorted(model_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
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}")
print("\n" + "="*72); print("BY TOOL x MODEL"); print("="*72)
for k, v in sorted(tool_model_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
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}")
print("\n" + "="*72); print("HF VISIBILITY SHARE BY TOOL"); print("="*72)
for k, v in sorted(visibility_share.items(), key=lambda kv: -kv[1]["share_hf"]):
print(f" {k:15s} hf={v['hf_mentions']:5d} comp={v['competitor_mentions']:5d} share_hf={v['share_hf']:.1%}")
print("\n" + "="*72); print("TOP HF SURFACES MENTIONED"); print("="*72)
for name, count in top_hf:
print(f" {count:6d} {name}")
print("\n" + "="*72); print("TOP DETECTED KEYWORDS (HF auto-detect)"); print("="*72)
for name, count in top_detected[:25]:
print(f" {count:6d} {name}")
print("\n" + "="*72); print("TOP NON-HF COMPETITORS"); print("="*72)
for name, count in top_competitors[:35]:
print(f" {count:6d} {name}")
print("\n" + "="*72); print("BY CATEGORY"); print("="*72)
for cat, v in sorted(cat_stats.items(), key=lambda kv: -kv[1]["turns"]):
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}")
print("\n" + "="*72); print("BY QUERY LEVEL"); print("="*72)
for k, v in sorted(level_stats.items(), key=lambda kv: -kv[1]["turns"]):
print(f" turns={v['turns']:5d} hf_rate={v['hf_mention_rate']:.2%} hf/turn={v['avg_hf_per_turn']:.2f} -- {k}")
print("\n" + "="*72); print("BY THINKING / EFFORT"); print("="*72)
print("thinking:", json.dumps(thinking_stats, indent=2, default=str))
print("effort: ", json.dumps(effort_stats, indent=2, default=str))
print("\n" + "="*72); print("BY FULL CONFIG (sorted by HF rate)"); print("="*72)
for cfg, v in sorted(config_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
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}")
print("\n" + "="*72); print("PER-TOOL TOP HF MENTIONS"); print("="*72)
for tool, top in per_tool_hf.items():
print(f"\n {tool}:")
for n, c in top[:10]:
print(f" {c:5d} {n}")
print("\n" + "="*72); print("PER-TOOL TOP COMPETITORS"); print("="*72)
for tool, top in per_tool_comp.items():
print(f"\n {tool}:")
for n, c in top[:10]:
print(f" {c:5d} {n}")
output = {
"dataset": DATASET_ID,
"overall": overall,
"by_tool": tool_stats,
"by_model": model_stats,
"by_tool_model": tool_model_stats,
"by_thinking": thinking_stats,
"by_effort": effort_stats,
"by_config": config_stats,
"by_category": cat_stats,
"by_level": level_stats,
"cat_x_tool": cat_x_tool,
"top_hf_products": top_hf,
"top_detected_keywords": top_detected,
"top_competitors": top_competitors,
"per_tool_top_hf": {k: list(v) for k, v in per_tool_hf.items()},
"per_tool_top_competitors": {k: list(v) for k, v in per_tool_comp.items()},
"visibility_share": visibility_share,
}
out_path = "/tmp/analysis.json"
with open(out_path, "w") as f:
json.dump(output, f, indent=2, default=str)
try:
api = HfApi()
api.create_repo(repo_id=OUTPUT_REPO, repo_type="dataset", exist_ok=True, private=False)
api.upload_file(path_or_fileobj=out_path, path_in_repo="analysis.json",
repo_id=OUTPUT_REPO, repo_type="dataset",
commit_message="Add full analysis JSON")
print(f"\nUploaded results to https://huggingface.co/datasets/{OUTPUT_REPO}", flush=True)
except Exception as e:
print(f"Upload failed: {e}", flush=True)
if __name__ == "__main__":
main()
|