File size: 9,954 Bytes
3af75d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import json
import re
from Levenshtein import distance as levenshtein

# ---- CONFIG ----
MAX_USER_LEN = 900
LEVENSHTEIN_THRESH = 19
MIN_TURN_LEN = 5
DEFAULT_ANSWER = "Informação não encontrada no contexto fornecido."
MARKDOWN_THRESH = 3  # for rule 5


def clean_text(text: str, counters=None) -> str:
    """Clean user text and track modifications for rule 6."""
    # Rule: remove ', conforme descrito no texto.'
    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)

    # Rule 6: remove 'Conforme o contexto,' at the beginning
    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("|")


# ---- MAIN CLEANING FUNCTION ----
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"]

            # --- Rule 7: turn too short (user or assistant) ---
            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

            # --- Rule 1: default assistant answer ---
            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

            # --- Rule 2: user too long (not first user) ---
            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

            # --- Rule 3: user similar to previous assistant ---
            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

            # --- Rule 4: user similar to previous users ---
            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

            # --- Rule 5: too many markdown symbols (skip for first turn) ---
            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

            # Passed all filters, keep turn
            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


# ---- MAIN EXECUTION ----
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']}")