VIZINTZOR commited on
Commit
3404377
·
1 Parent(s): 22e7825

Update tokenizer.py

Browse files
Files changed (1) hide show
  1. tokenizer.py +79 -160
tokenizer.py CHANGED
@@ -1,161 +1,80 @@
1
  import re
2
- import torch
3
-
4
- CODEC_CODEBOOK_SIZE = 12800
5
-
6
- TH_CHARS = 'กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรลวศษสหฬอฮฤฦะัาำิีึืุูเแโใไๅํ็่้๊๋ฯฺๆ์ํ๎๏๚๛๐๑๒๓๔๕๖๗๘๙฿'
7
- EN_LOWER = "abcdefghijklmnopqrstuvwxyz"
8
- EN_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
9
- DIGITS = "0123456789"
10
- PUNCT = '.,!?;:-–—…"\'()[]{}«»„"" '
11
- EXTRA = "\n\t"
12
-
13
- _ALL_CHARS: list[str] = []
14
- _seen: set[str] = set()
15
- for _src in [TH_CHARS, EN_LOWER, EN_UPPER, DIGITS, PUNCT, EXTRA]:
16
- for _ch in _src:
17
- if _ch not in _seen:
18
- _ALL_CHARS.append(_ch)
19
- _seen.add(_ch)
20
-
21
- SPECIAL_TOKENS = {
22
- "<pad>": 0,
23
- "<start_of_text>": 1,
24
- "<end_of_text>": 2,
25
- "<start_of_speech>": 3,
26
- "<end_of_speech>": 4,
27
- "<spk_0>": 5, # kept for compatibility, but speaker embedding is primary
28
- "<spk_1>": 6,
29
- "<spk_2>": 7,
30
- "<spk_3>": 8,
31
- }
32
- NUM_SPECIAL_TOKENS = len(SPECIAL_TOKENS) # 9
33
-
34
- # ── Vocab offsets ───────────────────────────────────────────────
35
- TEXT_CHARS = _ALL_CHARS
36
- TEXT_VOCAB_SIZE = len(TEXT_CHARS) # ~146
37
- TEXT_OFFSET = NUM_SPECIAL_TOKENS # 9
38
- AUDIO_OFFSET = TEXT_OFFSET + TEXT_VOCAB_SIZE # 155
39
- NUM_AUDIO_TOKENS = CODEC_CODEBOOK_SIZE # 12,800
40
- TOTAL_VOCAB_SIZE = AUDIO_OFFSET + NUM_AUDIO_TOKENS # 12,955
41
-
42
- # Encoder needs only text vocab; decoder needs full vocab
43
- ENCODER_VOCAB_SIZE = AUDIO_OFFSET # 155 (special + text)
44
- DECODER_VOCAB_SIZE = TOTAL_VOCAB_SIZE # 12,955 (full)
45
-
46
- # ── Convenience IDs ─────────────────────────────────────────────
47
- PAD_TOKEN_ID = SPECIAL_TOKENS["<pad>"]
48
- START_OF_TEXT_TOKEN_ID = SPECIAL_TOKENS["<start_of_text>"]
49
- END_OF_TEXT_TOKEN_ID = SPECIAL_TOKENS["<end_of_text>"]
50
- START_OF_SPEECH_TOKEN_ID = SPECIAL_TOKENS["<start_of_speech>"]
51
- END_OF_SPEECH_TOKEN_ID = SPECIAL_TOKENS["<end_of_speech>"]
52
- SPK_0_TOKEN_ID = SPECIAL_TOKENS["<spk_0>"]
53
- SPK_1_TOKEN_ID = SPECIAL_TOKENS["<spk_1>"]
54
-
55
- # ── Helper functions ────────────────────────────────────────────
56
- def audio_token_id(code: int) -> int:
57
- """MioCodec code → global token ID."""
58
- return AUDIO_OFFSET + code
59
-
60
- def decode_audio_token(token_id: int) -> int:
61
- """Global token ID → MioCodec code."""
62
- return token_id - AUDIO_OFFSET
63
-
64
- def is_audio_token(token_id: int) -> bool:
65
- return AUDIO_OFFSET <= token_id < AUDIO_OFFSET + NUM_AUDIO_TOKENS
66
-
67
- def is_special_token(token_id: int) -> bool:
68
- return 0 <= token_id < NUM_SPECIAL_TOKENS
69
-
70
- def is_text_token(token_id: int) -> bool:
71
- return TEXT_OFFSET <= token_id < AUDIO_OFFSET
72
-
73
- class TTSTokenizer:
74
- def __init__(self):
75
- self.char2id: dict[str, int] = {}
76
- self.id2char: dict[int, str] = {}
77
- for i, ch in enumerate(TEXT_CHARS):
78
- tid = TEXT_OFFSET + i
79
- self.char2id[ch] = tid
80
- self.id2char[tid] = ch
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]))