forked from espnet/espnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
whisper_export_vocabulary.py
96 lines (78 loc) · 2.78 KB
/
whisper_export_vocabulary.py
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
#!/usr/bin/env python3
import argparse
import logging
import sys
from pathlib import Path
from typeguard import check_argument_types
from espnet.utils.cli_utils import get_commandline_args
def export_vocabulary(output: str, whisper_model: str, log_level: str):
try:
import whisper.tokenizer
except Exception as e:
print("Error: whisper is not properly installed.")
print(
"Please install whisper with: cd ${MAIN_ROOT}/tools && "
"./installers/install_whisper.sh"
)
raise e
assert check_argument_types()
logging.basicConfig(
level=log_level,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
if output == "-":
fout = sys.stdout
else:
p = Path(output)
p.parent.mkdir(parents=True, exist_ok=True)
fout = p.open("w", encoding="utf-8")
if whisper_model == "whisper_en":
tokenizer = whisper.tokenizer.get_tokenizer(multilingual=False)
# TODO(Shih-Lun): should support feeding in
# different languages (default is en)
elif whisper_model == "whisper_multilingual":
tokenizer = whisper.tokenizer.get_tokenizer(multilingual=True, language=None)
else:
raise ValueError("tokenizer unsupported:", whisper_model)
vocab_size = tokenizer.tokenizer.vocab_size + len(
tokenizer.tokenizer.get_added_vocab()
)
for i in range(vocab_size):
# take care of special char for <space>
tkn = tokenizer.tokenizer.convert_ids_to_tokens(i).replace("Ġ", " ")
fout.write(tkn + "\n")
# NOTE (Shih-Lun): extra tokens (for timestamped ASR) not
# stored in the wrapped tokenizer
full_vocab_size = 51865 if whisper_model == "whisper_multilingual" else 51864
for i in range(full_vocab_size - vocab_size):
fout.write("()" + "\n")
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Export Whisper vocabulary",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--log_level",
type=lambda x: x.upper(),
default="INFO",
choices=("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG", "NOTSET"),
help="The verbose level of logging",
)
parser.add_argument(
"--output", "-o", required=True, help="Output text. - indicates sys.stdout"
)
parser.add_argument(
"--whisper_model",
type=str,
required=True,
help="Whisper model type",
)
return parser
def main(cmd=None):
print(get_commandline_args(), file=sys.stderr)
parser = get_parser()
args = parser.parse_args(cmd)
kwargs = vars(args)
export_vocabulary(**kwargs)
if __name__ == "__main__":
main()