File size: 3,900 Bytes
5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 7ce9666 5be0f71 b62c0da 5be0f71 b62c0da 5be0f71 b62c0da | 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 | """
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: <pad>
- 1: <unk>
- 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)
|