| |
| |
| |
| |
| |
| |
| |
| |
| """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) |
|
|
| |
| sessions = table.to_pylist() |
| print(f"Sessions converted to {len(sessions)} python dicts", flush=True) |
|
|
| |
| 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, |
| } |
|
|
| |
| 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("\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() |
|
|