"""Build the ShareChat history (0-40K) / replay (40K-50K) splits and the replay trace from the public mirror anoynsharechat/sharechat, following arXiv 2611.09715v1 App. A.4. Deviations from the authors' pipeline (their repo has no ShareChat loader): - source is the public mirror, not gated tucnguyen/ShareChat - platform set and timestamp column are chosen here (see --configs, --ts-column) - conversations are sorted by first-turn timestamp, then split positionally Trace arrival process matches iac.data.build_trace defaults: Poisson starts at --rate (default 3.0/s, seed 0), original inter-turn gaps, 1800 s session timeout. """ from __future__ import annotations import argparse import json import os import sys from datetime import datetime, timezone import numpy as np REPO_DIR = os.environ.get("IAC_REPO", os.path.join(os.path.dirname(os.path.abspath(__file__)), "iac-repo")) sys.path.insert(0, REPO_DIR) from iac.data import ( # noqa: E402 MAX_UNIX_TIMESTAMP, DatasetSplits, Split, build_trace, make_candidate, select_splits, trace_summary, write_splits, ) def parse_ts(value): if value is None: return None if isinstance(value, datetime): dt = value else: s = str(value).strip() if not s: return None try: f = float(s[3:] if s.startswith("ts:") else s) return f if 0.0 < f <= MAX_UNIX_TIMESTAMP else None except ValueError: pass try: dt = datetime.fromisoformat(s.replace("Z", "+00:00").replace("ts:", "")) except ValueError: return None if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc) unix = dt.timestamp() return unix if 0.0 < unix <= MAX_UNIX_TIMESTAMP else None def iter_rows(config: str, batch_size: int = 4096): from datasets import load_dataset ds = load_dataset("anoynsharechat/sharechat", config, split="train") cols = ds.column_names for batch in ds.with_format("pandas").iter(batch_size): records = batch.to_dict("records") for r in records: yield cols, r def build_candidates(configs, ts_column, ts_role): """One candidate per conversation; messages ordered by message_index.""" by_conv: dict[str, dict] = {} cols_seen: dict[str, list] = {} for config in configs: for cols, r in iter_rows(config): cols_seen[config] = cols conv_id = f"{config}:{r['url']}" conv = by_conv.get(conv_id) if conv is None: conv = by_conv[conv_id] = {"config": config, "rows": []} conv["rows"].append(r) print(f"loaded {len(by_conv)} conversations from {configs}", flush=True) for config, cols in cols_seen.items(): print(f" {config} columns: {cols}", flush=True) candidates = [] for conv_id, conv in sorted(by_conv.items()): rows = sorted(conv["rows"], key=lambda r: r.get("message_index") or 0) messages = [ ( r.get("role"), r.get("plain_text"), parse_ts(r.get(ts_column)) if ts_column else None, ) for r in rows ] candidates.append(make_candidate(0, conv_id, conv["config"], messages, ts_role, None)) return candidates def main(): ap = argparse.ArgumentParser() ap.add_argument("--configs", default="chatgpt,grok,claude,gemini,perplexity") ap.add_argument("--ts-column", default="message_create_time") ap.add_argument("--ts-role", default="user", choices=["user", "assistant"]) ap.add_argument("--out", default="data/splits/sharechat") ap.add_argument("--traces", default="traces/sharechat_r3") ap.add_argument("--rate", type=float, default=3.0) ap.add_argument("--seed", type=int, default=0) ap.add_argument("--history", type=int, nargs=2, default=[0, 40000]) ap.add_argument("--replay", type=int, nargs=2, default=[40000, 50000]) args = ap.parse_args() candidates = build_candidates(args.configs.split(","), args.ts_column, args.ts_role) kept = [c for c in candidates if c.conversation is not None] dropped = {} for c in candidates: if c.conversation is None: dropped[c.drop_reason] = dropped.get(c.drop_reason, 0) + 1 print(f"kept {len(kept)} candidates, dropped {dropped}", flush=True) if len(kept) < args.replay[1]: raise SystemExit( f"only {len(kept)} timestamped conversations; cannot fill replay split to {args.replay[1]}" ) kept.sort(key=lambda c: c.conversation.turns[0].timestamp) stream = iter(kept) splits = select_splits(stream, {"history": tuple(args.history), "replay": tuple(args.replay)}) ds = DatasetSplits("sharechat", {"mirror": "anoynsharechat/sharechat", "ts_column": args.ts_column, "ts_role": args.ts_role, "configs": args.configs}, splits) manifest = write_splits(ds, args.out) for name, s in manifest["splits"].items(): print(f"{name}: {s['conversations']} convs, {s['requests']} requests, " f"mean_turns {s.get('mean_turns')}", flush=True) os.makedirs(args.traces, exist_ok=True) trace = build_trace(ds.splits["replay"].conversations, rate=args.rate, seed=args.seed) trace.save(args.traces) with open(os.path.join(args.traces, "summary.json"), "w") as f: json.dump(trace_summary(trace), f, indent=1) print(json.dumps(trace_summary(trace), indent=1), flush=True) if __name__ == "__main__": main()