omererce commited on
Commit
3c18de6
·
verified ·
1 Parent(s): d369b4b

Upload validate_and_merge_dataset.py

Browse files
Files changed (1) hide show
  1. validate_and_merge_dataset.py +330 -0
validate_and_merge_dataset.py ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Validate, deduplicate, optionally merge, and split Hycean-1 Omni ChatML datasets.
4
+
5
+ Supports:
6
+ - Base dataset: `datasets/hycean_omni_dataset.jsonl`
7
+ - Optional 4-teacher ensemble dataset: `datasets/hycean_multi_teacher_distilled.jsonl`
8
+ - Optional Kimi K3.1 Pro teacher dataset: `datasets/kimi_k3_distilled.jsonl`
9
+ - Optional Inkling-2 Mini teacher dataset: `datasets/inkling_2_mini_distilled.jsonl`
10
+ - Optional DeepSeek-V4.1 Flash teacher dataset: `datasets/deepseek_v4_1_flash_distilled.jsonl`
11
+ - Optional GLM-5.3 teacher dataset: `datasets/glm_5_3_distilled.jsonl`
12
+ - Optional user-exported app distillation dataset: `datasets/hycean_distill_dataset.jsonl`
13
+ - Optional extra ChatML JSONL files via `--extra`
14
+ - Strict JSON + role + `<tool_call>` JSON + `<think>` balance checks
15
+ - Exact normalized deduplication
16
+ - Deterministic 90% train / 10% eval split (`datasets/processed/`)
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import hashlib
23
+ import json
24
+ import random
25
+ import re
26
+ import sys
27
+ from collections import Counter
28
+ from pathlib import Path
29
+ from typing import Any
30
+
31
+ VALID_ROLES = {"system", "user", "assistant", "tool"}
32
+ TOOL_CALL_RE = re.compile(r"<tool_call>(.*?)</tool_call>", re.DOTALL)
33
+
34
+
35
+ def detect_turkish(text: str) -> bool:
36
+ if any(ch in text for ch in "çğıİöşüÇĞÖŞÜ"):
37
+ return True
38
+ lower = text.lower()
39
+ tr_hints = ("merhaba", "oluştur", "olustur", "görev", "gorev", "müzik", "muzik", "saniye", "hesapla", "çöz")
40
+ return any(h in lower for h in tr_hints)
41
+
42
+
43
+ def validate_record(raw_line: str, line_no: int, source_name: str) -> tuple[dict[str, Any] | None, list[str], list[str]]:
44
+ errors: list[str] = []
45
+ tools_found: list[str] = []
46
+
47
+ try:
48
+ obj = json.loads(raw_line)
49
+ except json.JSONDecodeError as exc:
50
+ return None, [f"{source_name}:{line_no}: invalid JSON ({exc})"], tools_found
51
+
52
+ if not isinstance(obj, dict) or "messages" not in obj:
53
+ return None, [f"{source_name}:{line_no}: missing top-level 'messages' object"], tools_found
54
+
55
+ messages = obj["messages"]
56
+ if not isinstance(messages, list) or len(messages) < 3:
57
+ return None, [f"{source_name}:{line_no}: 'messages' must be a list of >= 3 turns"], tools_found
58
+
59
+ roles: list[str] = []
60
+ for idx, msg in enumerate(messages):
61
+ if not isinstance(msg, dict):
62
+ errors.append(f"{source_name}:{line_no}: message[{idx}] is not an object")
63
+ continue
64
+ role = msg.get("role")
65
+ content = msg.get("content")
66
+ if role not in VALID_ROLES:
67
+ errors.append(f"{source_name}:{line_no}: message[{idx}] invalid role '{role}'")
68
+ if not isinstance(content, str) or not content.strip():
69
+ errors.append(f"{source_name}:{line_no}: message[{idx}] empty content")
70
+ continue
71
+ roles.append(str(role))
72
+
73
+ if role == "assistant":
74
+ # Check <think> balance
75
+ open_think = content.count("<think>")
76
+ close_think = content.count("</think>")
77
+ if open_think != close_think:
78
+ errors.append(f"{source_name}:{line_no}: unbalanced <think> tags ({open_think} vs {close_think})")
79
+
80
+ # Check <tool_call> tag balance & strict JSON payload
81
+ open_tc = content.count("<tool_call>")
82
+ close_tc = content.count("</tool_call>")
83
+ if open_tc != close_tc:
84
+ errors.append(f"{source_name}:{line_no}: unbalanced <tool_call> tags ({open_tc} vs {close_tc})")
85
+ for match in TOOL_CALL_RE.finditer(content):
86
+ inner = match.group(1).strip()
87
+ try:
88
+ payload = json.loads(inner)
89
+ except json.JSONDecodeError as exc:
90
+ errors.append(f"{source_name}:{line_no}: invalid <tool_call> JSON ({exc})")
91
+ continue
92
+ if not isinstance(payload, dict):
93
+ errors.append(f"{source_name}:{line_no}: <tool_call> payload must be JSON object")
94
+ continue
95
+ tool_name = payload.get("name")
96
+ tool_args = payload.get("arguments")
97
+ if not isinstance(tool_name, str) or not tool_name.strip():
98
+ errors.append(f"{source_name}:{line_no}: <tool_call> missing string 'name'")
99
+ if not isinstance(tool_args, dict):
100
+ errors.append(f"{source_name}:{line_no}: <tool_call> missing object 'arguments'")
101
+ else:
102
+ tools_found.append(str(tool_name))
103
+
104
+ if roles and roles[0] != "system":
105
+ errors.append(f"{source_name}:{line_no}: first message must be 'system' (got '{roles[0]}')")
106
+ if "user" not in roles or "assistant" not in roles:
107
+ errors.append(f"{source_name}:{line_no}: must contain both 'user' and 'assistant' roles")
108
+ if roles and roles[-1] != "assistant":
109
+ errors.append(f"{source_name}:{line_no}: conversation must end with 'assistant'")
110
+
111
+ if errors:
112
+ return None, errors, tools_found
113
+
114
+ cleaned = {
115
+ "messages": [
116
+ {"role": str(m["role"]), "content": str(m["content"]).strip()}
117
+ for m in messages
118
+ ]
119
+ }
120
+ return cleaned, [], tools_found
121
+
122
+
123
+ def fingerprint(record: dict[str, Any]) -> str:
124
+ # Normalize non-system turns for exact duplicate detection
125
+ key_parts = [
126
+ f"{m['role']}:{re.sub(r'\s+', ' ', m['content'].strip().lower())}"
127
+ for m in record["messages"]
128
+ if m["role"] != "system"
129
+ ]
130
+ return hashlib.sha256("||".join(key_parts).encode("utf-8")).hexdigest()
131
+
132
+
133
+ def load_jsonl(path: Path) -> tuple[list[dict[str, Any]], list[str], Counter[str]]:
134
+ records: list[dict[str, Any]] = []
135
+ all_errors: list[str] = []
136
+ tool_counts: Counter[str] = Counter()
137
+
138
+ with path.open("r", encoding="utf-8") as f:
139
+ for line_no, raw in enumerate(f, start=1):
140
+ stripped = raw.strip()
141
+ if not stripped:
142
+ continue
143
+ rec, errs, tools = validate_record(stripped, line_no, path.name)
144
+ if errs:
145
+ all_errors.extend(errs)
146
+ elif rec is not None:
147
+ records.append(rec)
148
+ tool_counts.update(tools)
149
+ return records, all_errors, tool_counts
150
+
151
+
152
+ def write_jsonl(path: Path, records: list[dict[str, Any]]) -> None:
153
+ path.parent.mkdir(parents=True, exist_ok=True)
154
+ with path.open("w", encoding="utf-8", newline="\n") as f:
155
+ for rec in records:
156
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
157
+
158
+
159
+ def main() -> int:
160
+ if hasattr(sys.stdout, "reconfigure"):
161
+ try:
162
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
163
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
164
+ except Exception:
165
+ pass
166
+
167
+ studio_root = Path(__file__).resolve().parent.parent
168
+ parser = argparse.ArgumentParser(
169
+ description="Validate, deduplicate, merge, and 90/10 split Hycean-1 Omni ChatML datasets."
170
+ )
171
+ parser.add_argument(
172
+ "--base",
173
+ type=Path,
174
+ default=studio_root / "datasets" / "hycean_omni_dataset.jsonl",
175
+ help="Path to base hycean_omni_dataset.jsonl",
176
+ )
177
+ parser.add_argument(
178
+ "--ensemble-distill",
179
+ type=Path,
180
+ default=studio_root / "datasets" / "hycean_multi_teacher_distilled.jsonl",
181
+ help="Optional path to unified 4-teacher datasets/hycean_multi_teacher_distilled.jsonl",
182
+ )
183
+ parser.add_argument(
184
+ "--kimi-distill",
185
+ type=Path,
186
+ default=studio_root / "datasets" / "kimi_k3_distilled.jsonl",
187
+ help="Optional path to Kimi K3.1 Pro distilled datasets/kimi_k3_distilled.jsonl",
188
+ )
189
+ parser.add_argument(
190
+ "--inkling-distill",
191
+ type=Path,
192
+ default=studio_root / "datasets" / "inkling_2_mini_distilled.jsonl",
193
+ help="Optional path to Inkling-2 Mini distilled datasets/inkling_2_mini_distilled.jsonl",
194
+ )
195
+ parser.add_argument(
196
+ "--deepseek-distill",
197
+ type=Path,
198
+ default=studio_root / "datasets" / "deepseek_v4_1_flash_distilled.jsonl",
199
+ help="Optional path to DeepSeek-V4.1 Flash distilled datasets/deepseek_v4_1_flash_distilled.jsonl",
200
+ )
201
+ parser.add_argument(
202
+ "--glm-distill",
203
+ type=Path,
204
+ default=studio_root / "datasets" / "glm_5_3_distilled.jsonl",
205
+ help="Optional path to GLM-5.3 distilled datasets/glm_5_3_distilled.jsonl",
206
+ )
207
+ parser.add_argument(
208
+ "--distill",
209
+ type=Path,
210
+ default=studio_root / "datasets" / "hycean_distill_dataset.jsonl",
211
+ help="Optional path to user-exported hycean_distill_dataset.jsonl",
212
+ )
213
+ parser.add_argument(
214
+ "--extra",
215
+ type=Path,
216
+ action="append",
217
+ default=[],
218
+ help="Optional additional ChatML JSONL dataset path(s) to merge",
219
+ )
220
+ parser.add_argument(
221
+ "--out-dir",
222
+ type=Path,
223
+ default=studio_root / "datasets" / "processed",
224
+ help="Output directory for merged train.jsonl / eval.jsonl",
225
+ )
226
+ parser.add_argument("--eval-ratio", type=float, default=0.10, help="Eval split fraction (default 0.10)")
227
+ parser.add_argument("--min-examples", type=int, default=220, help="Minimum required valid unique examples")
228
+ parser.add_argument("--seed", type=int, default=42, help="Deterministic shuffle seed")
229
+ args = parser.parse_args()
230
+
231
+ if not args.base.exists():
232
+ print(f"[ERROR] Base dataset not found: {args.base}", file=sys.stderr)
233
+ return 1
234
+
235
+ all_records, errors, tool_counts = load_jsonl(args.base)
236
+ sources_used = [str(args.base)]
237
+
238
+ optional_sources: list[Path] = []
239
+ for opt in (
240
+ args.ensemble_distill,
241
+ args.kimi_distill,
242
+ args.inkling_distill,
243
+ args.deepseek_distill,
244
+ args.glm_distill,
245
+ args.distill,
246
+ ):
247
+ if opt:
248
+ optional_sources.append(opt)
249
+ optional_sources.extend(args.extra or [])
250
+
251
+ seen_paths: set[Path] = {args.base.resolve()}
252
+ for extra_path in optional_sources:
253
+ if extra_path.exists():
254
+ resolved = extra_path.resolve()
255
+ if resolved in seen_paths:
256
+ continue
257
+ seen_paths.add(resolved)
258
+ extra_recs, extra_errs, extra_tools = load_jsonl(extra_path)
259
+ all_records.extend(extra_recs)
260
+ errors.extend(extra_errs)
261
+ tool_counts.update(extra_tools)
262
+ sources_used.append(str(extra_path))
263
+
264
+ if errors:
265
+ print(f"[ERROR] Validation failed with {len(errors)} issue(s):", file=sys.stderr)
266
+ for err in errors[:30]:
267
+ print(f" - {err}", file=sys.stderr)
268
+ return 1
269
+
270
+ seen: set[str] = set()
271
+ unique_records: list[dict[str, Any]] = []
272
+ duplicates = 0
273
+ for rec in all_records:
274
+ fp = fingerprint(rec)
275
+ if fp in seen:
276
+ duplicates += 1
277
+ continue
278
+ seen.add(fp)
279
+ unique_records.append(rec)
280
+
281
+ total = len(unique_records)
282
+ if total < args.min_examples:
283
+ print(
284
+ f"[ERROR] Too few unique valid examples: {total} < {args.min_examples}",
285
+ file=sys.stderr,
286
+ )
287
+ return 1
288
+
289
+ tr_count = 0
290
+ think_count = 0
291
+ multi_turn_count = 0
292
+ for rec in unique_records:
293
+ user_texts = [m["content"] for m in rec["messages"] if m["role"] == "user"]
294
+ asst_texts = [m["content"] for m in rec["messages"] if m["role"] == "assistant"]
295
+ if any(detect_turkish(t) for t in user_texts):
296
+ tr_count += 1
297
+ if any("<think>" in t for t in asst_texts):
298
+ think_count += 1
299
+ if len(user_texts) > 1:
300
+ multi_turn_count += 1
301
+
302
+ shuffled = list(unique_records)
303
+ rng = random.Random(args.seed)
304
+ rng.shuffle(shuffled)
305
+
306
+ eval_size = max(1, int(round(total * args.eval_ratio)))
307
+ eval_records = shuffled[:eval_size]
308
+ train_records = shuffled[eval_size:]
309
+
310
+ write_jsonl(args.out_dir / "merged_all.jsonl", unique_records)
311
+ write_jsonl(args.out_dir / "train.jsonl", train_records)
312
+ write_jsonl(args.out_dir / "eval.jsonl", eval_records)
313
+
314
+ en_count = total - tr_count
315
+ print("=== Hycean-1 Omni Dataset Validation Report ===")
316
+ print(f"Sources : {', '.join(sources_used)}")
317
+ print(f"Valid examples : {total} (duplicates removed: {duplicates}, invalid: 0)")
318
+ print(f"Language split : TR={tr_count} ({tr_count/total*100:.1f}%), EN={en_count} ({en_count/total*100:.1f}%)")
319
+ print(f"Multi-turn : {multi_turn_count}")
320
+ print(f"<think> chains : {think_count}")
321
+ print(f"Tool calls : {sum(tool_counts.values())} total across {len(tool_counts)} tools")
322
+ for name, count in sorted(tool_counts.items()):
323
+ print(f" - {name}: {count}")
324
+ print(f"Split written : train={len(train_records)} ({args.out_dir / 'train.jsonl'}), "
325
+ f"eval={len(eval_records)} ({args.out_dir / 'eval.jsonl'})")
326
+ return 0
327
+
328
+
329
+ if __name__ == "__main__":
330
+ raise SystemExit(main())