| import json |
| import re |
| from Levenshtein import distance as levenshtein |
|
|
| |
| MAX_USER_LEN = 900 |
| LEVENSHTEIN_THRESH = 19 |
| MIN_TURN_LEN = 5 |
| DEFAULT_ANSWER = "Informação não encontrada no contexto fornecido." |
| MARKDOWN_THRESH = 3 |
|
|
|
|
| def clean_text(text: str, counters=None) -> str: |
| """Clean user text and track modifications for rule 6.""" |
| |
| def remove_conforme_texto(m): |
| if counters is not None: |
| counters["turns_modified"] += 1 |
| return "." |
|
|
| text = re.sub(r", conforme descrito no texto\.", remove_conforme_texto, text) |
|
|
| |
| def remove_conforme(m): |
| if counters is not None: |
| counters["rule6_conforme_contexto"] += 1 |
| counters["turns_modified"] += 1 |
| return m.group(1).upper() |
|
|
| text = re.sub( |
| r"^\s*Conforme o contexto,\s*([a-zA-Z])", |
| remove_conforme, |
| text |
| ) |
|
|
| return text |
|
|
|
|
| def is_default_answer(msg: str) -> bool: |
| return msg.strip() == DEFAULT_ANSWER |
|
|
|
|
| def count_markdown(text: str) -> int: |
| """Count occurrences of specific markdown symbols.""" |
| return text.count("\n") + text.count("|") |
|
|
|
|
| |
| def clean_conversations(conversations, verbose=False): |
| cleaned = [] |
|
|
| counters = { |
| "rule1_default_answer": 0, |
| "rule2_long_user": 0, |
| "rule3_similar_to_assistant": 0, |
| "rule4_similar_to_user": 0, |
| "rule5_markdown_count": 0, |
| "rule6_conforme_contexto": 0, |
| "rule7_too_short_turn": 0, |
| "empty_turns": 0, |
| "conversations_dropped": 0, |
| "conversations_kept": 0, |
| "turns_removed": 0, |
| "turns_modified": 0 |
| } |
|
|
| empty_turns_info = [] |
|
|
| for conv in conversations: |
| seq_id = conv["seq_id"] |
| convo = conv["conversation"] |
|
|
| new_convo = [] |
| skip_conversation = False |
|
|
| user_prompts = [] |
| last_assistant = None |
|
|
| i = 0 |
| while i < len(convo): |
| turn_user = convo[i] if i < len(convo) and convo[i]["role"] == "user" else None |
| turn_assistant = convo[i + 1] if i + 1 < len(convo) and convo[i + 1]["role"] == "assistant" else None |
|
|
| if ( |
| turn_user is None |
| or turn_assistant is None |
| or turn_user.get("content") is None |
| or turn_assistant.get("content") is None |
| ): |
| counters["empty_turns"] += 1 |
| counters["turns_removed"] += 1 |
| empty_turns_info.append({ |
| "seq_id": seq_id, |
| "conversation": convo |
| }) |
| if verbose: |
| print(f" → Dropping turn {i//2+1} in {seq_id}: empty user or assistant message") |
| i += 2 |
| continue |
|
|
| user_msg = clean_text(turn_user["content"], counters=counters) |
| assistant_msg = turn_assistant["content"] |
|
|
| |
| if len(user_msg.strip()) < MIN_TURN_LEN or len(assistant_msg.strip()) < MIN_TURN_LEN: |
| counters["rule7_too_short_turn"] += 1 |
| counters["turns_removed"] += 1 |
| if verbose: |
| print( |
| f" → Dropping turn {i//2+1} in {seq_id}: " |
| f"user({len(user_msg.strip())}) or assistant({len(assistant_msg.strip())}) < {MIN_TURN_LEN} chars" |
| ) |
| i += 2 |
| continue |
|
|
| |
| if is_default_answer(assistant_msg): |
| counters["rule1_default_answer"] += 1 |
| if not new_convo: |
| skip_conversation = True |
| if verbose: |
| print(f" → Dropping entire conversation {seq_id}: first assistant default") |
| break |
| else: |
| counters["turns_removed"] += 1 |
| if verbose: |
| print(f" → Dropping turn {i//2+1} in {seq_id}: assistant default answer") |
| i += 2 |
| continue |
|
|
| |
| if len(user_msg) > MAX_USER_LEN and new_convo: |
| counters["rule2_long_user"] += 1 |
| counters["turns_removed"] += 1 |
| if verbose: |
| print( |
| f" → Dropping turn {i//2+1} in {seq_id}: " |
| f"user message too long ({len(user_msg)} chars)" |
| ) |
| i += 2 |
| continue |
|
|
| |
| if last_assistant and levenshtein(user_msg, last_assistant) <= LEVENSHTEIN_THRESH: |
| counters["rule3_similar_to_assistant"] += 1 |
| counters["turns_removed"] += 1 |
| if verbose: |
| print(f" → Dropping turn {i//2+1} in {seq_id}: user similar to last assistant") |
| i += 2 |
| continue |
|
|
| |
| if any(levenshtein(user_msg, prev) <= LEVENSHTEIN_THRESH for prev in user_prompts): |
| counters["rule4_similar_to_user"] += 1 |
| counters["turns_removed"] += 1 |
| if verbose: |
| print( |
| f" → Dropping turn {i//2+1} in {seq_id}: " |
| f"user duplicate or similar to previous user" |
| ) |
| i += 2 |
| continue |
|
|
| |
| if new_convo and count_markdown(user_msg) >= MARKDOWN_THRESH: |
| counters["rule5_markdown_count"] += 1 |
| counters["turns_removed"] += 1 |
| if verbose: |
| print( |
| f" → Dropping turn {i//2+1} in {seq_id}: " |
| f"user has {count_markdown(user_msg)} markdown symbols" |
| ) |
| i += 2 |
| continue |
|
|
| |
| new_convo.append({"role": "user", "content": user_msg}) |
| new_convo.append({"role": "assistant", "content": assistant_msg}) |
|
|
| user_prompts.append(user_msg) |
| last_assistant = assistant_msg |
|
|
| i += 2 |
|
|
| if not skip_conversation and new_convo: |
| cleaned.append({ |
| "seq_id": seq_id, |
| "conversation": new_convo, |
| "question_style": conv.get("question_style"), |
| "context_id": conv.get("context_id") |
| }) |
| counters["conversations_kept"] += 1 |
| else: |
| if skip_conversation: |
| counters["conversations_dropped"] += 1 |
|
|
| return cleaned, counters |
|
|
|
|
| |
| if __name__ == "__main__": |
| verbose = False |
| input_file = "magpie_conversations_cemig_v1_objetiva.jsonl" |
| output_file = "./cemig_cleaned/magpie_conversations_cemig_v1_objetiva.jsonl" |
|
|
| with open(input_file, "r", encoding="utf-8") as f: |
| data = [] |
| for lineno, line in enumerate(f, start=1): |
| if not line.strip(): |
| continue |
| try: |
| obj = json.loads(line) |
| data.append(obj) |
| except json.JSONDecodeError as e: |
| print(f"JSON error at file line {lineno}, char {e.pos}: {e}") |
| print("Problematic line:") |
| print(line) |
|
|
| print("Attempting automatic fix by splitting '}{'") |
| parts = line.replace("}{", "}\n{").splitlines() |
| fixed_objs = 0 |
| for part in parts: |
| try: |
| obj = json.loads(part) |
| data.append(obj) |
| fixed_objs += 1 |
| except json.JSONDecodeError as e2: |
| print(f"Still failed to parse part: {e2}") |
| print(part) |
| print(f"Fixed {fixed_objs} objects from problematic line.") |
|
|
| total_turns = sum(len(conv["conversation"]) // 2 for conv in data) |
|
|
| cleaned, counters = clean_conversations(data, verbose=verbose) |
|
|
| kept_turns = sum(len(conv["conversation"]) // 2 for conv in cleaned) |
| percentage_kept = (kept_turns / total_turns * 100) if total_turns > 0 else 0 |
|
|
| with open(output_file, "w", encoding="utf-8") as f: |
| for conv in cleaned: |
| f.write(json.dumps(conv, ensure_ascii=False) + "\n") |
|
|
| print("\nFinal results") |
| print(f"Rule 1 (default answer) was triggered {counters['rule1_default_answer']} times") |
| print(f"Rule 2 (long user message) was triggered {counters['rule2_long_user']} times") |
| print(f"Rule 3 (user similar to assistant) was triggered {counters['rule3_similar_to_assistant']} times") |
| print(f"Rule 4 (user similar to another user) was triggered {counters['rule4_similar_to_user']} times") |
| print(f"Rule 5 (user contains too many markdown symbols) was triggered {counters['rule5_markdown_count']} times") |
| print(f"Rule 6 (Conforme o contexto, removed) was triggered {counters['rule6_conforme_contexto']} times") |
| print(f"Rule 7 (turn too short) was triggered {counters['rule7_too_short_turn']} times") |
| print(f"Empty turns removed: {counters['empty_turns']}") |
| print(f"Turns removed: {counters['turns_removed']}") |
| print(f"Turns modified: {counters['turns_modified']}") |
| print(f"Total turns in original file: {total_turns}") |
| print(f"Turns kept after cleaning: {kept_turns} ({percentage_kept:.2f}%)") |
| print(f"Conversations kept: {counters['conversations_kept']}") |
| print(f"Conversations dropped: {counters['conversations_dropped']}") |
|
|