File size: 4,837 Bytes
c2c5af9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
ViuAI-10M 50:50 Bilingual Chat Data Pipeline (Strict 1:1 English & Hinglish).

Fixes applied from Senior Engineering Audit:
1. Removed translation dataset (`findnitai/english-to-hinglish`) so the model learns
   to answer prompts rather than translate them.
2. Enforces strict 1:1 (50:50) pairing — stops cleanly when either stream finishes
   so the ratio never drifts toward English.
"""

import os
import sys
import json
import random
from typing import Generator, Dict

project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

DATA_DIR = os.path.join(project_root, "data")
TRAIN_PATH = os.path.join(DATA_DIR, "train_50_50.jsonl")
EVAL_PATH = os.path.join(DATA_DIR, "eval_50_50.jsonl")
CORPUS_PATH = os.path.join(DATA_DIR, "bilingual_corpus.txt")


def stream_english_datasets() -> Generator[Dict, None, None]:
    """Stream verified public English conversational datasets."""
    from datasets import load_dataset

    # 1. Databricks Dolly-15k
    try:
        print("[*] Streaming Databricks Dolly-15k...")
        ds = load_dataset("databricks/databricks-dolly-15k", split="train", streaming=True)
        for row in ds:
            ins = row.get("instruction", "").strip()
            ctx = row.get("context", "").strip()
            resp = row.get("response", "").strip()
            if ins and resp:
                content = f"{ins}\n\nContext:\n{ctx}" if ctx else ins
                yield {"messages": [{"role": "user", "content": content}, {"role": "assistant", "content": resp}]}
    except Exception as e:
        print(f"  [Dolly note]: {e}")

    # 2. SmolTalk (Multi-turn chat)
    try:
        print("[*] Streaming SmolTalk (conversations)...")
        ds = load_dataset("HuggingFaceTB/smoltalk", "all", split="train", streaming=True)
        for row in ds:
            msgs = row.get("messages", [])
            if len(msgs) >= 2:
                formatted = [
                    {"role": m["role"], "content": m["content"].strip()}
                    for m in msgs
                    if m.get("role") in ("user", "assistant") and m.get("content")
                ]
                if len(formatted) >= 2:
                    yield {"messages": formatted}
    except Exception as e:
        print(f"  [SmolTalk note]: {e}")


def stream_hinglish_datasets() -> Generator[Dict, None, None]:
    """Stream verified public Hinglish chat/instruction datasets (no translation tasks)."""
    from datasets import load_dataset

    # NebulaByte/alpaca-gpt4-hindi-hinglish (52k Roman Hinglish instructions & responses)
    try:
        print("[*] Streaming NebulaByte Alpaca Hinglish...")
        ds = load_dataset("NebulaByte/alpaca-gpt4-hindi-hinglish", split="train", streaming=True)
        for row in ds:
            user = row.get("input_hinglish", "").strip()
            assistant = row.get("output_hinglish", "").strip()
            if user and assistant:
                yield {"messages": [{"role": "user", "content": user}, {"role": "assistant", "content": assistant}]}
    except Exception as e:
        print(f"  [NebulaByte Hinglish note]: {e}")


def main():
    print("=" * 65)
    print("  ViuAI-10M: Strict 50:50 English-Hinglish Chat Data Pipeline")
    print("=" * 65)

    os.makedirs(DATA_DIR, exist_ok=True)
    en_gen = stream_english_datasets()
    hi_gen = stream_hinglish_datasets()

    print("[*] Interleaving strict 1:1 English & Hinglish chat pairs...")
    train_count = 0
    eval_count = 0
    en_count = 0
    hi_count = 0

    with open(TRAIN_PATH, "w", encoding="utf-8") as f_tr, \
         open(EVAL_PATH, "w", encoding="utf-8") as f_ev, \
         open(CORPUS_PATH, "w", encoding="utf-8") as f_cp:

        while True:
            en = next(en_gen, None)
            hi = next(hi_gen, None)
            # Stop when either stream ends to preserve strict 50:50 balance
            if en is None or hi is None:
                break

            en_count += 1
            hi_count += 1
            for s in (en, hi):
                if random.random() < 0.95:
                    f_tr.write(json.dumps(s, ensure_ascii=False) + "\n")
                    train_count += 1
                else:
                    f_ev.write(json.dumps(s, ensure_ascii=False) + "\n")
                    eval_count += 1

                for msg in s["messages"]:
                    f_cp.write(msg["content"].replace("\n", " ") + "\n")

            if (train_count + eval_count) % 10000 == 0:
                print(f"  Processed {train_count + eval_count:,} chats (EN={en_count:,}, HI={hi_count:,})...")

    print(f"\n[DONE] Strict 50:50 Balance: EN={en_count:,} | HI={hi_count:,}")
    print(f"  Train:  {train_count:,} chats -> {TRAIN_PATH}")
    print(f"  Eval:   {eval_count:,} chats -> {EVAL_PATH}")


if __name__ == "__main__":
    main()