Spaces:
Running
Running
Update tokenizer.py
Browse files- tokenizer.py +79 -160
tokenizer.py
CHANGED
|
@@ -1,161 +1,80 @@
|
|
| 1 |
import re
|
| 2 |
-
import
|
| 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 |
-
self._special_id_to_name = {v: k for k, v in SPECIAL_TOKENS.items()}
|
| 83 |
-
self.vocab_size = TOTAL_VOCAB_SIZE
|
| 84 |
-
self.text_vocab_size = len(TEXT_CHARS)
|
| 85 |
-
|
| 86 |
-
def normalize_text(self, text: str) -> str:
|
| 87 |
-
text = re.sub(r'\s+', ' ', text).strip()
|
| 88 |
-
text = re.sub(r'[–—]', '-', text)
|
| 89 |
-
text = re.sub(r'[«»„""]', '"', text)
|
| 90 |
-
return text
|
| 91 |
-
|
| 92 |
-
def encode_text(self, text: str) -> list[int]:
|
| 93 |
-
text = self.normalize_text(text)
|
| 94 |
-
return [self.char2id[ch] for ch in text if ch in self.char2id]
|
| 95 |
-
|
| 96 |
-
def decode_text(self, ids: list[int]) -> str:
|
| 97 |
-
return "".join(self.id2char.get(t, "") for t in ids if is_text_token(t))
|
| 98 |
-
|
| 99 |
-
# ── Encoder-Decoder methods ──────────────────────────────
|
| 100 |
-
|
| 101 |
-
def build_encoder_input(self, text: str) -> torch.Tensor:
|
| 102 |
-
"""
|
| 103 |
-
Encoder input: <sot> text_chars <eot>
|
| 104 |
-
No speaker token — speaker info comes from embedding.
|
| 105 |
-
"""
|
| 106 |
-
text_ids = self.encode_text(text)
|
| 107 |
-
seq = text_ids
|
| 108 |
-
return torch.tensor(seq, dtype=torch.long)
|
| 109 |
-
|
| 110 |
-
def build_decoder_input(self, audio_codes: torch.Tensor) -> torch.Tensor:
|
| 111 |
-
"""
|
| 112 |
-
Decoder input: <sos> [audio_codes + AUDIO_OFFSET] <eos>
|
| 113 |
-
audio_codes: raw MioCodec codes in [0, 12799]
|
| 114 |
-
"""
|
| 115 |
-
seq = (
|
| 116 |
-
[START_OF_SPEECH_TOKEN_ID]
|
| 117 |
-
+ (audio_codes + AUDIO_OFFSET).tolist()
|
| 118 |
-
+ [END_OF_SPEECH_TOKEN_ID]
|
| 119 |
-
)
|
| 120 |
-
return torch.tensor(seq, dtype=torch.long)
|
| 121 |
-
|
| 122 |
-
def build_decoder_prefix(self) -> torch.Tensor:
|
| 123 |
-
"""For inference: just <sos> to start generation."""
|
| 124 |
-
return torch.tensor([START_OF_SPEECH_TOKEN_ID], dtype=torch.long)
|
| 125 |
-
|
| 126 |
-
def extract_audio_codes(self, sequence: torch.Tensor):
|
| 127 |
-
"""Extract raw MioCodec codes from a token sequence."""
|
| 128 |
-
mask = torch.tensor([is_audio_token(t.item()) for t in sequence])
|
| 129 |
-
if not mask.any():
|
| 130 |
-
return None
|
| 131 |
-
return sequence[mask] - AUDIO_OFFSET
|
| 132 |
-
|
| 133 |
-
def describe(self, seq: torch.Tensor, max_tok: int = 30) -> str:
|
| 134 |
-
parts = []
|
| 135 |
-
for t in seq[:max_tok]:
|
| 136 |
-
tid = t.item()
|
| 137 |
-
if is_special_token(tid):
|
| 138 |
-
parts.append(self._special_id_to_name.get(tid, f"<sp_{tid}>"))
|
| 139 |
-
elif is_text_token(tid):
|
| 140 |
-
ch = self.id2char.get(tid, "?")
|
| 141 |
-
parts.append(ch if ch != " " else "·")
|
| 142 |
-
elif is_audio_token(tid):
|
| 143 |
-
code = tid - AUDIO_OFFSET
|
| 144 |
-
parts.append(f"♪{code}")
|
| 145 |
-
else:
|
| 146 |
-
parts.append(f"?{tid}")
|
| 147 |
-
r = " ".join(parts)
|
| 148 |
-
if len(seq) > max_tok:
|
| 149 |
-
r += f" ... [{len(seq) - max_tok} more]"
|
| 150 |
-
return r
|
| 151 |
-
|
| 152 |
-
if __name__ == "__main__":
|
| 153 |
-
tokens = TTSTokenizer()
|
| 154 |
-
text = """สวัสดีค่ะ วันนี้อยากเล่าเรื่องหนึ่งที่เราไม่เคยคิดว่าจะเปลี่ยนชีวิตเราได้ขนาดนี้ มันเป็นวันที่ธรรมดา"""
|
| 155 |
-
print(f"Text Len: {len(text)}")
|
| 156 |
-
encode = tokens.encode_text(text)
|
| 157 |
-
build_encode = tokens.build_encoder_input(text)
|
| 158 |
-
print(build_encode)
|
| 159 |
-
print(encode)
|
| 160 |
-
print(f"Encode Len: {len(encode)}")
|
| 161 |
-
print(f"Build Encode Len: {len(build_encode)}")
|
|
|
|
| 1 |
import re
|
| 2 |
+
from typing import List
|
| 3 |
+
from vachana_g2p import th2ipa
|
| 4 |
+
from pythainlp.tokenize import word_tokenize
|
| 5 |
+
from pythainlp.util import normalize as pythai_normalize
|
| 6 |
+
|
| 7 |
+
PAD = "_"
|
| 8 |
+
BOS = "^"
|
| 9 |
+
EOS = "$"
|
| 10 |
+
SPACE = " "
|
| 11 |
+
UNK = "?"
|
| 12 |
+
|
| 13 |
+
_ARABIC_DIGITS = list("0123456789")
|
| 14 |
+
_PUNCT = list(" .,!?;:()\"'-…")
|
| 15 |
+
_IPA_THAI = ['a', 'b', 'd', 'e', 'f', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'w', 'ŋ', 'ɔ', 'ɕ', 'ə', 'ɛ', 'ɯ', 'ʔ', 'ʰ', 'ː']
|
| 16 |
+
_IPA_TONE = list('̀'+'́'+'̂'+'̌')
|
| 17 |
+
|
| 18 |
+
SYMBOLS = (
|
| 19 |
+
[PAD, BOS, EOS, UNK]
|
| 20 |
+
+ _IPA_THAI
|
| 21 |
+
+ _IPA_TONE
|
| 22 |
+
+ _ARABIC_DIGITS
|
| 23 |
+
+ _PUNCT
|
| 24 |
+
+ ["|"]
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
SYMBOLS = list(dict.fromkeys(SYMBOLS))
|
| 28 |
+
|
| 29 |
+
_SYM2ID = {s: i for i, s in enumerate(SYMBOLS)}
|
| 30 |
+
_ID2SYM = {i: s for i, s in enumerate(SYMBOLS)}
|
| 31 |
+
|
| 32 |
+
VOCAB_SIZE = len(SYMBOLS)
|
| 33 |
+
|
| 34 |
+
def chunk_text(text, max_char=1000):
|
| 35 |
+
words = word_tokenize(text)
|
| 36 |
+
|
| 37 |
+
chunks = []
|
| 38 |
+
current = ""
|
| 39 |
+
|
| 40 |
+
for word in words:
|
| 41 |
+
if len(current) + len(word) <= max_char:
|
| 42 |
+
current += word
|
| 43 |
+
else:
|
| 44 |
+
chunks.append(current)
|
| 45 |
+
current = word
|
| 46 |
+
|
| 47 |
+
if current:
|
| 48 |
+
chunks.append(current)
|
| 49 |
+
|
| 50 |
+
return chunks
|
| 51 |
+
|
| 52 |
+
def _normalize_text(text: str) -> str:
|
| 53 |
+
text = text.strip()
|
| 54 |
+
text = pythai_normalize(text)
|
| 55 |
+
text = re.sub(r"\s+", " ", text)
|
| 56 |
+
return text
|
| 57 |
+
|
| 58 |
+
def text_to_words(text: str) -> List[str]:
|
| 59 |
+
text = _normalize_text(text)
|
| 60 |
+
text = th2ipa(text) + "."
|
| 61 |
+
return [text]
|
| 62 |
+
|
| 63 |
+
def tokenize(text: str, add_bos_eos: bool = True) -> List[int]:
|
| 64 |
+
"""Text -> list of symbol ids, with '|' inserted at word boundaries."""
|
| 65 |
+
words = text_to_words(text)
|
| 66 |
+
ids: List[int] = []
|
| 67 |
+
if add_bos_eos:
|
| 68 |
+
ids.append(_SYM2ID[BOS])
|
| 69 |
+
for wi, w in enumerate(words):
|
| 70 |
+
for ch in w:
|
| 71 |
+
ids.append(_SYM2ID.get(ch, _SYM2ID[UNK]))
|
| 72 |
+
if wi != len(words) - 1:
|
| 73 |
+
ids.append(_SYM2ID["|"])
|
| 74 |
+
if add_bos_eos:
|
| 75 |
+
ids.append(_SYM2ID[EOS])
|
| 76 |
+
return ids
|
| 77 |
+
|
| 78 |
+
def ids_to_text(ids: List[int]) -> str:
|
| 79 |
+
return "".join(_ID2SYM.get(i, UNK) for i in ids if i not in
|
| 80 |
+
(_SYM2ID[PAD], _SYM2ID[BOS], _SYM2ID[EOS]))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|