| import json |
| from transformers import AutoTokenizer |
|
|
| input_path = "/root/test/weitiao/data_process_bq/data/train2_closed.json" |
|
|
| |
| tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-3B", trust_remote_code=True) |
|
|
| def count_tokens(text): |
| if text is None: |
| return 0 |
| if not isinstance(text, str): |
| text = str(text) |
| return len(tokenizer.encode(text)) |
|
|
| def process_item(item): |
| |
| content_tokens = 0 |
| content = item.get("content", []) |
|
|
| if isinstance(content, list): |
| for msg in content: |
| if isinstance(msg, dict) and "content" in msg: |
| content_tokens += count_tokens(msg["content"]) |
| elif isinstance(msg, str): |
| content_tokens += count_tokens(msg) |
| elif isinstance(content, str): |
| content_tokens += count_tokens(content) |
|
|
| |
| chosen_tokens = count_tokens(item.get("chosen", "")) |
| rejected_tokens = count_tokens(item.get("rejected", "")) |
|
|
| return content_tokens, chosen_tokens, rejected_tokens |
|
|
|
|
| def main(): |
| with open(input_path, "r", encoding="utf-8") as f: |
| data = json.load(f) |
|
|
| result = [] |
| for idx, item in enumerate(data): |
| c_tokens, ch_tokens, r_tokens = process_item(item) |
| result.append({ |
| "index": idx, |
| "content_tokens": c_tokens, |
| "chosen_tokens": ch_tokens, |
| "rejected_tokens": r_tokens, |
| "total_tokens": c_tokens + ch_tokens + r_tokens |
| }) |
|
|
| output_path = input_path.replace(".json", "_token_stats.json") |
| with open(output_path, "w", encoding="utf-8") as f: |
| json.dump(result, f, ensure_ascii=False, indent=2) |
|
|
| print(f"统计完成,共 {len(result)} 条") |
| print(f"输出保存到: {output_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|