File size: 11,879 Bytes
afecc1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
UKS Seed Dataset Generator

Generates preprocessed training data from FineWeb dataset using:
- spaCy for linguistic features (POS, dependencies, lemmas, entities)
- XLNetTokenizer for subword tokenization

Outputs:
- pre_tokenized.jsonl.gz: Ready for model training
- intermediate.parquet: For exploration and custom tokenization
"""

import gzip
import hashlib
import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, Iterator, List, Optional

import spacy
from datasets import load_dataset
from transformers import XLNetTokenizer
from tqdm import tqdm


@dataclass
class SEEDConfig:
    max_samples: int = 10000
    batch_size: int = 100
    min_sentence_len: int = 5
    max_sentence_len: int = 512
    output_dir: Path = Path(__file__).parent / "train"
    cache_dir: Path = Path(__file__).parent / ".cache"
    hf_dataset_name: str = "HuggingFaceFW/fineweb"
    hf_dataset_split: str = "train"
    spacy_model: str = "en_core_web_sm"
    xlnet_model: str = "xlnet/xlnet-base-cased"


class SEEDDatasetGenerator:
    def __init__(self, config: Optional[SEEDConfig] = None):
        self.config = config or SEEDConfig()
        self._nlp = None
        self._tokenizer = None
        self._processed_ids: set = set()

    @property
    def nlp(self):
        if self._nlp is None:
            try:
                self._nlp = spacy.load(self.config.spacy_model)
            except OSError:
                import subprocess
                import sys

                print(f"Downloading spaCy model: {self.config.spacy_model}")
                subprocess.run(
                    [
                        sys.executable,
                        "-m",
                        "spacy",
                        "download",
                        self.config.spacy_model,
                    ],
                    check=True,
                )
                self._nlp = spacy.load(self.config.spacy_model)
        return self._nlp

    @property
    def tokenizer(self):
        if self._tokenizer is None:
            self._tokenizer = XLNetTokenizer.from_pretrained(self.config.xlnet_model)
        return self._tokenizer

    def _load_processed_ids(self) -> set:
        cache_file = self.config.cache_dir / "processed_ids.json"
        if cache_file.exists():
            with open(cache_file, "r") as f:
                return set(json.load(f))
        return set()

    def _save_processed_ids(self):
        cache_file = self.config.cache_dir / "processed_ids.json"
        cache_file.parent.mkdir(parents=True, exist_ok=True)
        with open(cache_file, "w") as f:
            json.dump(list(self._processed_ids), f)

    def _get_sample_id(self, text: str) -> str:
        return hashlib.sha256(text.encode()).hexdigest()[:16]

    def _load_fineweb(self) -> Iterator[Dict]:
        dataset = load_dataset(
            self.config.hf_dataset_name,
            split=self.config.hf_dataset_split,
            streaming=True,
        )
        for sample in dataset:
            text = sample.get("text", "")
            if text and len(text.strip()) > 0:
                yield {
                    "id": sample.get("id", ""),
                    "text": text,
                }

    def _process_document(self, text: str) -> List[Dict]:
        doc = self.nlp(text)
        records = []

        for sent in doc.sents:
            sent_text = sent.text.strip()
            if len(sent_text) < self.config.min_sentence_len:
                continue
            if len(sent_text) > self.config.max_sentence_len:
                sent_text = sent_text[: self.config.max_sentence_len]

            tokens = []
            pos_tags = []
            dep_tags = []
            lemmas = []
            ent_types = []
            head_dists = []

            for token in sent:
                tokens.append(token.text)
                pos_tags.append(token.pos_)
                dep_tags.append(token.dep_)
                lemmas.append(token.lemma_ if token.lemma_ else token.text)
                ent_types.append(token.ent_type_ if token.ent_type_ else "O")
                head_dists.append(token.head.i - token.i)

            enc = self.tokenizer(
                sent_text,
                add_special_tokens=False,
                truncation=True,
                max_length=self.config.max_sentence_len,
            )
            token_ids = enc["input_ids"]

            record = {
                "id": self._get_sample_id(sent_text),
                "text": sent_text,
                "tokens": json.dumps(tokens),
                "token_ids": json.dumps(token_ids),
                "pos": json.dumps(pos_tags),
                "dep": json.dumps(dep_tags),
                "lemma": json.dumps(lemmas),
                "ent_type": json.dumps(ent_types),
                "head_dist": json.dumps(head_dists),
            }
            records.append(record)

        return records

    def generate(self) -> Dict[str, Path]:
        self.config.output_dir.mkdir(parents=True, exist_ok=True)
        self.config.cache_dir.mkdir(parents=True, exist_ok=True)
        self._processed_ids = self._load_processed_ids()

        jsonl_path = self.config.output_dir / "pre_tokenized.jsonl.gz"
        parquet_path = self.config.output_dir / "intermediate.parquet"

        jsonl_records: List[Dict] = []
        all_records: List[Dict] = []

        try:
            import pyarrow as pa
            import pyarrow.parquet as pq

            has_pyarrow = True
        except ImportError:
            has_pyarrow = False
            print("Warning: pyarrow not installed. Parquet output will be skipped.")
            print("Install with: pip install pyarrow")

        batch_buffer: List[str] = []
        sample_count = 0
        skipped_count = 0

        print(f"Loading FineWeb from: {self.config.hf_dataset_name}")
        print(f"Target samples: {self.config.max_samples}")

        dataset = self._load_fineweb()

        for sample in tqdm(dataset, desc="Processing documents"):
            if sample_count >= self.config.max_samples:
                break

            sample_text = sample["text"]
            if not sample_text:
                continue

            batch_buffer.append(sample_text)

            if len(batch_buffer) >= self.config.batch_size:
                texts = batch_buffer
                batch_buffer = []

                docs = list(self.nlp.pipe(texts, batch_size=len(texts)))

                for doc in docs:
                    for sent in doc.sents:
                        sent_text = sent.text.strip()
                        if len(sent_text) < self.config.min_sentence_len:
                            continue
                        if len(sent_text) > self.config.max_sentence_len:
                            sent_text = sent_text[: self.config.max_sentence_len]

                        sample_id = self._get_sample_id(sent_text)
                        if sample_id in self._processed_ids:
                            skipped_count += 1
                            continue

                        self._processed_ids.add(sample_id)
                        sample_count += 1

                        tokens = []
                        pos_tags = []
                        dep_tags = []
                        lemmas = []
                        ent_types = []
                        head_dists = []

                        for token in sent:
                            tokens.append(token.text)
                            pos_tags.append(token.pos_)
                            dep_tags.append(token.dep_)
                            lemmas.append(token.lemma_ if token.lemma_ else token.text)
                            ent_types.append(
                                token.ent_type_ if token.ent_type_ else "O"
                            )
                            head_dists.append(token.head.i - token.i)

                        enc = self.tokenizer(
                            sent_text,
                            add_special_tokens=False,
                            truncation=True,
                            max_length=self.config.max_sentence_len,
                        )
                        token_ids = enc["input_ids"]

                        record = {
                            "id": sample_id,
                            "text": sent_text,
                            "tokens": json.dumps(tokens),
                            "token_ids": json.dumps(token_ids),
                            "pos": json.dumps(pos_tags),
                            "dep": json.dumps(dep_tags),
                            "lemma": json.dumps(lemmas),
                            "ent_type": json.dumps(ent_types),
                            "head_dist": json.dumps(head_dists),
                        }

                        jsonl_records.append(record)
                        all_records.append(record)

                        if sample_count >= self.config.max_samples:
                            break
                    if sample_count >= self.config.max_samples:
                        break

            if sample_count % 1000 == 0 and jsonl_records:
                self._write_jsonl(jsonl_records, jsonl_path, append=True)
                jsonl_records = []
                self._save_processed_ids()

        if jsonl_records:
            self._write_jsonl(jsonl_records, jsonl_path, append=True)

        if has_pyarrow and all_records:
            self._write_parquet(all_records, parquet_path)

        self._save_processed_ids()

        print(f"\n=== Generation Complete ===")
        print(f"Total samples: {sample_count}")
        print(f"Skipped (duplicates): {skipped_count}")
        print(f"Output files:")
        print(f"  - {jsonl_path}")
        if has_pyarrow:
            print(f"  - {parquet_path}")

        return {
            "jsonl": jsonl_path,
            "parquet": parquet_path if has_pyarrow else None,
        }

    def _write_jsonl(self, records: List[Dict], path: Path, append: bool = False):
        mode = "ab" if append else "wb"
        with gzip.open(path, mode) as f:
            for record in records:
                f.write((json.dumps(record) + "\n").encode())

    def _write_parquet(self, records: List[Dict], path: Path):
        try:
            import pyarrow as pa
            import pyarrow.parquet as pq

            if not records:
                return

            keys = list(records[0].keys())
            arrays = []
            for key in keys:
                arrays.append(
                    pa.array([r.get(key, "") for r in records], type=pa.string())
                )

            schema = pa.schema(zip(keys, [pa.string() for _ in keys]))
            table = pa.table(dict(zip(keys, arrays)), schema=schema)
            pq.write_table(table, path)
        except ImportError:
            print("Skipping parquet output (pyarrow not available)")


def main():
    import argparse

    parser = argparse.ArgumentParser(description="Generate UKS Seed Dataset")
    parser.add_argument(
        "--max-samples", type=int, default=10000, help="Maximum number of samples"
    )
    parser.add_argument(
        "--batch-size", type=int, default=100, help="Batch size for processing"
    )
    parser.add_argument("--output-dir", type=str, default=None, help="Output directory")
    parser.add_argument("--cache-dir", type=str, default=None, help="Cache directory")
    args = parser.parse_args()

    config = SEEDConfig(
        max_samples=args.max_samples,
        batch_size=args.batch_size,
    )
    if args.output_dir:
        config.output_dir = Path(args.output_dir)
    if args.cache_dir:
        config.cache_dir = Path(args.cache_dir)

    generator = SEEDDatasetGenerator(config)
    generator.generate()


if __name__ == "__main__":
    main()