| """Convert a5_user_data.json -> per-user txt, then plot token length distribution. |
| |
| Usage: |
| python /mnt/train-gui-agent/zhangxinyuan/data_mem/output/export_and_plot_lengths.py |
| """ |
|
|
| import json |
| import os |
| import glob |
| import statistics |
|
|
| |
| A5_PATH = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/a5_user_data.json" |
| USER_TEXT_DIR = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/user_text" |
| MODEL_PATH = "/mnt/train-gui-agent/zhangzeyu/models/Qwen3-8B" |
| OUT_DIR = "/mnt/train-gui-agent/zhangxinyuan/data_mem/output/eval" |
|
|
|
|
| def format_session(session): |
| """Format a single session as plain text.""" |
| lines = [f"[Session: {session.get('timestamp', 'unknown')}]"] |
| for turn in session.get("turns", []): |
| content = turn.get("content") |
| if not content: |
| continue |
| role = turn.get("role", "unknown") |
| |
| if role.startswith("assistant"): |
| role = "Assistant" |
| elif role.startswith("user"): |
| role = "User" |
| else: |
| role = role.capitalize() |
| lines.append(f"{role}: {content}") |
| return "\n".join(lines) |
|
|
|
|
| def step1_export_txt(): |
| """a5_user_data.json -> user_text/{user_id}.txt""" |
| print(f"[Step 1] Loading {A5_PATH}") |
| with open(A5_PATH, "r", encoding="utf-8") as f: |
| data = json.load(f) |
| print(f" {len(data)} users") |
|
|
| os.makedirs(USER_TEXT_DIR, exist_ok=True) |
| count = 0 |
| for user in data: |
| user_id = user["user_id"] |
| sessions = user.get("all_sessions", []) |
| if not sessions: |
| continue |
|
|
| sessions_sorted = sorted(sessions, key=lambda s: s.get("timestamp", "")) |
| full_text = "\n\n".join(format_session(s) for s in sessions_sorted) |
|
|
| out_path = os.path.join(USER_TEXT_DIR, f"{user_id}.txt") |
| with open(out_path, "w", encoding="utf-8") as f: |
| f.write(full_text) |
| count += 1 |
|
|
| print(f" Exported {count} user txt files -> {USER_TEXT_DIR}/") |
| return count |
|
|
|
|
| def step2_token_stats(): |
| """Tokenize all txt files and plot distribution.""" |
| from transformers import AutoTokenizer |
| import matplotlib |
| matplotlib.use("Agg") |
| import matplotlib.pyplot as plt |
|
|
| print(f"\n[Step 2] Loading tokenizer from {MODEL_PATH}") |
| tok = AutoTokenizer.from_pretrained(MODEL_PATH) |
|
|
| files = sorted(glob.glob(os.path.join(USER_TEXT_DIR, "*.txt"))) |
| print(f" Tokenizing {len(files)} files...") |
|
|
| counts = [] |
| for f in files: |
| txt = open(f, encoding="utf-8").read() |
| counts.append(len(tok.encode(txt, add_special_tokens=False))) |
|
|
| |
| s = sorted(counts) |
| n = len(s) |
| def pct(p): |
| return s[min(n - 1, int(p / 100 * n))] |
|
|
| stats = { |
| "n": n, |
| "min": s[0], |
| "max": s[-1], |
| "mean": round(statistics.mean(s), 1), |
| "median": s[n // 2], |
| "p10": pct(10), |
| "p25": pct(25), |
| "p75": pct(75), |
| "p90": pct(90), |
| "p95": pct(95), |
| "std": round(statistics.pstdev(s), 1), |
| } |
|
|
| print(f"\n === Token Length Stats ===") |
| for k, v in stats.items(): |
| print(f" {k}: {v:,}" if isinstance(v, int) else f" {k}: {v}") |
|
|
| |
| os.makedirs(OUT_DIR, exist_ok=True) |
|
|
| fig, ax = plt.subplots(figsize=(10, 5)) |
| ax.hist(counts, bins=40, color="#4C72B0", edgecolor="white", alpha=0.85) |
| ax.axvline(stats["median"], color="black", ls="--", lw=1.5, |
| label=f"median={stats['median']:,}") |
| ax.axvline(stats["mean"], color="dimgray", ls=":", lw=1.5, |
| label=f"mean={stats['mean']:,.0f}") |
| ax.set_title(f"User history token length (n={n}, Qwen3-8B tokens)\n" |
| f"zhangxinyuan a5_user_data") |
| ax.set_xlabel("tokens per user") |
| ax.set_ylabel("number of users") |
| ax.legend() |
| fig.tight_layout() |
|
|
| out_png = os.path.join(OUT_DIR, "user_history_tokens.png") |
| fig.savefig(out_png, dpi=130) |
| plt.close(fig) |
| print(f"\n Plot saved -> {out_png}") |
|
|
| |
| out_json = os.path.join(OUT_DIR, "user_history_tokens.json") |
| with open(out_json, "w") as f: |
| json.dump({"stats": stats, "raw_counts": counts}, f, indent=2) |
| print(f" Stats saved -> {out_json}") |
|
|
|
|
| if __name__ == "__main__": |
| step1_export_txt() |
| step2_token_stats() |
|
|