File size: 2,813 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import json
import re
import os

input_path = "/root/test/weitiao/data_process_bq/data/train01_hg2chatml_p2r.json"
output_path = "/root/test/weitiao/data_process_bq/data/train01_chatml_p2r_closed.json"
dropped_path = "/root/test/weitiao/data_process_bq/data/train01_chatml_p2r_unclosed.json"

def is_balanced(text: str):
    """检查 text 内部的特殊字符是否成对出现"""
    if text.count('*') % 2 != 0:
        return False, "unmatched *"
    if re.search(r'(?<!\\)"', text):
        return False, "unescaped quote"
    return True, None

def check_role_format(text: str):
    """检查角色名格式是否正常"""
    pattern = r'^[A-Za-z0-9_]+:\s*(["*]|.)'
    ok = re.match(pattern, text.strip()) is not None
    return ok

def is_valid_message_content(content: str):
    # 1. 成对符号检查
    ok, reason = is_balanced(content)
    if not ok:
        return False, reason

    # 2. 角色格式检查
    if ":" in content:
        left = content.split(":", 1)[0]
        if re.match(r'^[A-Za-z0-9_]+$', left):
            if not check_role_format(content):
                return False, "invalid role format"

    return True, None

def clean_dataset(input_path, output_path, dropped_path):
    with open(input_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    cleaned = []
    dropped = []

    for item_idx, item in enumerate(data):
        ok = True
        reason = ""

        # -------- 检查 chosen / rejected message lists --------
        for branch in ["chosen", "rejected"]:
            if branch not in item:
                ok = False
                reason = f"missing field: {branch}"
                break
            for msg_idx, msg in enumerate(item[branch]):
                content = msg.get("content", "")
                valid, why = is_valid_message_content(content)
                if not valid:
                    ok = False
                    reason = f"{branch}[{msg_idx}].content: {why}"
                    break
            if not ok:
                break
        if ok:
            cleaned.append(item)
        else:
            new_item = dict(item)
            new_item["drop_reason"] = reason
            dropped.append(new_item)

    print(f"总共 {len(data)} 条")
    print(f"丢弃 {len(dropped)} 条(不闭合或格式异常)")
    print(f"保留 {len(cleaned)} 条 → {output_path}")
    print(f"丢弃样本写入 → {dropped_path}")

    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(cleaned, f, indent=2, ensure_ascii=False)

    os.makedirs(os.path.dirname(dropped_path), exist_ok=True)
    with open(dropped_path, "w", encoding="utf-8") as f:
        json.dump(dropped, f, indent=2, ensure_ascii=False)


if __name__ == "__main__":
    clean_dataset(input_path, output_path, dropped_path)