| 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) |
|
|
| |
| 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: |
| |
| 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"] |
| |
| 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() |