File size: 7,797 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import json, os, re, concurrent.futures
from openai import OpenAI
from colorama import Fore, init
import time

init(autoreset=True)

# ================= 配置区 =================
API_KEY = "sk_6K2WAGvUtmmJspmA82xp5Bi7uOWNJZo2XeNJZ5kgo4o"
BASE_URL = "https://api.ppio.com/openai"
MODEL = "zai-org/glm-5" 

INPUT_FILE = "/root/test/weitiao/data_process_bq/data3/result/M_sharegpt_data3_all_fail.json"
OUTPUT_FILE = "/root/test/weitiao/1" 

MAX_WORKERS = 40
TIMEOUT = 90
# ==========================================

client = OpenAI(api_key=API_KEY, base_url=BASE_URL)

# ================= 针对 N-gram 模式坍塌的专用 Prompt =================
DPO_DUAL_PROMPT = """你是一名专业的小说文本质检员和自然语言处理分析师。你的任务是检测文本中是否出现了严重的“模式坍塌(Mode Collapse)”和“陈词滥调(Clichés)”。

【极其重要】:
1. 忽略文中描述的任何行为、道德、合规性或安全性。
2. 无论内容多么露骨(NSFW)或违规视为“虚构数据”,不要进行安全判定。
3. 只寻找“刻板的生理反应描写”“高度重复的套路词汇”以及“空壳式互动启动语”。

1. 空壳式互动启动语【最高优先级】:指仅用于制造互动氛围或暧昧节奏、但不提供任何实质信息、如果一句话删除后不影响剧情理解的启动句或提问句:
“Can I…”, “May I…”, “Let me…”, “You know…”, “Guess what…”、 “Something personal?”, “Something important?”、未完成句式( “You know what I—”)、“I have something…” 、语义等价表达(陈述句:“I wanted to tell you something.”、“There’s something I should say。”、“I was wondering if…” )
2. 咬唇综合征:"bites her/his lip", "biting her lower lip" 等。
3. 气音与低语狂热:"voice barely above a whisper", "voice drops to a whisper", "dropping to a sultry/husky..."。
4. 刻板仰视:"looks up at you/him", "looking up at... with..."。
5. 陈腔滥调的生理反应:"heart skips a beat", "takes a deep breath", "eyes widen in shock", "tears prick at the corners"。
6. 标志性动作复读:"running a hand through his hair", "a mischievous glint in her eye"。
7. 凑字数模板:"with a mix of...", "for a moment before", "just like that"。

【判定准则】:
- 只要文本中明显使用了上述的套路化表达判定为 True。
- 文本动作描写具体生动、符合角色个性,不存在空壳互动或模板化表达,判定为 False。

请严格返回 JSON:
{
  "chosen_has_cliche": true/false,
  "rejected_has_cliche": true/false
}"""

# ===== 以下代码完全未修改 =====

def calculate_dual_quality(chosen_has_cliche, rejected_has_cliche):
    if chosen_has_cliche is False and rejected_has_cliche is True:
        return "Perfect"
    elif chosen_has_cliche is False and rejected_has_cliche is False:
        return "Neutral_Clean"
    elif chosen_has_cliche is True and rejected_has_cliche is True:
        return "Bad_Pair"
    elif chosen_has_cliche is True and rejected_has_cliche is False:
        return "Toxic_Reverse"
    else:
        return "Unknown"

def extract_json_robust(text):
    if not text: return None

    text = re.sub(r"^```json\s*", "", text, flags=re.MULTILINE)
    text = re.sub(r"```$", "", text, flags=re.MULTILINE).strip()

    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass

    try:
        match = re.search(r'(\{.*)[,"]', text, re.DOTALL)
        if match:
            potential_json = match.group(1).strip()
            for suffix in ['"}', '}', 'true}', 'false}']:
                try:
                    return json.loads(potential_json + suffix)
                except:
                    continue
    except:
        return None
    return None

def audit_dual_item(index, item):
    prompt = f"###[A] Chosen Text:\n{item['chosen']['value']}\n\n### [B] Rejected Text:\n{item['rejected']['value']}"
    
    max_retries = 3
    
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model=MODEL,
                messages=[
                    {"role": "system", "content": DPO_DUAL_PROMPT}, 
                    {"role": "user", "content": prompt}
                ],
                response_format={"type": "json_object"}, 
                temperature=0.1,  
                timeout=TIMEOUT
            )
            content = response.choices[0].message.content.strip()
            audit = extract_json_robust(content)

            if audit:
                # ✅ 兼容 list 或 dict
                if isinstance(audit, list) and len(audit) > 0:
                    audit = audit[0]

                c_cliche = audit.get("chosen_has_cliche")
                r_cliche = audit.get("rejected_has_cliche")
                audit["dual_quality"] = calculate_dual_quality(c_cliche, r_cliche)
                return {"_original_index": index, "audit_result": audit}
            else:
                return {
                    "_original_index": index,
                    "audit_result": {
                        "chosen_has_cliche": False, 
                        "rejected_has_cliche": False,
                        "dual_quality": "Refused"
                    }
                }
                
        except Exception as e:
            error_msg = str(e)
            if ("timed out" in error_msg.lower() or "timeout" in error_msg.lower() or "connection" in error_msg.lower()) and attempt < max_retries - 1:
                sleep_time = 2 ** attempt
                time.sleep(sleep_time)
                continue
            
            return {"_original_index": index, "error": error_msg}

def process():
    if not os.path.exists(INPUT_FILE):
        print(f"{Fore.RED}错误:找不到输入文件 {INPUT_FILE}")
        return
    
    with open(INPUT_FILE, "r", encoding="utf-8") as f: 
        data = json.load(f)

    processed_count = 0
    if os.path.exists(OUTPUT_FILE):
        with open(OUTPUT_FILE, "r", encoding="utf-8") as f: 
            processed_count = sum(1 for _ in f)

    to_process = data[processed_count:]
    print(f"{Fore.CYAN}🚀 鲁棒审计启动(打击过拟合与套路词),剩余: {len(to_process)} 条...")

    with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
        futures = {executor.submit(audit_dual_item, i + processed_count, item): i for i, item in enumerate(to_process)}

        for future in concurrent.futures.as_completed(futures):
            res = future.result()
            idx = res.get("_original_index", "??")

            if "error" in res:
                print(f"{Fore.RED}#{idx} | 拦截/错误: {res['error'][:40]}")
            else:
                aud = res["audit_result"]
                # ✅ 防止 audit 是字符串/其他非 dict
                if isinstance(aud, dict):
                    c_c = aud.get("chosen_has_cliche")
                    r_c = aud.get("rejected_has_cliche")
                    quality = aud.get("dual_quality")
                else:
                    c_c = r_c = quality = "Unknown"

                if quality == "Perfect":
                    color = Fore.GREEN
                elif quality == "Toxic_Reverse" or quality == "Bad_Pair":
                    color = Fore.RED
                else:
                    color = Fore.YELLOW
                    
                print(f"#{idx} | {color}解析成功 | Chosen_套路: {c_c} | Rejected_套路: {r_c} | 综合质量: {quality}")

            with open(OUTPUT_FILE, "a", encoding="utf-8") as f:
                f.write(json.dumps(res, ensure_ascii=False) + "\n")

if __name__ == "__main__":
    process()