File size: 13,539 Bytes
3bd62c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
#!/usr/bin/env python3
from __future__ import annotations

import re
import unicodedata
from typing import Optional

# ---------------------------------------------------------------- scripts ----
_RANGES = [
    (0x0370, 0x03FF, "Greek"), (0x1F00, 0x1FFF, "Greek"),   # Greek is normal in science text
    (0x0400, 0x052F, "Cyrillic"), (0x0530, 0x058F, "Armenian"), (0x0590, 0x05FF, "Hebrew"),
    (0x0600, 0x06FF, "Arabic"), (0x0750, 0x077F, "Arabic"), (0x08A0, 0x08FF, "Arabic"),
    (0xFB50, 0xFDFF, "Arabic"), (0xFE70, 0xFEFF, "Arabic"),
    (0x0900, 0x097F, "Devanagari"), (0x0980, 0x09FF, "Bengali"), (0x0A00, 0x0A7F, "Gurmukhi"),
    (0x0A80, 0x0AFF, "Gujarati"), (0x0B00, 0x0B7F, "Oriya"), (0x0B80, 0x0BFF, "Tamil"),
    (0x0C00, 0x0C7F, "Telugu"), (0x0C80, 0x0CFF, "Kannada"), (0x0D00, 0x0D7F, "Malayalam"),
    (0x0D80, 0x0DFF, "Sinhala"), (0x0E00, 0x0E7F, "Thai"), (0x0E80, 0x0EFF, "Lao"),
    (0x0F00, 0x0FFF, "Tibetan"), (0x1000, 0x109F, "Myanmar"), (0x10A0, 0x10FF, "Georgian"),
    (0x1200, 0x137F, "Ethiopic"), (0x1780, 0x17FF, "Khmer"),
    (0x1100, 0x11FF, "Hangul"), (0x3130, 0x318F, "Hangul"), (0xAC00, 0xD7AF, "Hangul"),
    (0x3040, 0x30FF, "Kana"),
    (0x3400, 0x4DBF, "CJK"), (0x4E00, 0x9FFF, "CJK"), (0xF900, 0xFAFF, "CJK"), (0x20000, 0x2A6DF, "CJK"),
]
_EAST_ASIAN = {"CJK", "Kana", "Hangul"}
# Scripts that show up legitimately in science/maths text, so they never count as "foreign".
_NORMAL = {"Greek"}


def script_of(ch: str) -> Optional[str]:
    """Script name for foreign-script letters, else None (Latin, digits, punctuation, Greek...)."""
    o = ord(ch)
    if o < 0x0370:
        return None
    for lo, hi, name in _RANGES:
        if lo <= o <= hi:
            return None if name in _NORMAL else name
    return None


def _is_latin_letter(ch: str) -> bool:
    return ch.isalpha() and (ch < "\u0250" or "\u1e00" <= ch <= "\u1eff")


# ------------------------------------------------------------ patterns -------
_CODE_SPAN = re.compile(r"(```.*?```|`[^`\n]*`)", re.S)
_U_ESCAPE = re.compile(r"\\+u([0-9a-fA-F]{4})(?:\\+u([dD][c-fC-F][0-9a-fA-F]{2}))?")
_MOJIBAKE = re.compile(r"Ã[\u0080-\u00bf¡-¿]|â€[™œ\u009d“”˜¢¦\"'\-–—]|Â[\u00a0-\u00bf]|ðŸ|â€|â|é")
_PUA = re.compile(r"[\ue000-\uf8ff\U000f0000-\U0010ffff]")
_CONTROL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")          # tab/newline/CR are fine
_BIDI_INVISIBLE = re.compile(r"[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]")

# LaTeX commands whose first letter JSON silently ate as an escape (\f \b \a \v ...).
_LATEX_CTRL = [
    (r"\x0crac", r"\frac"), (r"\x0corall", r"\forall"),
    (r"\x08eta", r"\beta"), (r"\x08egin", r"\begin"), (r"\x08inom", r"\binom"),
    (r"\x08oldsymbol", r"\boldsymbol"), (r"\x08ar", r"\bar"),
    (r"\x07lpha", r"\alpha"), (r"\x07pprox", r"\approx"),
    (r"\x0bec", r"\vec"),
]
_LATEX_TAB = re.compile(r"\t(?=(?:heta|imes|ext\{|extbf|ilde|riangle|au(?![a-z])))")


def _decode_escape(m: "re.Match") -> str:
    hi = int(m.group(1), 16)
    if 0xD800 <= hi < 0xDC00 and m.group(2):
        lo = int(m.group(2), 16)
        return chr(0x10000 + ((hi - 0xD800) << 10) + (lo - 0xDC00))
    if 0xD800 <= hi <= 0xDFFF:
        return m.group(0)          # lone surrogate - not decodable, leave it (will be flagged)
    return chr(hi)


def repair_text(text: str) -> tuple:
    """Returns (repaired_text, [what was fixed])."""
    fixes = []
    parts = _CODE_SPAN.split(text)          # odd indexes are code spans - left untouched
    n_esc = 0
    for i in range(0, len(parts), 2):
        parts[i], k = _U_ESCAPE.subn(_decode_escape, parts[i])
        n_esc += k
    out = "".join(parts)
    if n_esc:
        fixes.append(f"decoded {n_esc} literal \\uXXXX escape(s)")
    for bad, good in _LATEX_CTRL:
        bad_c = bad.encode().decode("unicode_escape")      # '\\x0crac' -> '\x0crac'
        if bad_c in out:
            out = out.replace(bad_c, good)
            fixes.append(f"restored LaTeX {good}")
    if _LATEX_TAB.search(out):
        out = _LATEX_TAB.sub(r"\\t", out)
        fixes.append("restored LaTeX \\t... command(s)")
    return out, fixes


def repair_messages(messages: list) -> tuple:
    fixed, all_fixes = [], []
    for m in messages:
        text, fx = repair_text(m["content"])
        fixed.append({**m, "content": text})
        all_fixes.extend(fx)
    return fixed, all_fixes


# ------------------------------------------------------------ analysis -------
def _accents(word: str) -> int:
    return sum(1 for c in unicodedata.normalize("NFD", word) if unicodedata.category(c) == "Mn")


def analyze(text: str) -> dict:
    """Returns {"hard": [...], "soft": [...]} lists of short human-readable findings."""
    hard, soft = [], []

    if "\ufffd" in text:
        hard.append("replacement character U+FFFD (decoding damage)")
    if _PUA.search(text):
        hard.append("private-use-area character")
    m = _CONTROL.search(text)
    if m:
        hard.append(f"control character U+{ord(m.group(0)):04X}")
    for m in _BIDI_INVISIBLE.finditer(text):
        hard.append(f"invisible/bidi character U+{ord(m.group(0)):04X}")
        break
    # ZWJ (U+200D) is how multi-part emoji are built; only suspicious away from symbols.
    for m in re.finditer("\u200d", text):
        a = text[m.start() - 1] if m.start() else ""
        b = text[m.end()] if m.end() < len(text) else ""
        if a.isalnum() and b.isalnum():
            hard.append("zero-width joiner between letters")
            break
    m = _MOJIBAKE.search(text)
    if m:
        hard.append(f"mojibake '{m.group(0)}' (UTF-8 mis-decoded)")
    if re.search(r"\\+u[0-9a-fA-F]{4}", _CODE_SPAN.sub("", text)):
        hard.append("literal \\uXXXX text outside code")
    if re.search(r"[\ud800-\udfff]", text):
        hard.append("lone surrogate")

    # combining mark stuck to a digit/punctuation/space instead of a letter
    for i, ch in enumerate(text):
        if (unicodedata.category(ch) == "Mn" and not 0xFE00 <= ord(ch) <= 0xFE0F) and i:
            prev = text[i - 1]
            if not prev.isalpha() and unicodedata.category(prev) != "Mn":
                hard.append(f"stray combining mark after '{prev}'")
                break

    foreign = set()
    for mm in re.finditer(r"\w+", text):
        word = mm.group(0)
        scripts = {script_of(c) for c in word if c.isalpha()} - {None}
        foreign |= scripts
        if scripts and any(_is_latin_letter(c) for c in word):
            hard.append(f"Latin glued to {'/'.join(sorted(scripts))} text in one word: '{word[:30]}'")
            break
    family = {("EastAsian" if s in _EAST_ASIAN else s) for s in foreign}
    if len(family) >= 2:
        hard.append("unrelated scripts mixed in one conversation: " + ", ".join(sorted(family)))
    elif foreign:
        soft.append("contains " + "/".join(sorted(foreign)) + " text - check it is intentional")

    for mm in re.finditer(r"\w{5,}", text):
        if _accents(mm.group(0)) >= 3:
            soft.append(f"word with many accents: '{mm.group(0)[:30]}'")
            break
    if "\\n" in text and "\n" not in text and len(text) > 200 and "`" not in text:
        soft.append("literal \\n present but no real newlines (double-escaped?)")
    return {"hard": hard, "soft": soft}


def analyze_messages(messages: list) -> dict:
    return analyze("\n".join(m["content"] for m in messages))


# ============================ command line ============================

import argparse
import collections
import json
import sys
from pathlib import Path



def read_jsonl(path):
    rows = []
    with open(path, encoding="utf-8") as f:
        for n, line in enumerate(f, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rows.append((n, json.loads(line)))
            except json.JSONDecodeError:
                rows.append((n, None))
    return rows


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("output")
    ap.add_argument("--metadata", help="metadata sidecar (one line per output line) for topic-aware requeue")
    ap.add_argument("--requeue", metavar="LEDGER", help="append 'failed' entries for quarantined topics to this ledger")
    ap.add_argument("--min-assistant-words", type=int, default=0, metavar="N",
                    help="also drop any example in which ANY assistant message has fewer than N words (0 = off)")
    ap.add_argument("--show", type=int, default=12, help="examples per finding type to print")
    args = ap.parse_args()

    src = Path(args.output)
    rows = read_jsonl(src)
    meta_rows = read_jsonl(args.metadata) if args.metadata else None
    aligned = meta_rows is not None and len(meta_rows) == len(rows)
    if args.metadata and not aligned:
        print(f"! metadata has {len(meta_rows)} lines but output has {len(rows)} - cannot match rows to topics; "
              "skipping clean metadata and requeue", file=sys.stderr)

    stem = src.with_suffix("")
    clean_fh = open(f"{stem}.clean.jsonl", "w", encoding="utf-8")
    quar_fh = open(f"{stem}.quarantine.jsonl", "w", encoding="utf-8")
    cmeta_fh = open(f"{stem}.clean.metadata.jsonl", "w", encoding="utf-8") if aligned else None
    report, hard_kinds, soft_kinds, repair_kinds = [], collections.Counter(), collections.Counter(), collections.Counter()
    short_fh = open(f"{stem}.removed_short.jsonl", "w", encoding="utf-8") if args.min_assistant_words else None
    n_clean = n_quar = n_repaired = n_soft = n_bad_line = n_short = 0
    requeue = []

    for idx, (lineno, obj) in enumerate(rows):
        if obj is None or not isinstance(obj.get("messages"), list):
            n_bad_line += 1
            report.append(f"row {lineno}: UNREADABLE line")
            continue
        messages, fixes = repair_messages(obj["messages"])
        result = analyze_messages(messages)
        for f in fixes:
            repair_kinds[f.split(" ")[0] + " " + f.split(" ")[1]] += 1
        if fixes:
            n_repaired += 1
            report.append(f"row {lineno}: repaired - {'; '.join(fixes)}")
        if result["hard"]:
            n_quar += 1
            for h in result["hard"]:
                hard_kinds[h.split(":")[0].split("'")[0].strip()] += 1
            report.append(f"row {lineno}: QUARANTINED - {'; '.join(result['hard'])}")
            quar_fh.write(json.dumps({"row": lineno, "problems": result["hard"], "messages": messages},
                                     ensure_ascii=False) + "\n")
            if aligned and isinstance(meta_rows[idx][1], dict) and meta_rows[idx][1].get("topic"):
                requeue.append((meta_rows[idx][1]["topic"], "; ".join(result["hard"])[:200]))
            continue
        if args.min_assistant_words:
            words = [len(m["content"].split()) for m in messages if m.get("role") == "assistant"]
            if words and min(words) < args.min_assistant_words:
                n_short += 1
                report.append(f"row {lineno}: REMOVED (short) - shortest assistant reply has {min(words)} words")
                short_fh.write(json.dumps({"row": lineno, "min_words": min(words), "messages": messages},
                                          ensure_ascii=False) + "\n")
                continue
        if result["soft"]:
            n_soft += 1
            for s in result["soft"]:
                soft_kinds[s.split(" - ")[0][:45]] += 1
            report.append(f"row {lineno}: review - {'; '.join(result['soft'])}")
        n_clean += 1
        clean_fh.write(json.dumps({**obj, "messages": messages}, ensure_ascii=False) + "\n")
        if cmeta_fh and meta_rows[idx][1] is not None:
            cmeta_fh.write(json.dumps(meta_rows[idx][1], ensure_ascii=False) + "\n")

    for fh in (clean_fh, quar_fh, cmeta_fh, short_fh):
        if fh:
            fh.close()
    Path(f"{stem}.report.txt").write_text("\n".join(report) + "\n", encoding="utf-8")

    print(f"rows read:            {len(rows)}")
    print(f"clean (kept):         {n_clean}   -> {stem}.clean.jsonl")
    print(f"  of which repaired:  {n_repaired}")
    print(f"  flagged for review: {n_soft}   (kept; see report)")
    print(f"quarantined:          {n_quar}   -> {stem}.quarantine.jsonl")
    if args.min_assistant_words:
        print(f"removed (<{args.min_assistant_words} words):  {n_short}   -> {stem}.removed_short.jsonl")
    if n_bad_line:
        print(f"unreadable lines:     {n_bad_line}")
    if hard_kinds:
        print("\nquarantine reasons:")
        for k, v in hard_kinds.most_common():
            print(f"  {v:5d}  {k}")
    if repair_kinds:
        print("\nrepairs applied:", dict(repair_kinds))
    if soft_kinds:
        print("\nreview flags:", dict(soft_kinds.most_common(6)))
    shown = 0
    print()
    for line in report:
        if "QUARANTINED" in line and shown < args.show:
            print(" ", line[:220]); shown += 1
    print(f"\nfull list: {stem}.report.txt")

    if args.requeue:
        if not aligned:
            print("requeue skipped (metadata not aligned)."); return
        with open(args.requeue, "a", encoding="utf-8") as fh:
            for topic, why in requeue:
                fh.write(json.dumps({"topic": topic, "status": "failed", "error": ("quarantined: " + why)[:300]}, ensure_ascii=False) + "\n")
        print(f"requeued {len(requeue)} topics in {args.requeue} - run generate_dataset.py --retry-failed")


if __name__ == "__main__":
    main()