File size: 1,873 Bytes
3d27cfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import json
from transformers import AutoTokenizer

input_path = "/root/test/weitiao/data_process_bq/data/train2_closed.json"

# 使用 Qwen 的 tokenizer(与 Qwen3-4B 兼容)
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 token 统计
    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 / rejected
    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()