|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang |
| 3 | +# Wei Kang) |
| 4 | +# |
| 5 | +# See ../../../../LICENSE for clarification regarding multiple authors |
| 6 | +# |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +# you may not use this file except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, software |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +# See the License for the specific language governing permissions and |
| 17 | +# limitations under the License. |
| 18 | + |
| 19 | + |
| 20 | +""" |
| 21 | +
|
| 22 | +This script takes as input `lang_dir`, which should contain:: |
| 23 | +
|
| 24 | + - lang_dir/bbpe.model, |
| 25 | + - lang_dir/words.txt |
| 26 | +
|
| 27 | +and generates the following files in the directory `lang_dir`: |
| 28 | +
|
| 29 | + - lexicon.txt |
| 30 | + - lexicon_disambig.txt |
| 31 | + - L.pt |
| 32 | + - L_disambig.pt |
| 33 | + - tokens.txt |
| 34 | +""" |
| 35 | + |
| 36 | +import argparse |
| 37 | +from pathlib import Path |
| 38 | +from typing import Dict, List, Tuple |
| 39 | + |
| 40 | +import k2 |
| 41 | +import sentencepiece as spm |
| 42 | +import torch |
| 43 | +from prepare_lang import ( |
| 44 | + Lexicon, |
| 45 | + add_disambig_symbols, |
| 46 | + add_self_loops, |
| 47 | + write_lexicon, |
| 48 | + write_mapping, |
| 49 | +) |
| 50 | + |
| 51 | +from icefall.byte_utils import byte_encode |
| 52 | +from icefall.utils import str2bool, tokenize_by_CJK_char |
| 53 | + |
| 54 | + |
| 55 | +def lexicon_to_fst_no_sil( |
| 56 | + lexicon: Lexicon, |
| 57 | + token2id: Dict[str, int], |
| 58 | + word2id: Dict[str, int], |
| 59 | + need_self_loops: bool = False, |
| 60 | +) -> k2.Fsa: |
| 61 | + """Convert a lexicon to an FST (in k2 format). |
| 62 | +
|
| 63 | + Args: |
| 64 | + lexicon: |
| 65 | + The input lexicon. See also :func:`read_lexicon` |
| 66 | + token2id: |
| 67 | + A dict mapping tokens to IDs. |
| 68 | + word2id: |
| 69 | + A dict mapping words to IDs. |
| 70 | + need_self_loops: |
| 71 | + If True, add self-loop to states with non-epsilon output symbols |
| 72 | + on at least one arc out of the state. The input label for this |
| 73 | + self loop is `token2id["#0"]` and the output label is `word2id["#0"]`. |
| 74 | + Returns: |
| 75 | + Return an instance of `k2.Fsa` representing the given lexicon. |
| 76 | + """ |
| 77 | + loop_state = 0 # words enter and leave from here |
| 78 | + next_state = 1 # the next un-allocated state, will be incremented as we go |
| 79 | + |
| 80 | + arcs = [] |
| 81 | + |
| 82 | + # The blank symbol <blk> is defined in local/train_bpe_model.py |
| 83 | + assert token2id["<blk>"] == 0 |
| 84 | + assert word2id["<eps>"] == 0 |
| 85 | + |
| 86 | + eps = 0 |
| 87 | + |
| 88 | + for word, pieces in lexicon: |
| 89 | + assert len(pieces) > 0, f"{word} has no pronunciations" |
| 90 | + cur_state = loop_state |
| 91 | + |
| 92 | + word = word2id[word] |
| 93 | + pieces = [token2id[i] for i in pieces] |
| 94 | + |
| 95 | + for i in range(len(pieces) - 1): |
| 96 | + w = word if i == 0 else eps |
| 97 | + arcs.append([cur_state, next_state, pieces[i], w, 0]) |
| 98 | + |
| 99 | + cur_state = next_state |
| 100 | + next_state += 1 |
| 101 | + |
| 102 | + # now for the last piece of this word |
| 103 | + i = len(pieces) - 1 |
| 104 | + w = word if i == 0 else eps |
| 105 | + arcs.append([cur_state, loop_state, pieces[i], w, 0]) |
| 106 | + |
| 107 | + if need_self_loops: |
| 108 | + disambig_token = token2id["#0"] |
| 109 | + disambig_word = word2id["#0"] |
| 110 | + arcs = add_self_loops( |
| 111 | + arcs, |
| 112 | + disambig_token=disambig_token, |
| 113 | + disambig_word=disambig_word, |
| 114 | + ) |
| 115 | + |
| 116 | + final_state = next_state |
| 117 | + arcs.append([loop_state, final_state, -1, -1, 0]) |
| 118 | + arcs.append([final_state]) |
| 119 | + |
| 120 | + arcs = sorted(arcs, key=lambda arc: arc[0]) |
| 121 | + arcs = [[str(i) for i in arc] for arc in arcs] |
| 122 | + arcs = [" ".join(arc) for arc in arcs] |
| 123 | + arcs = "\n".join(arcs) |
| 124 | + |
| 125 | + fsa = k2.Fsa.from_str(arcs, acceptor=False) |
| 126 | + return fsa |
| 127 | + |
| 128 | + |
| 129 | +def generate_lexicon( |
| 130 | + model_file: str, words: List[str], oov: str |
| 131 | +) -> Tuple[Lexicon, Dict[str, int]]: |
| 132 | + """Generate a lexicon from a BPE model. |
| 133 | +
|
| 134 | + Args: |
| 135 | + model_file: |
| 136 | + Path to a sentencepiece model. |
| 137 | + words: |
| 138 | + A list of strings representing words. |
| 139 | + oov: |
| 140 | + The out of vocabulary word in lexicon. |
| 141 | + Returns: |
| 142 | + Return a tuple with two elements: |
| 143 | + - A dict whose keys are words and values are the corresponding |
| 144 | + word pieces. |
| 145 | + - A dict representing the token symbol, mapping from tokens to IDs. |
| 146 | + """ |
| 147 | + sp = spm.SentencePieceProcessor() |
| 148 | + sp.load(str(model_file)) |
| 149 | + |
| 150 | + # Convert word to word piece IDs instead of word piece strings |
| 151 | + # to avoid OOV tokens. |
| 152 | + encode_words = [byte_encode(tokenize_by_CJK_char(w)) for w in words] |
| 153 | + words_pieces_ids: List[List[int]] = sp.encode(encode_words, out_type=int) |
| 154 | + |
| 155 | + # Now convert word piece IDs back to word piece strings. |
| 156 | + words_pieces: List[List[str]] = [sp.id_to_piece(ids) for ids in words_pieces_ids] |
| 157 | + |
| 158 | + lexicon = [] |
| 159 | + for word, pieces in zip(words, words_pieces): |
| 160 | + lexicon.append((word, pieces)) |
| 161 | + |
| 162 | + lexicon.append((oov, ["▁", sp.id_to_piece(sp.unk_id())])) |
| 163 | + |
| 164 | + token2id: Dict[str, int] = {sp.id_to_piece(i): i for i in range(sp.vocab_size())} |
| 165 | + |
| 166 | + return lexicon, token2id |
| 167 | + |
| 168 | + |
| 169 | +def get_args(): |
| 170 | + parser = argparse.ArgumentParser() |
| 171 | + parser.add_argument( |
| 172 | + "--lang-dir", |
| 173 | + type=str, |
| 174 | + help="""Input and output directory. |
| 175 | + It should contain the bpe.model and words.txt |
| 176 | + """, |
| 177 | + ) |
| 178 | + |
| 179 | + parser.add_argument( |
| 180 | + "--oov", |
| 181 | + type=str, |
| 182 | + default="<UNK>", |
| 183 | + help="The out of vocabulary word in lexicon.", |
| 184 | + ) |
| 185 | + |
| 186 | + parser.add_argument( |
| 187 | + "--debug", |
| 188 | + type=str2bool, |
| 189 | + default=False, |
| 190 | + help="""True for debugging, which will generate |
| 191 | + a visualization of the lexicon FST. |
| 192 | +
|
| 193 | + Caution: If your lexicon contains hundreds of thousands |
| 194 | + of lines, please set it to False! |
| 195 | +
|
| 196 | + See "test/test_bpe_lexicon.py" for usage. |
| 197 | + """, |
| 198 | + ) |
| 199 | + |
| 200 | + return parser.parse_args() |
| 201 | + |
| 202 | + |
| 203 | +def main(): |
| 204 | + args = get_args() |
| 205 | + lang_dir = Path(args.lang_dir) |
| 206 | + model_file = lang_dir / "bbpe.model" |
| 207 | + |
| 208 | + word_sym_table = k2.SymbolTable.from_file(lang_dir / "words.txt") |
| 209 | + |
| 210 | + words = word_sym_table.symbols |
| 211 | + |
| 212 | + excluded = ["<eps>", "!SIL", "<SPOKEN_NOISE>", args.oov, "#0", "<s>", "</s>"] |
| 213 | + |
| 214 | + for w in excluded: |
| 215 | + if w in words: |
| 216 | + words.remove(w) |
| 217 | + |
| 218 | + lexicon, token_sym_table = generate_lexicon(model_file, words, args.oov) |
| 219 | + |
| 220 | + lexicon_disambig, max_disambig = add_disambig_symbols(lexicon) |
| 221 | + |
| 222 | + next_token_id = max(token_sym_table.values()) + 1 |
| 223 | + for i in range(max_disambig + 1): |
| 224 | + disambig = f"#{i}" |
| 225 | + assert disambig not in token_sym_table |
| 226 | + token_sym_table[disambig] = next_token_id |
| 227 | + next_token_id += 1 |
| 228 | + |
| 229 | + word_sym_table.add("#0") |
| 230 | + word_sym_table.add("<s>") |
| 231 | + word_sym_table.add("</s>") |
| 232 | + |
| 233 | + write_mapping(lang_dir / "tokens.txt", token_sym_table) |
| 234 | + |
| 235 | + write_lexicon(lang_dir / "lexicon.txt", lexicon) |
| 236 | + write_lexicon(lang_dir / "lexicon_disambig.txt", lexicon_disambig) |
| 237 | + |
| 238 | + L = lexicon_to_fst_no_sil( |
| 239 | + lexicon, |
| 240 | + token2id=token_sym_table, |
| 241 | + word2id=word_sym_table, |
| 242 | + ) |
| 243 | + |
| 244 | + L_disambig = lexicon_to_fst_no_sil( |
| 245 | + lexicon_disambig, |
| 246 | + token2id=token_sym_table, |
| 247 | + word2id=word_sym_table, |
| 248 | + need_self_loops=True, |
| 249 | + ) |
| 250 | + torch.save(L.as_dict(), lang_dir / "L.pt") |
| 251 | + torch.save(L_disambig.as_dict(), lang_dir / "L_disambig.pt") |
| 252 | + |
| 253 | + if args.debug: |
| 254 | + labels_sym = k2.SymbolTable.from_file(lang_dir / "tokens.txt") |
| 255 | + aux_labels_sym = k2.SymbolTable.from_file(lang_dir / "words.txt") |
| 256 | + |
| 257 | + L.labels_sym = labels_sym |
| 258 | + L.aux_labels_sym = aux_labels_sym |
| 259 | + L.draw(f"{lang_dir / 'L.svg'}", title="L.pt") |
| 260 | + |
| 261 | + L_disambig.labels_sym = labels_sym |
| 262 | + L_disambig.aux_labels_sym = aux_labels_sym |
| 263 | + L_disambig.draw(f"{lang_dir / 'L_disambig.svg'}", title="L_disambig.pt") |
| 264 | + |
| 265 | + |
| 266 | +if __name__ == "__main__": |
| 267 | + main() |
0 commit comments