import json import re from collections import Counter, defaultdict from pathlib import Path ROOT = Path("/root/test/weitiao/data_process_bq") INPUT = ROOT / "data" / "train_merged_dedup_shuffled_30001.json" OUT_DIR = ROOT / "13052_style_issue_samples" NARRATOR_PATTERNS = [ r"\bas soon as\b", r"\bas they\b", r"\bas (he|she|it|you|we)\b", r"\b(months?|weeks?|days?|years?) (pass|passed|later)\b", r"\b(time passes|time passed)\b", r"\bthe next (morning|day|night|week)\b", r"\blater that\b", r"\beventually\b", r"\bafter a while\b", r"\bover the next\b", r"\bin the following\b", r"\bmeanwhile\b", ] SCENE_JUMP_PATTERNS = [ r"\b(knock|knocking|knocked) (at|on)\b", r"\bthe door (opens|opened|slams|slammed|bursts|burst)\b", r"\bphone (rings|rang|buzzes|buzzed)\b", r"\bmessage (arrives|arrived|pops|popped)\b", r"\bsuddenly\b", r"\bjust then\b", r"\bout of nowhere\b", r"\bflashback\b", r"\bremembers?\b", r"\bmemory\b", r"\b(hours?|days?|weeks?|months?) later\b", r"\bthe next (morning|day|night|week)\b", ] CONTROL_SHIFT_PATTERNS = [ r"\byou (nod|nodded|agree|agreed|follow|followed|step|stepped|walk|walked|sit|sat|stand|stood|take|took|accept|accepted|realize|realized|understand|understood|decide|decided|feel|felt|can't help but|cannot help but)\b", r"\byour (heart|breath|body|mind|thoughts|eyes|hands|lips|cheeks)\b", r"\byou (can't|cannot) resist\b", r"\byou let him\b", r"\byou let her\b", r"\byou find yourself\b", r"\bboth of you\b", r"\btogether, you\b", ] FORMAT_MISMATCH_PATTERNS = [ r"^\s*(with|after|as|while|when)\b", r"\b(washes over|a wave of|a surge of|couldn't help but|for a moment|in that moment)\b", r"\b(his|her|their) mind\b", r"\bthe weight of\b", r"\bthe air (is|was|grows|grew|hangs|hung)\b", ] UNSAFE_PATTERNS = [ r"\b(kill|murder|blood|gun|knife|shoot|shot|stab|weapon|execution|mafia|cartel|hostage|kidnap|torture|corpse|dead|death)\b", r"\b(suicide|self[- ]harm|cut myself|overdose)\b", r"\b(sex|cum|cock|pussy|dick|orgasm|naked|rape|raped|molest|blowjob|anal|thrust|clit|boobs)\b", r"\b(minor|underage|teen|schoolgirl|schoolboy)\b", r"\b(drug|cocaine|heroin|meth|overdose)\b", ] NARRATOR_RE = [(pat, re.compile(pat, re.I)) for pat in NARRATOR_PATTERNS] SCENE_JUMP_RE = [(pat, re.compile(pat, re.I)) for pat in SCENE_JUMP_PATTERNS] CONTROL_SHIFT_RE = [(pat, re.compile(pat, re.I)) for pat in CONTROL_SHIFT_PATTERNS] FORMAT_MISMATCH_RE = [(pat, re.compile(pat, re.I)) for pat in FORMAT_MISMATCH_PATTERNS] UNSAFE_RE = [(pat, re.compile(pat, re.I)) for pat in UNSAFE_PATTERNS] WORD_RE = re.compile(r"\b[\w']+\b") THIRD_PERSON_RE = re.compile(r"\b(he|she|they|him|her|his|hers|their|the)\b", re.I) YOU_RE = re.compile(r"\byou\b|\byour\b", re.I) ACTION_RE = re.compile( r"^\s*[A-ZÁÉÍÓÚÄÖÜÑ][^.\n]{0,80}\s+" r"(nods|smiles|leans|steps|looks|says|asks|whispers|murmurs|growls|grins)\b", re.I, ) def norm(text): return (text or "").replace("\r\n", "\n") def text_of_message(msg): if isinstance(msg, dict): return norm(msg.get("value", "")) return norm(str(msg)) def regex_hits(compiled_patterns, text): hits = [] for pat, rex in compiled_patterns: if rex.search(text): hits.append(pat) return hits def quote_count(text): return text.count('"') + text.count("“") + text.count("”") + text.count("¿") + text.count("?") def action_dialog_score(text): has_action = "*" in text or ACTION_RE.search(text) return int(bool(has_action)) + int(quote_count(text) >= 2) def categories_for(text, other_text): words = WORD_RE.findall(text) word_count = max(len(words), 1) cats = {} narrator_hits = regex_hits(NARRATOR_RE, text) third_person = len(THIRD_PERSON_RE.findall(text)) dialogue_sparse = quote_count(text) < 2 longish = word_count >= 35 if narrator_hits or (longish and dialogue_sparse and third_person / word_count > 0.08): cats["narrator_summary"] = { "hits": narrator_hits, "word_count": word_count, "quote_count": quote_count(text), "third_person_ratio": round(third_person / word_count, 3), } jump_hits = regex_hits(SCENE_JUMP_RE, text) if jump_hits: cats["scene_jump_new_event"] = {"hits": jump_hits} control_hits = regex_hits(CONTROL_SHIFT_RE, text) user_mentions = len(YOU_RE.findall(text)) if control_hits or user_mentions >= 5: cats["role_control_shift"] = { "hits": control_hits, "you_your_count": user_mentions, } format_hits = regex_hits(FORMAT_MISMATCH_RE, text) other_action_dialog = action_dialog_score(other_text) this_action_dialog = action_dialog_score(text) if format_hits or (word_count >= 45 and dialogue_sparse and other_action_dialog > this_action_dialog): cats["tone_format_mismatch"] = { "hits": format_hits, "word_count": word_count, "quote_count": quote_count(text), "this_action_dialog_score": this_action_dialog, "other_action_dialog_score": other_action_dialog, } return cats def safety_label(record, chosen_text, rejected_text): parts = [] for msg in record.get("conversations", [])[-6:]: parts.append(text_of_message(msg)) parts.extend([chosen_text, rejected_text]) blob = "\n".join(parts) hits = regex_hits(UNSAFE_RE, blob) return ("unsafe_or_sensitive" if hits else "relatively_safe", hits[:12]) def context_tail(record, n=4): conv = record.get("conversations", []) return [ {"from": m.get("from"), "value": text_of_message(m)} for m in conv[-n:] if isinstance(m, dict) ] def main(): OUT_DIR.mkdir(parents=True, exist_ok=True) with INPUT.open(encoding="utf-8") as f: data = json.load(f) files = { "narrator_summary": (OUT_DIR / "01_narrator_summary.jsonl").open("w", encoding="utf-8"), "scene_jump_new_event": (OUT_DIR / "02_scene_jump_new_event.jsonl").open("w", encoding="utf-8"), "role_control_shift": (OUT_DIR / "03_role_control_shift.jsonl").open("w", encoding="utf-8"), "tone_format_mismatch": (OUT_DIR / "04_tone_format_mismatch.jsonl").open("w", encoding="utf-8"), "all": (OUT_DIR / "all_flagged.jsonl").open("w", encoding="utf-8"), } category_counts = Counter() side_counts = Counter() safety_total = Counter() safety_flagged = Counter() safety_by_category = defaultdict(Counter) overlap_counts = Counter() for idx, record in enumerate(data): chosen_text = text_of_message(record.get("chosen", {})) rejected_text = text_of_message(record.get("rejected", {})) label, safety_hits = safety_label(record, chosen_text, rejected_text) safety_total[label] += 1 per_record_categories = set() for side, text, other in [ ("chosen", chosen_text, rejected_text), ("rejected", rejected_text, chosen_text), ]: cats = categories_for(text, other) if not cats: continue item = { "index": idx, "side": side, "categories": cats, "safety_label": label, "safety_hits": safety_hits, "context_tail": context_tail(record), "response": text, "other_response": other, } line = json.dumps(item, ensure_ascii=False) files["all"].write(line + "\n") side_counts[side] += 1 safety_flagged[label] += 1 for cat in cats: files[cat].write(line + "\n") category_counts[cat] += 1 safety_by_category[cat][label] += 1 per_record_categories.add(cat) if per_record_categories: overlap_counts[len(per_record_categories)] += 1 for f in files.values(): f.close() summary = { "input": str(INPUT), "output_dir": str(OUT_DIR), "records": len(data), "category_counts_candidate_level": dict(category_counts), "flagged_side_counts": dict(side_counts), "safety_total_record_level": dict(safety_total), "safety_flagged_candidate_level": dict(safety_flagged), "safety_by_category_candidate_level": {k: dict(v) for k, v in safety_by_category.items()}, "record_category_overlap_counts": dict(overlap_counts), "notes": [ "The source has no model-id field, so flagged_side is chosen/rejected, not a confirmed 13052 label.", "Safety labels are heuristic keyword labels over context plus both candidate responses.", "Counts are candidate-level for flagged outputs unless the key says record-level.", ], } (OUT_DIR / "summary.json").write_text( json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8" ) md = [ "# 13052 Style Issue Extraction", "", f"Input: `{INPUT}`", f"Records: {len(data)}", "", "## Output files", "", "- `01_narrator_summary.jsonl`: 旁白总结/复述剧情感", "- `02_scene_jump_new_event.jsonl`: 跳场景/新增事件", "- `03_role_control_shift.jsonl`: 替用户推进/控制用户动作或心理", "- `04_tone_format_mismatch.jsonl`: 语气和格式更像小说叙述,互动弱", "- `all_flagged.jsonl`: 所有命中候选", "- `summary.json`: 统计信息", "", "## Candidate-level counts", "", ] for cat, cnt in category_counts.most_common(): md.append(f"- {cat}: {cnt}") md.extend(["", "## Safety heuristic", ""]) for label, total in safety_total.items(): flagged = safety_flagged.get(label, 0) rate = flagged / total if total else 0 md.append(f"- {label}: records={total}, flagged_candidates={flagged}, flagged_candidates_per_record={rate:.3f}") md.extend(["", "## Caveats", ""]) md.extend(f"- {note}" for note in summary["notes"]) (OUT_DIR / "README.md").write_text("\n".join(md) + "\n", encoding="utf-8") print(json.dumps(summary, ensure_ascii=False, indent=2)) if __name__ == "__main__": main()