""" Universal Multilingual Text Cleaner and Hybrid Tokenizer. Supports English, Hindi (Devanagari Unicode), Hinglish, numbers, and punctuation. Uses 1-token-per-character for Devanagari & ASCII + UTF-8 byte fallback for 0% OOV. """ import re import unicodedata import torch from typing import List class TextTokenizer: """ Hybrid Unicode Character + UTF-8 Byte Fallback Tokenizer (vocab_size = 512). Layout: - 0: - 1: - 2..129: Devanagari Unicode block U+0900..U+097F (128 chars, 1 token per char!) - 130..224: Printable ASCII U+0020..U+007E (95 chars, 1 token per char!) - 225..480: UTF-8 byte fallback (256 bytes) for any other Unicode characters """ PAD_ID = 0 UNK_ID = 1 DEV_START = 2 ASCII_START = 130 BYTE_START = 225 VOCAB_SIZE = 512 def __init__(self, pad_id: int = 0): self.pad_id = pad_id self.vocab_size = self.VOCAB_SIZE def clean_text(self, text: str) -> str: if not isinstance(text, str): return "" # Unicode normalization (NFC) text = unicodedata.normalize("NFC", text) # Normalize common smart punctuation text = ( text.replace("“", '"') .replace("”", '"') .replace("‘", "'") .replace("’", "'") .replace("—", "-") .replace("–", "-") ) # Collapse multiple spaces and newlines text = re.sub(r"\s+", " ", text).strip() return text @staticmethod def normalize_hindi_pronunciation(text: str) -> str: """ Resolves word-medial Hindi anusvara (ं) before stop consonants into explicit half-nasal consonants (न्/म्/ण्/ञ्) so raw-character models pronounce words like 'ईंधन' ('ईन्धन'), 'कंबल' ('कम्बल'), 'ठंड' ('ठण्ड') accurately. Leaves word-final nasalization ('मैं', 'हूं', 'गांव', 'बच्चों') untouched. """ if not text: return text text = re.sub(r"ं(?=[तथदधन])", "न्", text) text = re.sub(r"ं(?=[पफबभम])", "म्", text) text = re.sub(r"ं(?=[टठडढण])", "ण्", text) text = re.sub(r"ं(?=[चछजझञ])", "ञ्", text) return text def text_to_ids(self, text: str) -> torch.Tensor: """Encodes text to a 1D tensor of token IDs in range [2, 480].""" text = self.clean_text(text) ids: List[int] = [] for ch in text: cp = ord(ch) if 0x0900 <= cp <= 0x097F: ids.append(self.DEV_START + (cp - 0x0900)) elif 0x0020 <= cp <= 0x007E: ids.append(self.ASCII_START + (cp - 0x0020)) else: for b in ch.encode("utf-8"): ids.append(self.BYTE_START + b) return torch.tensor(ids, dtype=torch.long) def ids_to_text(self, ids: List[int]) -> str: """Decodes token IDs back to a readable string.""" out: List[str] = [] byte_buf = bytearray() def flush_bytes(): if byte_buf: out.append(byte_buf.decode("utf-8", errors="replace")) byte_buf.clear() for idx in ids: if idx <= 1: continue elif self.DEV_START <= idx < self.DEV_START + 128: flush_bytes() out.append(chr(0x0900 + (idx - self.DEV_START))) elif self.ASCII_START <= idx < self.ASCII_START + 95: flush_bytes() out.append(chr(0x0020 + (idx - self.ASCII_START))) elif self.BYTE_START <= idx < self.BYTE_START + 256: byte_buf.append(idx - self.BYTE_START) flush_bytes() return "".join(out)