File size: 23,667 Bytes
b3d361d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
"""
Prepare Korean instruction-following data for Supervised Fine-Tuning (SFT).

Downloads Korean SFT datasets from HuggingFace, normalises them to a common
JSONL format, applies quality filters, deduplicates, and splits into
train / validation sets.

Output format (one JSON object per line):
    {"instruction": "...", "input": "...", "output": "..."}

Usage:
    python data/prepare_sft_data.py
    python data/prepare_sft_data.py --output_dir data/sft/
"""

from __future__ import annotations

import argparse
import json
import os
import random
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional, Tuple


# ---------------------------------------------------------------------------
# Type alias
# ---------------------------------------------------------------------------

Sample = Dict[str, str]  # {"instruction": str, "input": str, "output": str}


# ---------------------------------------------------------------------------
# Dataset-specific loaders
# ---------------------------------------------------------------------------

def _normalize_sample(
    instruction: str,
    input_text: str,
    output: str,
) -> Optional[Sample]:
    """
    Return a normalised sample dict, or None if any required field is missing.

    All fields are stripped of leading/trailing whitespace.  ``input`` is
    allowed to be empty (many alpaca-style datasets leave it blank).
    """
    instruction = (instruction or "").strip()
    input_text  = (input_text  or "").strip()
    output      = (output      or "").strip()

    if not instruction or not output:
        return None

    return {"instruction": instruction, "input": input_text, "output": output}


def load_kor_openorca_platypus(dataset_name: str) -> List[Sample]:
    """
    kyujinpy/KOR-OpenOrca-Platypus-v3

    Expected columns: instruction, input, output
    Falls back to system_prompt/question/response if needed.
    """
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", trust_remote_code=True)
    cols = set(ds.column_names)
    samples: List[Sample] = []

    for row in ds:
        # Primary column mapping
        if "instruction" in cols and "output" in cols:
            instruction = row.get("instruction", "") or ""
            input_text  = row.get("input", "") or ""
            output      = row.get("output", "") or ""
        # Fallback: question / response style
        elif "question" in cols and "response" in cols:
            instruction = row.get("question", "") or ""
            input_text  = ""
            output      = row.get("response", "") or ""
        # Fallback: conversations list
        elif "conversations" in cols:
            sample = _extract_from_conversations(row.get("conversations", []))
            if sample is None:
                continue
            instruction, input_text, output = sample
        else:
            # Last resort: dump all string fields and skip
            continue

        norm = _normalize_sample(instruction, input_text, output)
        if norm is not None:
            samples.append(norm)

    return samples


def load_kullm_v2(dataset_name: str) -> List[Sample]:
    """
    nlpai-lab/kullm-v2

    The KULLM-v2 dataset typically uses:
        - ``instruction``  (ํ•œ๊ตญ์–ด ์ง€์‹œ๋ฌธ)
        - ``input``        (์ถ”๊ฐ€ ์ปจํ…์ŠคํŠธ, optional)
        - ``output``       (์‘๋‹ต)

    Some variants use ``context`` instead of ``input``, or nest content under
    ``text`` as a formatted prompt.  We inspect at runtime and adapt.
    """
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", trust_remote_code=True)
    cols = set(ds.column_names)
    samples: List[Sample] = []

    for row in ds:
        if "instruction" in cols and "output" in cols:
            instruction = row.get("instruction", "") or ""
            # Some KULLM records use "context" as the secondary input field.
            input_text  = (row.get("input", "") or row.get("context", "")) or ""
            output      = row.get("output", "") or ""

        elif "text" in cols:
            # Alpaca-formatted single-string: parse out the fields.
            parsed = _parse_alpaca_text(row.get("text", "") or "")
            if parsed is None:
                continue
            instruction, input_text, output = parsed

        elif "conversations" in cols:
            result = _extract_from_conversations(row.get("conversations", []))
            if result is None:
                continue
            instruction, input_text, output = result

        else:
            continue

        norm = _normalize_sample(instruction, input_text, output)
        if norm is not None:
            samples.append(norm)

    return samples


def load_ko_alpaca(dataset_name: str) -> List[Sample]:
    """
    junhochoi/ko-alpaca-12k

    Standard Alpaca format: instruction, input, output
    """
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", trust_remote_code=True)
    cols = set(ds.column_names)
    samples: List[Sample] = []

    for row in ds:
        if "instruction" in cols and "output" in cols:
            instruction = row.get("instruction", "") or ""
            input_text  = row.get("input", "") or ""
            output      = row.get("output", "") or ""

        elif "conversations" in cols:
            result = _extract_from_conversations(row.get("conversations", []))
            if result is None:
                continue
            instruction, input_text, output = result

        else:
            continue

        norm = _normalize_sample(instruction, input_text, output)
        if norm is not None:
            samples.append(norm)

    return samples


def load_korean_safe_conversation(dataset_name: str) -> List[Sample]:
    """jojo0217/korean_safe_conversation โ€” ์•ˆ์ „ ์ •๋ ฌ ํ•œ๊ตญ์–ด ๋Œ€ํ™”"""
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", token=os.environ.get("HF_TOKEN"))
    samples: List[Sample] = []
    for item in ds:
        s = _normalize_sample(
            instruction=item.get("instruction", ""),
            input_text=item.get("input", ""),
            output=item.get("output", ""),
        )
        if s:
            samples.append(s)
    return samples


def load_evol_instruct_korean(dataset_name: str) -> List[Sample]:
    """FreedomIntelligence/Evol-Instruct-Korean โ€” ๋ณต์žกํ•œ ์ถ”๋ก /์ฝ”๋“œ"""
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", token=os.environ.get("HF_TOKEN"))
    samples: List[Sample] = []
    for item in ds:
        conversations = item.get("conversations", [])
        if len(conversations) >= 2:
            instruction = conversations[0].get("value", "")
            output = conversations[1].get("value", "")
            s = _normalize_sample(instruction=instruction, input_text="", output=output)
            if s:
                samples.append(s)
    return samples


def load_kovast(dataset_name: str, max_samples: int = 50000) -> List[Sample]:
    """maywell/koVast โ€” ๋ฉ€ํ‹ฐํ„ด ๋Œ€ํ™” (์ฒซ ํ„ด๋งŒ ์ถ”์ถœ)"""
    from datasets import load_dataset  # type: ignore

    ds = load_dataset(dataset_name, split="train", token=os.environ.get("HF_TOKEN"))
    samples: List[Sample] = []
    for item in ds:
        if len(samples) >= max_samples:
            break
        conversations = item.get("conversations", [])
        if len(conversations) >= 2:
            human_turn = next((c for c in conversations if c.get("from") == "human"), None)
            gpt_turn   = next((c for c in conversations if c.get("from") == "gpt"),   None)
            if human_turn and gpt_turn:
                s = _normalize_sample(
                    instruction=human_turn.get("value", ""),
                    input_text="",
                    output=gpt_turn.get("value", ""),
                )
                if s:
                    samples.append(s)
    return samples


# ---------------------------------------------------------------------------
# Format-parsing helpers
# ---------------------------------------------------------------------------

def _extract_from_conversations(
    conversations: list,
) -> Optional[Tuple[str, str, str]]:
    """
    Extract (instruction, input, output) from a conversations list.

    Handles both dict-based conversation items (with "from"/"value" or
    "role"/"content" keys) and plain string lists.

    Returns None if the conversation does not contain at least one user turn
    followed by one assistant turn.
    """
    if not conversations:
        return None

    user_msg: Optional[str] = None
    assistant_msg: Optional[str] = None

    for item in conversations:
        if isinstance(item, dict):
            # OpenAI / ShareGPT style: {"role": "user", "content": "..."}
            role    = (item.get("role") or item.get("from") or "").lower()
            content = (item.get("content") or item.get("value") or "").strip()
        elif isinstance(item, str):
            # Occasionally items are raw strings; treat alternating as user/asst.
            content = item.strip()
            role    = "user" if user_msg is None else "assistant"
        else:
            continue

        if not content:
            continue

        if role in ("user", "human") and user_msg is None:
            user_msg = content
        elif role in ("assistant", "gpt", "bot") and user_msg is not None and assistant_msg is None:
            assistant_msg = content

        if user_msg is not None and assistant_msg is not None:
            break

    if user_msg is None or assistant_msg is None:
        return None

    return user_msg, "", assistant_msg


def _parse_alpaca_text(text: str) -> Optional[Tuple[str, str, str]]:
    """
    Parse an Alpaca-formatted text string of the form::

        Below is an instruction...

        ### Instruction:
        <instruction>

        ### Input:
        <input>

        ### Response:
        <response>

    Returns (instruction, input, response) or None on failure.
    """
    instruction = ""
    input_text  = ""
    output      = ""

    current_section: Optional[str] = None
    buffer: List[str] = []

    for line in text.splitlines():
        stripped = line.strip()
        lower    = stripped.lower()

        if lower.startswith("### instruction"):
            if current_section == "input":
                input_text = "\n".join(buffer).strip()
            elif current_section == "response":
                output = "\n".join(buffer).strip()
            current_section = "instruction"
            buffer = []
        elif lower.startswith("### input"):
            if current_section == "instruction":
                instruction = "\n".join(buffer).strip()
            current_section = "input"
            buffer = []
        elif lower.startswith("### response") or lower.startswith("### output"):
            if current_section == "instruction":
                instruction = "\n".join(buffer).strip()
            elif current_section == "input":
                input_text = "\n".join(buffer).strip()
            current_section = "response"
            buffer = []
        else:
            if current_section is not None:
                buffer.append(line)

    # Flush final buffer
    if current_section == "instruction":
        instruction = "\n".join(buffer).strip()
    elif current_section == "input":
        input_text = "\n".join(buffer).strip()
    elif current_section == "response":
        output = "\n".join(buffer).strip()

    if not instruction or not output:
        return None

    return instruction, input_text, output


# ---------------------------------------------------------------------------
# Quality filtering
# ---------------------------------------------------------------------------

MIN_OUTPUT_LEN     = 10      # characters
MAX_OUTPUT_LEN     = 8_000   # characters


def _quality_filter(sample: Sample) -> bool:
    """ํ’ˆ์งˆ ํ•„ํ„ฐ: ๊ธธ์ด + ๋ฐ˜๋ณต + ํ•œ๊ตญ์–ด ๋น„์œจ"""
    instruction = sample["instruction"]
    output      = sample["output"]

    # ๊ธธ์ด ํ•„ํ„ฐ
    if len(instruction) < 10 or len(output) < 50:
        return False
    if len(output) > 3000:  # [์ˆ˜์ •] 4000โ†’3000 ๊ธด ์‘๋‹ต ์ œ๊ฑฐ
        return False

    # ํ•œ๊ตญ์–ด ๋น„์œจ (์ตœ์†Œ 50% ์ด์ƒ ํ•œ๊ธ€ ๋ฌธ์ž) [์ˆ˜์ •] 30%โ†’50%
    ko_chars = sum(1 for c in output if '๊ฐ€' <= c <= 'ํžฃ')
    if len(output) > 0 and ko_chars / len(output) < 0.5:
        return False

    # ๋ฐ˜๋ณต ํ‡ดํ™” ํ•„ํ„ฐ (3-gram ๋ฐ˜๋ณต ๋น„์œจ)
    words = output.split()
    if len(words) > 10:
        trigrams = [tuple(words[i:i+3]) for i in range(len(words) - 2)]
        if len(trigrams) > 0:
            unique_ratio = len(set(trigrams)) / len(trigrams)
            if unique_ratio < 0.5:  # 50% ์ด์ƒ ๋ฐ˜๋ณต์ด๋ฉด ์ œ๊ฑฐ
                return False

    return True


def _enhanced_quality_filter(sample: Sample) -> Optional[Sample]:
    """
    [์ถ”๊ฐ€] ๋ฐ์ดํ„ฐ ํ’ˆ์งˆ ์˜ค์—ผ ํ•„ํ„ฐ:
      1. EOS ๋ฆฌํ„ฐ๋Ÿด ํ…์ŠคํŠธ ์ œ๊ฑฐ
      2. ์งˆ๋ฌธ:/๋‹ต๋ณ€: ํŒจํ„ด ์˜ค์—ผ ํ•„ํ„ฐ
      3. 50์ž ๋ฏธ๋งŒ output ํ•„ํ„ฐ
    """
    output = sample.get("output", "")
    # 1. EOS ๋ฆฌํ„ฐ๋Ÿด ์ œ๊ฑฐ
    output = output.replace("</s>", "").replace("<|endoftext|>", "").strip()
    # 2. Q/A ํŒจํ„ด ์˜ค์—ผ ํ•„ํ„ฐ
    if re.search(r"(์งˆ๋ฌธ\s*:|๋‹ต๋ณ€\s*:|### Q|### A)", output):
        return None
    # 3. ๋„ˆ๋ฌด ์งง์€ output ํ•„ํ„ฐ
    if len(output) < 50:
        return None
    sample["output"] = output
    return sample


def quality_filter(samples: List[Sample]) -> List[Sample]:
    """
    Remove samples that fail basic quality checks:
      - Empty instruction
      - Output shorter than MIN_OUTPUT_LEN characters
      - Output longer than MAX_OUTPUT_LEN characters
      - Korean character ratio below 30 %
      - 3-gram repetition ratio above 50 %
      - [์ถ”๊ฐ€] EOS ๋ฆฌํ„ฐ๋Ÿด, Q/A ํŒจํ„ด ์˜ค์—ผ, 50์ž ๋ฏธ๋งŒ
    """
    filtered: List[Sample] = []
    for s in samples:
        if not s["instruction"]:
            continue
        # [์ถ”๊ฐ€] Enhanced quality filter first (cleans output & rejects bad ones)
        s = _enhanced_quality_filter(s)
        if s is None:
            continue
        out_len = len(s["output"])
        if out_len < MIN_OUTPUT_LEN:
            continue
        if out_len > MAX_OUTPUT_LEN:
            continue
        if not _quality_filter(s):
            continue
        filtered.append(s)
    return filtered


def deduplicate(samples: List[Sample]) -> List[Sample]:
    """
    Remove duplicate samples based on instruction text (case-sensitive, exact).
    The first occurrence of each instruction is kept; subsequent ones are dropped.
    """
    seen: set[str] = set()
    unique: List[Sample] = []
    for s in samples:
        key = s["instruction"]
        if key not in seen:
            seen.add(key)
            unique.append(s)
    return unique


def apply_weighted_sampling(
    all_samples_with_source: Dict[str, List[Sample]],
    weights_dict: Dict[str, float],
) -> List[Sample]:
    """
    ์†Œ์Šค๋ณ„ ๊ฐ€์ค‘์น˜์— ๋”ฐ๋ผ ์ƒ˜ํ”Œ์„ ์—…์ƒ˜ํ”Œ๋ง/๋‹ค์šด์ƒ˜ํ”Œ๋ง.

    weights > 1.0: ์—…์ƒ˜ํ”Œ๋ง (๊ธฐ๋ณธ + ์ถ”๊ฐ€ ๋ณต์ œ)
    weights < 1.0: ๋‹ค์šด์ƒ˜ํ”Œ๋ง (๋žœ๋ค ์ œ๊ฑฐ, ์ตœ์†Œ 1๊ฐœ ์œ ์ง€)
    weights == 1.0: ๋ณ€๊ฒฝ ์—†์Œ

    Args:
        all_samples_with_source: ์†Œ์Šค๋ช… โ†’ ์ƒ˜ํ”Œ ๋ฆฌ์ŠคํŠธ ๋งคํ•‘
        weights_dict: ์†Œ์Šค๋ช… โ†’ ๊ฐ€์ค‘์น˜ ๋งคํ•‘ (ํ‚ค ์—†์œผ๋ฉด 1.0 ์‚ฌ์šฉ)

    Returns:
        ๊ฐ€์ค‘์น˜ ์ ์šฉ ํ›„ ํ•ฉ์ณ์ง„ ์ƒ˜ํ”Œ ๋ฆฌ์ŠคํŠธ
    """
    result: List[Sample] = []
    for source_name, samples in all_samples_with_source.items():
        if not samples:
            continue
        weight = weights_dict.get(source_name, 1.0)
        if weight >= 1.0:
            # ์—…์ƒ˜ํ”Œ๋ง: ์›๋ณธ ์ „์ฒด ํฌํ•จ + ์ถ”๊ฐ€ ๋ณต์ œ
            result.extend(samples)
            extra = int(len(samples) * (weight - 1.0))
            if extra > 0:
                result.extend(random.choices(samples, k=extra))
        else:
            # ๋‹ค์šด์ƒ˜ํ”Œ๋ง: weight ๋น„์œจ๋งŒํผ๋งŒ ์œ ์ง€ (์ตœ์†Œ 1๊ฐœ)
            keep = max(1, int(len(samples) * weight))
            result.extend(random.sample(samples, keep))
        target = int(len(samples) * weight)
        print(f"  {source_name}: {len(samples):,} โ†’ {target:,} (ร—{weight})")
    return result


# ---------------------------------------------------------------------------
# I/O helpers
# ---------------------------------------------------------------------------

def save_jsonl(samples: List[Sample], path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with open(path, "w", encoding="utf-8") as fh:
        for s in samples:
            fh.write(json.dumps(s, ensure_ascii=False) + "\n")


def _avg_len(samples: List[Sample], field: str) -> float:
    if not samples:
        return 0.0
    return sum(len(s[field]) for s in samples) / len(samples)


# ---------------------------------------------------------------------------
# Dataset registry & sampling weights
# ---------------------------------------------------------------------------

# Weights control upsampling/downsampling relative to a baseline of 1.0.
# Values >1 cause the source to be overrepresented; values <1 underrepresent.
DATASET_WEIGHTS: Dict[str, float] = {
    # ํ‚ค๋Š” DATASET_REGISTRY ์˜ display_name ๊ณผ ์ •ํ™•ํžˆ ์ผ์น˜ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
    "KOR-OpenOrca-Platypus-v3":   1.5,  # [์ˆ˜์ •] 2.0โ†’1.5
    "kullm-v2":                   1.0,  # ๊ธฐ๋ณธ๊ฐ’
    "ko-alpaca-12k":              2.0,  # ๊ณ ํ’ˆ์งˆ โ†’ 2๋ฐฐ ์ƒ˜ํ”Œ๋ง
    "korean_safe_conversation":   1.5,
    "evol-instruct-korean":       2.0,  # [์ˆ˜์ •] 1.5โ†’2.0
    "kovast":                     0.5,  # [์ˆ˜์ •] 0.8โ†’0.5 ๋‹ค์šด์ƒ˜ํ”Œ๋ง ๊ฐ•ํ™”
}

# Each entry: (display_name, hf_repo_id, loader_function)
DATASET_REGISTRY = [
    (
        "KOR-OpenOrca-Platypus-v3",
        "kyujinpy/KOR-OpenOrca-Platypus-v3",
        load_kor_openorca_platypus,
    ),
    (
        "kullm-v2",
        "nlpai-lab/kullm-v2",
        load_kullm_v2,
    ),
    (
        "ko-alpaca-12k",
        "junhochoi/ko-alpaca-12k",
        load_ko_alpaca,
    ),
    (
        "korean_safe_conversation",
        "jojo0217/korean_safe_conversation",
        load_korean_safe_conversation,
    ),
    (
        "evol-instruct-korean",
        "FreedomIntelligence/Evol-Instruct-Korean",
        load_evol_instruct_korean,
    ),
    (
        "kovast",
        "maywell/koVast",
        load_kovast,
    ),
]


# ---------------------------------------------------------------------------
# Argument parsing
# ---------------------------------------------------------------------------

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Download and prepare Korean SFT datasets from HuggingFace. "
            "Outputs train.jsonl and val.jsonl in the specified directory."
        )
    )
    parser.add_argument(
        "--output_dir",
        default="data/sft/",
        help="Directory where train.jsonl and val.jsonl will be written "
             "(default: data/sft/)",
    )
    parser.add_argument(
        "--val_split",
        type=float,
        default=0.05,
        help="Fraction of samples reserved for validation (default: 0.05)",
    )
    parser.add_argument(
        "--seed",
        type=int,
        default=42,
        help="Random seed for shuffling before the train/val split (default: 42)",
    )
    parser.add_argument(
        "--min_output_len",
        type=int,
        default=MIN_OUTPUT_LEN,
        help=f"Minimum output length in characters (default: {MIN_OUTPUT_LEN})",
    )
    parser.add_argument(
        "--max_output_len",
        type=int,
        default=MAX_OUTPUT_LEN,
        help=f"Maximum output length in characters (default: {MAX_OUTPUT_LEN})",
    )
    return parser.parse_args()


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def main() -> None:
    args = parse_args()

    # Allow overriding filter thresholds via CLI
    global MIN_OUTPUT_LEN, MAX_OUTPUT_LEN
    MIN_OUTPUT_LEN = args.min_output_len
    MAX_OUTPUT_LEN = args.max_output_len

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # ---- Download and normalise each dataset --------------------------------

    samples_by_source: Dict[str, List[Sample]] = {}

    for display_name, repo_id, loader_fn in DATASET_REGISTRY:
        print(f"\nDownloading {display_name}...")
        try:
            raw = loader_fn(repo_id)
        except Exception as exc:  # pylint: disable=broad-except
            print(
                f"  WARNING: Failed to load {display_name} ({repo_id}): {exc}",
                file=sys.stderr,
            )
            continue

        before = len(raw)
        filtered = quality_filter(raw)
        after = len(filtered)

        print(f"  Loaded {before:,} samples -> {after:,} after filtering")
        samples_by_source[display_name] = filtered

    # ---- Weighted sampling --------------------------------------------------

    print("\n[Weighted Sampling]")
    all_samples: List[Sample] = apply_weighted_sampling(samples_by_source, DATASET_WEIGHTS)

    if not all_samples:
        print(
            "\nERROR: No samples were collected. "
            "Check network connectivity and dataset availability.",
            file=sys.stderr,
        )
        sys.exit(1)

    # ---- Deduplication -------------------------------------------------------

    total_before_dedup = len(all_samples)
    all_samples = deduplicate(all_samples)
    total_after_dedup = len(all_samples)

    print(f"\nTotal: {total_before_dedup:,} samples")
    print(f"After deduplication: {total_after_dedup:,} samples")

    # ---- Shuffle and split ---------------------------------------------------

    rng = random.Random(args.seed)
    rng.shuffle(all_samples)

    val_size   = max(1, int(len(all_samples) * args.val_split))
    train_size = len(all_samples) - val_size

    train_samples = all_samples[:train_size]
    val_samples   = all_samples[train_size:]

    print(f"Train: {len(train_samples):,} | Val: {len(val_samples):,}")

    # ---- Save ----------------------------------------------------------------

    train_path = output_dir / "train.jsonl"
    val_path   = output_dir / "val.jsonl"

    save_jsonl(train_samples, train_path)
    save_jsonl(val_samples,   val_path)

    # ---- Statistics ----------------------------------------------------------

    avg_instr_train  = _avg_len(train_samples, "instruction")
    avg_output_train = _avg_len(train_samples, "output")
    avg_input_train  = _avg_len(train_samples, "input")

    print(f"\nSaved to:")
    print(f"  {train_path} ({len(train_samples):,} samples)")
    print(f"  {val_path}   ({len(val_samples):,} samples)")
    print()
    print("--- Statistics (train set) ---")
    print(f"  Avg instruction length : {avg_instr_train:.1f} chars")
    print(f"  Avg input length       : {avg_input_train:.1f} chars")
    print(f"  Avg output length      : {avg_output_train:.1f} chars")

    # Rough token estimate (Korean ~1.5 chars per token for BPE tokenizers)
    est_tokens = (avg_instr_train + avg_input_train + avg_output_train) * len(train_samples) / 1.5
    print(f"  Est. tokens (train)    : ~{est_tokens / 1e6:.1f}M  (rough, 1.5 chars/tok)")


if __name__ == "__main__":
    main()