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

Use pyarrow to_pylist for proper dict conversion

Browse files
Files changed (1) hide show
  1. analyze_traces.py +65 -27
analyze_traces.py CHANGED
@@ -4,11 +4,9 @@
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
@@ -17,7 +15,7 @@ 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"
@@ -101,41 +99,63 @@ def main():
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({
@@ -143,7 +163,7 @@ def main():
143
  "model": model,
144
  "effort": effort or meta.get("effort"),
145
  "thinking": thinking or meta.get("thinking"),
146
- "session_id": sess["session_id"],
147
  "cost_usd": float(meta.get("cost_usd") or 0.0),
148
  "latency_ms": float(meta.get("latency_ms") or 0.0),
149
  "query_level": meta.get("query_level"),
@@ -188,7 +208,8 @@ def main():
188
  "avg_output_chars": sm([r["output_chars"] for r in rs]),
189
  }
190
 
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:
@@ -226,7 +247,7 @@ def main():
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 = {}
232
  for tool, rs in by_tool.items():
@@ -254,7 +275,23 @@ def main():
254
  "share_hf": hf / (hf + comp) if (hf + comp) else 0,
255
  }
256
 
257
- # === Print summary ===
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
258
  print("\n" + "="*72); print("OVERALL"); print("="*72)
259
  print(json.dumps(overall, indent=2, default=str))
260
 
@@ -283,7 +320,7 @@ def main():
283
  print(f" {count:6d} {name}")
284
 
285
  print("\n" + "="*72); print("TOP NON-HF COMPETITORS"); print("="*72)
286
- for name, count in top_competitors[:30]:
287
  print(f" {count:6d} {name}")
288
 
289
  print("\n" + "="*72); print("BY CATEGORY"); print("="*72)
@@ -325,6 +362,7 @@ def main():
325
  "by_config": config_stats,
326
  "by_category": cat_stats,
327
  "by_level": level_stats,
 
328
  "top_hf_products": top_hf,
329
  "top_detected_keywords": top_detected,
330
  "top_competitors": top_competitors,
 
4
  # "pandas>=2.0",
5
  # "pyarrow>=14",
6
  # "huggingface_hub>=0.26",
 
 
7
  # ]
8
  # ///
9
+ """Analyze davidkling/hf-coding-tools-traces from the parquet export."""
10
  from __future__ import annotations
11
 
12
  import ast
 
15
  from collections import Counter, defaultdict
16
  from statistics import mean
17
 
18
+ import pyarrow.parquet as pq
19
  from huggingface_hub import HfApi, hf_hub_download
20
 
21
  DATASET_ID = "davidkling/hf-coding-tools-traces"
 
99
  filename="default/train/0000.parquet",
100
  revision="refs/convert/parquet",
101
  )
102
+ print(f"Parquet at {pq_path}", flush=True)
103
+
104
+ table = pq.read_table(pq_path)
105
+ print(f"Schema:\n{table.schema}", flush=True)
106
+ print(f"Rows: {table.num_rows}", flush=True)
107
+
108
+ # Convert to pure Python via to_pylist for max compatibility.
109
+ sessions = table.to_pylist()
110
+ print(f"Sessions converted to {len(sessions)} python dicts", flush=True)
111
+
112
+ # Diagnostic on first session
113
+ s0 = sessions[0]
114
+ print(f"First session keys: {list(s0.keys())}", flush=True)
115
+ traces0 = s0.get("traces") or []
116
+ print(f"First session: {len(traces0)} trace events; type of first ev = {type(traces0[0]).__name__}", flush=True)
117
+ if traces0:
118
+ ev0 = traces0[0]
119
+ if isinstance(ev0, str):
120
+ print("Traces are JSON strings — will parse.", flush=True)
121
+ elif isinstance(ev0, dict):
122
+ print(f"First event keys: {list(ev0.keys())[:12]}", flush=True)
123
+ print(f"First event type field: {ev0.get('type')}", flush=True)
124
 
125
  rows = []
126
+ for sess in sessions:
127
+ tool, model, effort, thinking = parse_filename(sess.get("file_path", ""))
128
+ traces = sess.get("traces") or []
129
+ for raw in traces:
130
+ ev = raw
131
+ if isinstance(ev, str):
 
 
 
132
  try:
133
+ ev = json.loads(ev)
134
  except Exception:
135
  continue
136
+ if not isinstance(ev, dict):
137
+ continue
138
  if ev.get("type") != "assistant":
139
  continue
140
+ meta = ev.get("benchmark_metadata")
141
  if isinstance(meta, str):
142
  try:
143
  meta = json.loads(meta)
144
  except Exception:
145
+ meta = None
146
  if not meta:
147
  continue
148
  detected = parse_listlike(meta.get("detected_products"))
149
  all_mentioned = parse_listlike(meta.get("all_mentioned_products"))
150
  text = ""
151
+ msg = ev.get("message") or {}
152
+ if isinstance(msg, str):
153
+ try:
154
+ msg = json.loads(msg)
155
+ except Exception:
156
+ msg = {}
157
  if isinstance(msg, dict):
158
+ for block in (msg.get("content") or []):
159
  if isinstance(block, dict) and block.get("type") == "text":
160
  text += block.get("text", "") or ""
161
  rows.append({
 
163
  "model": model,
164
  "effort": effort or meta.get("effort"),
165
  "thinking": thinking or meta.get("thinking"),
166
+ "session_id": sess.get("session_id"),
167
  "cost_usd": float(meta.get("cost_usd") or 0.0),
168
  "latency_ms": float(meta.get("latency_ms") or 0.0),
169
  "query_level": meta.get("query_level"),
 
208
  "avg_output_chars": sm([r["output_chars"] for r in rs]),
209
  }
210
 
211
+ by_tool, by_model = defaultdict(list), defaultdict(list)
212
+ by_thinking, by_effort = defaultdict(list), defaultdict(list)
213
  by_config, by_category, by_level = defaultdict(list), defaultdict(list), defaultdict(list)
214
  by_tool_model = defaultdict(list)
215
  for r in rows:
 
247
  for r in rows:
248
  for p in r["competitor_products"]:
249
  comp_counter[(p or "").strip()] += 1
250
+ top_competitors = comp_counter.most_common(50)
251
 
252
  per_tool_hf = {}
253
  for tool, rs in by_tool.items():
 
275
  "share_hf": hf / (hf + comp) if (hf + comp) else 0,
276
  }
277
 
278
+ # Per-category x per-tool breakdown for top categories
279
+ top_cats = sorted(cat_stats.items(), key=lambda kv: -kv[1]["turns"])[:12]
280
+ cat_x_tool = {}
281
+ for cat_name, _ in top_cats:
282
+ cat_x_tool[cat_name] = {}
283
+ cat_rows = by_category[cat_name]
284
+ local_by_tool = defaultdict(list)
285
+ for r in cat_rows:
286
+ local_by_tool[r["tool"]].append(r)
287
+ for tool, rs in local_by_tool.items():
288
+ cat_x_tool[cat_name][tool] = {
289
+ "turns": len(rs),
290
+ "hf_rate": sum(1 for r in rs if r["has_hf_mention"]) / len(rs),
291
+ "hf_per_turn": sm([r["n_hf_mentioned"] for r in rs]),
292
+ }
293
+
294
+ # === Print ===
295
  print("\n" + "="*72); print("OVERALL"); print("="*72)
296
  print(json.dumps(overall, indent=2, default=str))
297
 
 
320
  print(f" {count:6d} {name}")
321
 
322
  print("\n" + "="*72); print("TOP NON-HF COMPETITORS"); print("="*72)
323
+ for name, count in top_competitors[:35]:
324
  print(f" {count:6d} {name}")
325
 
326
  print("\n" + "="*72); print("BY CATEGORY"); print("="*72)
 
362
  "by_config": config_stats,
363
  "by_category": cat_stats,
364
  "by_level": level_stats,
365
+ "cat_x_tool": cat_x_tool,
366
  "top_hf_products": top_hf,
367
  "top_detected_keywords": top_detected,
368
  "top_competitors": top_competitors,