evalstate HF Staff commited on
Commit
050cae0
·
verified ·
1 Parent(s): 9d92df5

Use parquet export directly

Browse files
Files changed (1) hide show
  1. analyze_traces.py +49 -30
analyze_traces.py CHANGED
@@ -1,30 +1,24 @@
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"
@@ -100,25 +94,50 @@ def parse_filename(fp):
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,
@@ -140,6 +159,9 @@ def main():
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
 
@@ -169,7 +191,6 @@ def main():
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)
@@ -204,7 +225,7 @@ def main():
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 = {}
@@ -220,7 +241,7 @@ def main():
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 = {}
@@ -234,8 +255,7 @@ def main():
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)
@@ -250,15 +270,15 @@ def main():
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
 
@@ -294,7 +314,6 @@ def main():
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,
 
1
  # /// script
2
  # requires-python = ">=3.11"
3
  # dependencies = [
 
4
  # "pandas>=2.0",
5
+ # "pyarrow>=14",
6
  # "huggingface_hub>=0.26",
7
+ # "fsspec",
8
+ # "requests",
9
  # ]
10
  # ///
11
+ """Analyze davidkling/hf-coding-tools-traces."""
 
 
 
 
 
 
 
 
12
  from __future__ import annotations
13
 
14
  import ast
15
  import json
16
  import os
17
  from collections import Counter, defaultdict
18
+ from statistics import mean
19
 
20
+ import pandas as pd
21
+ from huggingface_hub import HfApi, hf_hub_download
22
 
23
  DATASET_ID = "davidkling/hf-coding-tools-traces"
24
  OUTPUT_REPO = "evalstate/hf-coding-traces-analysis"
 
94
 
95
 
96
  def main():
97
+ print(f"Downloading parquet from {DATASET_ID} ...", flush=True)
98
+ pq_path = hf_hub_download(
99
+ repo_id=DATASET_ID,
100
+ repo_type="dataset",
101
+ filename="default/train/0000.parquet",
102
+ revision="refs/convert/parquet",
103
+ )
104
+ print(f"Loaded parquet at {pq_path}", flush=True)
105
+
106
+ df = pd.read_parquet(pq_path)
107
+ print(f"Loaded {len(df)} sessions; columns = {list(df.columns)}", flush=True)
108
 
109
  rows = []
110
+ for _, sess in df.iterrows():
111
  tool, model, effort, thinking = parse_filename(sess["file_path"])
112
+ traces = sess["traces"]
113
+ # `traces` is a list/array of JSON-serializable dicts (already parsed by pyarrow)
114
+ if isinstance(traces, str):
115
+ traces = json.loads(traces)
116
+ for ev in traces:
117
+ # ev might be a dict or a numpy/pyarrow scalar
118
+ if not isinstance(ev, dict):
119
+ try:
120
+ ev = dict(ev)
121
+ except Exception:
122
+ continue
123
  if ev.get("type") != "assistant":
124
  continue
125
  meta = ev.get("benchmark_metadata") or {}
126
+ if isinstance(meta, str):
127
+ try:
128
+ meta = json.loads(meta)
129
+ except Exception:
130
+ meta = {}
131
  if not meta:
132
  continue
133
  detected = parse_listlike(meta.get("detected_products"))
134
  all_mentioned = parse_listlike(meta.get("all_mentioned_products"))
135
  text = ""
136
+ msg = ev.get("message", {})
137
+ if isinstance(msg, dict):
138
+ for block in msg.get("content", []) or []:
139
+ if isinstance(block, dict) and block.get("type") == "text":
140
+ text += block.get("text", "") or ""
141
  rows.append({
142
  "tool": tool or meta.get("tool"),
143
  "model": model,
 
159
  })
160
 
161
  print(f"Total assistant turns: {len(rows)}", flush=True)
162
+ if not rows:
163
+ print("WARNING: zero rows extracted — diagnose schema.", flush=True)
164
+ return
165
 
166
  def sm(xs): return float(mean(xs)) if xs else 0.0
167
 
 
191
  by_tool, by_model, by_thinking, by_effort = defaultdict(list), defaultdict(list), defaultdict(list), defaultdict(list)
192
  by_config, by_category, by_level = defaultdict(list), defaultdict(list), defaultdict(list)
193
  by_tool_model = defaultdict(list)
 
194
  for r in rows:
195
  by_tool[r["tool"]].append(r)
196
  by_model[r["model"]].append(r)
 
225
  comp_counter = Counter()
226
  for r in rows:
227
  for p in r["competitor_products"]:
228
+ comp_counter[(p or "").strip()] += 1
229
  top_competitors = comp_counter.most_common(40)
230
 
231
  per_tool_hf = {}
 
241
  c = Counter()
242
  for r in rs:
243
  for p in r["competitor_products"]:
244
+ c[(p or "").strip()] += 1
245
  per_tool_comp[tool] = c.most_common(15)
246
 
247
  visibility_share = {}
 
255
  }
256
 
257
  # === Print summary ===
258
+ print("\n" + "="*72); print("OVERALL"); print("="*72)
 
259
  print(json.dumps(overall, indent=2, default=str))
260
 
261
  print("\n" + "="*72); print("BY TOOL"); print("="*72)
 
270
  for k, v in sorted(tool_model_stats.items(), key=lambda kv: -kv[1]["hf_mention_rate"]):
271
  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}")
272
 
273
+ print("\n" + "="*72); print("HF VISIBILITY SHARE BY TOOL"); print("="*72)
274
  for k, v in sorted(visibility_share.items(), key=lambda kv: -kv[1]["share_hf"]):
275
  print(f" {k:15s} hf={v['hf_mentions']:5d} comp={v['competitor_mentions']:5d} share_hf={v['share_hf']:.1%}")
276
 
277
+ print("\n" + "="*72); print("TOP HF SURFACES MENTIONED"); print("="*72)
278
  for name, count in top_hf:
279
  print(f" {count:6d} {name}")
280
 
281
+ print("\n" + "="*72); print("TOP DETECTED KEYWORDS (HF auto-detect)"); print("="*72)
282
  for name, count in top_detected[:25]:
283
  print(f" {count:6d} {name}")
284
 
 
314
  for n, c in top[:10]:
315
  print(f" {c:5d} {n}")
316
 
 
317
  output = {
318
  "dataset": DATASET_ID,
319
  "overall": overall,