File size: 3,291 Bytes
ac5c307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Download DailyDialog, clean it, and write one formatted dialogue per line.

Output (data/train.txt, data/val.txt), one line each:

    <|user|> hello, how are you? <|bot|> i'm fine, thanks. <|eos|>

Phase 2 stops at text; tokenizer.py turns these into token arrays.
"""
import re
import sys

from datasets import load_dataset

from config import BOT, DATA_DIR, EOS, USER, DataConfig

# DailyDialog is distributed pre-tokenized: spaces before punctuation, and
# apostrophes split out as a standalone unicode ’ ("it ’ s"). Undo both so the
# BPE vocabulary is spent on words rather than on punctuation fragments.
UNICODE_FIXES = {
    "’": "'", "β€˜": "'", "β€œ": '"', "”": '"',
    "β€”": "-", "–": "-", "。": ".", "、": ",",
}
SPACED_APOSTROPHE = re.compile(r"\s*'\s*(?=(s|t|re|ve|ll|d|m|clock)\b)", re.I)
SPACE_BEFORE_PUNCT = re.compile(r"\s+([,.!?;:%])")
SPACE_AFTER_OPEN = re.compile(r"([($])\s+")
REPEATED_PUNCT = re.compile(r"([.!?,])\1{2,}")
WHITESPACE = re.compile(r"\s+")


def clean(text: str, lowercase: bool) -> str:
    for bad, good in UNICODE_FIXES.items():
        text = text.replace(bad, good)
    text = WHITESPACE.sub(" ", text)
    text = SPACED_APOSTROPHE.sub("'", text)
    text = SPACE_BEFORE_PUNCT.sub(r"\1", text)
    text = SPACE_AFTER_OPEN.sub(r"\1", text)
    text = REPEATED_PUNCT.sub(r"\1\1\1", text)
    text = text.strip()
    return text.lower() if lowercase else text


def format_dialogue(utterances: list[str], lowercase: bool) -> str | None:
    """Alternate speaker tags. Returns None if the dialogue is unusable."""
    parts = []
    for i, utterance in enumerate(utterances):
        cleaned = clean(utterance, lowercase)
        if not cleaned:
            return None  # a blank turn breaks the alternation; drop the dialogue
        parts.append(f"{USER if i % 2 == 0 else BOT} {cleaned}")
    # Must end on a bot turn, so every training example teaches a reply.
    if len(parts) < 2:
        return None
    if len(parts) % 2:
        parts.pop()
    return " ".join(parts) + f" {EOS}"


def build_split(rows, lowercase: bool) -> list[str]:
    lines = []
    for row in rows:
        line = format_dialogue(row["dialog"], lowercase)
        if line:
            lines.append(line)
    return lines


def main() -> None:
    cfg = DataConfig()
    ds = load_dataset(cfg.dataset, revision=cfg.revision)
    DATA_DIR.mkdir(exist_ok=True)

    # DailyDialog ships its own validation split; use it rather than carving up
    # train, so val loss stays comparable to published numbers.
    for split, name in [("train", "train"), ("validation", "val")]:
        lines = build_split(ds[split], cfg.lowercase)
        path = DATA_DIR / f"{name}.txt"
        path.write_text("\n".join(lines) + "\n", encoding="utf-8")
        words = sum(len(l.split()) for l in lines)
        print(
            f"{name:5s} {len(lines):6,} dialogues  {words:9,} whitespace-tokens"
            f"  -> {path.relative_to(DATA_DIR.parent)}"
        )
        print(f"      dropped {len(ds[split]) - len(lines)} unusable dialogues")

    print("\nsample:")
    for line in (DATA_DIR / "train.txt").read_text(encoding="utf-8").splitlines()[:2]:
        print(" ", line[:300], "..." if len(line) > 300 else "")


if __name__ == "__main__":
    sys.exit(main())