import re import json import torch from torch.utils.data import Dataset from torch.nn.utils.rnn import pad_sequence from collections import Counter class TokiPonaTokenizer: def __init__(self): # Special Tokens self.pad_token = "" self.unk_token = "" self.bos_token = "" self.eos_token = "" self.special_tokens = [self.pad_token, self.unk_token, self.bos_token, self.eos_token] # Mappings: word -> ID and ID -> word self.word2idx = {} self.idx2word = {} def tokenize(self, text): """Uniform tokenization logic for both vocab building and encoding.""" # Clean out wiki markup symbols like * or = that are not real tokens cleaned = re.sub(r'[*=+#`~]', ' ', text) # Extract word tokens and individual punctuation marks return re.findall(r"\w+|[^\w\s]", cleaned.lower()) def build_vocab(self, texts, min_freq=20): """Extracts unique words from texts, applying a minimum frequency filter to clean noise.""" self.word2idx = {token: idx for idx, token in enumerate(self.special_tokens)} word_counts = Counter() for text in texts: tokens = self.tokenize(text) word_counts.update(tokens) current_id = len(self.special_tokens) for word, count in sorted(word_counts.items()): if count >= min_freq and word not in self.word2idx: # Filter out pure numbers / excessive length noise if not word.isdigit() and len(word) < 30: self.word2idx[word] = current_id current_id += 1 # Rebuild reverse index mapping self.idx2word = {idx: word for word, idx in self.word2idx.items()} def save_vocab(self, filepath='vocab.json'): """Saves the word2idx mapping to a JSON file for inference persistence.""" with open(filepath, 'w', encoding='utf-8') as f: json.dump(self.word2idx, f, ensure_ascii=False, indent=2) print(f"Vocabulary saved successfully to '{filepath}'.") def load_vocab(self, filepath='vocab.json'): """Loads vocabulary mapping from a JSON file.""" with open(filepath, 'r', encoding='utf-8') as f: self.word2idx = json.load(f) self.idx2word = {v: k for k, v in self.word2idx.items()} print(f"Vocabulary successfully loaded from '{filepath}' (Size: {len(self.word2idx)}).") def encode(self, text, add_special_tokens=True): """Converts raw text into a list of integer IDs using the unified tokenizer.""" words = self.tokenize(text) ids = [self.word2idx.get(w, self.word2idx[self.unk_token]) for w in words] if add_special_tokens: ids = [self.word2idx[self.bos_token]] + ids + [self.word2idx[self.eos_token]] return ids def decode(self, ids, skip_special_tokens=True): """Converts a list of integer IDs back into text.""" words = [] for idx in ids: word = self.idx2word.get(idx, self.unk_token) if skip_special_tokens and word in self.special_tokens: continue words.append(word) return " ".join(words) class TokiPonaDataset(Dataset): """PyTorch Dataset wrapper for Toki Pona text samples with sentence-level splitting.""" def __init__(self, texts, tokenizer, max_len=32): self.tokenizer = tokenizer self.max_len = max_len self.samples = [] for text in texts: # Split full wiki articles into individual sentences/lines sentences = re.split(r'[\n.!?]+', text) for sentence in sentences: sentence = sentence.strip() if not sentence: continue encoded = self.tokenizer.encode(sentence) if len(encoded) > self.max_len: encoded = encoded[:self.max_len] if len(encoded) > 2: # Must have BOS + at least 1 word + EOS self.samples.append(torch.tensor(encoded, dtype=torch.long)) def __len__(self): return len(self.samples) def __getitem__(self, idx): return self.samples[idx] def pad_collate_fn(batch, pad_idx=0): """Custom collate function to pad variable-length sequences in a batch.""" return pad_sequence(batch, batch_first=True, padding_value=pad_idx)