Delete kokoro.py
Browse files
kokoro.py
DELETED
|
@@ -1,165 +0,0 @@
|
|
| 1 |
-
import phonemizer
|
| 2 |
-
import re
|
| 3 |
-
import torch
|
| 4 |
-
import numpy as np
|
| 5 |
-
|
| 6 |
-
def split_num(num):
|
| 7 |
-
num = num.group()
|
| 8 |
-
if '.' in num:
|
| 9 |
-
return num
|
| 10 |
-
elif ':' in num:
|
| 11 |
-
h, m = [int(n) for n in num.split(':')]
|
| 12 |
-
if m == 0:
|
| 13 |
-
return f"{h} o'clock"
|
| 14 |
-
elif m < 10:
|
| 15 |
-
return f'{h} oh {m}'
|
| 16 |
-
return f'{h} {m}'
|
| 17 |
-
year = int(num[:4])
|
| 18 |
-
if year < 1100 or year % 1000 < 10:
|
| 19 |
-
return num
|
| 20 |
-
left, right = num[:2], int(num[2:4])
|
| 21 |
-
s = 's' if num.endswith('s') else ''
|
| 22 |
-
if 100 <= year % 1000 <= 999:
|
| 23 |
-
if right == 0:
|
| 24 |
-
return f'{left} hundred{s}'
|
| 25 |
-
elif right < 10:
|
| 26 |
-
return f'{left} oh {right}{s}'
|
| 27 |
-
return f'{left} {right}{s}'
|
| 28 |
-
|
| 29 |
-
def flip_money(m):
|
| 30 |
-
m = m.group()
|
| 31 |
-
bill = 'dollar' if m[0] == '$' else 'pound'
|
| 32 |
-
if m[-1].isalpha():
|
| 33 |
-
return f'{m[1:]} {bill}s'
|
| 34 |
-
elif '.' not in m:
|
| 35 |
-
s = '' if m[1:] == '1' else 's'
|
| 36 |
-
return f'{m[1:]} {bill}{s}'
|
| 37 |
-
b, c = m[1:].split('.')
|
| 38 |
-
s = '' if b == '1' else 's'
|
| 39 |
-
c = int(c.ljust(2, '0'))
|
| 40 |
-
coins = f"cent{'' if c == 1 else 's'}" if m[0] == '$' else ('penny' if c == 1 else 'pence')
|
| 41 |
-
return f'{b} {bill}{s} and {c} {coins}'
|
| 42 |
-
|
| 43 |
-
def point_num(num):
|
| 44 |
-
a, b = num.group().split('.')
|
| 45 |
-
return ' point '.join([a, ' '.join(b)])
|
| 46 |
-
|
| 47 |
-
def normalize_text(text):
|
| 48 |
-
text = text.replace(chr(8216), "'").replace(chr(8217), "'")
|
| 49 |
-
text = text.replace('«', chr(8220)).replace('»', chr(8221))
|
| 50 |
-
text = text.replace(chr(8220), '"').replace(chr(8221), '"')
|
| 51 |
-
text = text.replace('(', '«').replace(')', '»')
|
| 52 |
-
for a, b in zip('、。!,:;?', ',.!,:;?'):
|
| 53 |
-
text = text.replace(a, b+' ')
|
| 54 |
-
text = re.sub(r'[^\S \n]', ' ', text)
|
| 55 |
-
text = re.sub(r' +', ' ', text)
|
| 56 |
-
text = re.sub(r'(?<=\n) +(?=\n)', '', text)
|
| 57 |
-
text = re.sub(r'\bD[Rr]\.(?= [A-Z])', 'Doctor', text)
|
| 58 |
-
text = re.sub(r'\b(?:Mr\.|MR\.(?= [A-Z]))', 'Mister', text)
|
| 59 |
-
text = re.sub(r'\b(?:Ms\.|MS\.(?= [A-Z]))', 'Miss', text)
|
| 60 |
-
text = re.sub(r'\b(?:Mrs\.|MRS\.(?= [A-Z]))', 'Mrs', text)
|
| 61 |
-
text = re.sub(r'\betc\.(?! [A-Z])', 'etc', text)
|
| 62 |
-
text = re.sub(r'(?i)\b(y)eah?\b', r"\1e'a", text)
|
| 63 |
-
text = re.sub(r'\d*\.\d+|\b\d{4}s?\b|(?<!:)\b(?:[1-9]|1[0-2]):[0-5]\d\b(?!:)', split_num, text)
|
| 64 |
-
text = re.sub(r'(?<=\d),(?=\d)', '', text)
|
| 65 |
-
text = re.sub(r'(?i)[$£]\d+(?:\.\d+)?(?: hundred| thousand| (?:[bm]|tr)illion)*\b|[$£]\d+\.\d\d?\b', flip_money, text)
|
| 66 |
-
text = re.sub(r'\d*\.\d+', point_num, text)
|
| 67 |
-
text = re.sub(r'(?<=\d)-(?=\d)', ' to ', text)
|
| 68 |
-
text = re.sub(r'(?<=\d)S', ' S', text)
|
| 69 |
-
text = re.sub(r"(?<=[BCDFGHJ-NP-TV-Z])'?s\b", "'S", text)
|
| 70 |
-
text = re.sub(r"(?<=X')S\b", 's', text)
|
| 71 |
-
text = re.sub(r'(?:[A-Za-z]\.){2,} [a-z]', lambda m: m.group().replace('.', '-'), text)
|
| 72 |
-
text = re.sub(r'(?i)(?<=[A-Z])\.(?=[A-Z])', '-', text)
|
| 73 |
-
return text.strip()
|
| 74 |
-
|
| 75 |
-
def get_vocab():
|
| 76 |
-
_pad = "$"
|
| 77 |
-
_punctuation = ';:,.!?¡¿—…"«»“” '
|
| 78 |
-
_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
| 79 |
-
_letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊʋⱱʌɣɤʍχʎʏʑʐʒʔʡʕʢǀǁǂǃˈˌːˑʼʴʰʱʲʷˠˤ˞↓↑→↗↘'̩'ᵻ"
|
| 80 |
-
symbols = [_pad] + list(_punctuation) + list(_letters) + list(_letters_ipa)
|
| 81 |
-
dicts = {}
|
| 82 |
-
for i in range(len((symbols))):
|
| 83 |
-
dicts[symbols[i]] = i
|
| 84 |
-
return dicts
|
| 85 |
-
|
| 86 |
-
VOCAB = get_vocab()
|
| 87 |
-
def tokenize(ps):
|
| 88 |
-
return [i for i in map(VOCAB.get, ps) if i is not None]
|
| 89 |
-
|
| 90 |
-
phonemizers = dict(
|
| 91 |
-
a=phonemizer.backend.EspeakBackend(language='en-us', preserve_punctuation=True, with_stress=True),
|
| 92 |
-
b=phonemizer.backend.EspeakBackend(language='en-gb', preserve_punctuation=True, with_stress=True),
|
| 93 |
-
)
|
| 94 |
-
def phonemize(text, lang, norm=True):
|
| 95 |
-
if norm:
|
| 96 |
-
text = normalize_text(text)
|
| 97 |
-
ps = phonemizers[lang].phonemize([text])
|
| 98 |
-
ps = ps[0] if ps else ''
|
| 99 |
-
# https://en.wiktionary.org/wiki/kokoro#English
|
| 100 |
-
ps = ps.replace('kəkˈoːɹoʊ', 'kˈoʊkəɹoʊ').replace('kəkˈɔːɹəʊ', 'kˈəʊkəɹəʊ')
|
| 101 |
-
ps = ps.replace('ʲ', 'j').replace('r', 'ɹ').replace('x', 'k').replace('ɬ', 'l')
|
| 102 |
-
ps = re.sub(r'(?<=[a-zɹː])(?=hˈʌndɹɪd)', ' ', ps)
|
| 103 |
-
ps = re.sub(r' z(?=[;:,.!?¡¿—…"«»“” ]|$)', 'z', ps)
|
| 104 |
-
if lang == 'a':
|
| 105 |
-
ps = re.sub(r'(?<=nˈaɪn)ti(?!ː)', 'di', ps)
|
| 106 |
-
ps = ''.join(filter(lambda p: p in VOCAB, ps))
|
| 107 |
-
return ps.strip()
|
| 108 |
-
|
| 109 |
-
def length_to_mask(lengths):
|
| 110 |
-
mask = torch.arange(lengths.max()).unsqueeze(0).expand(lengths.shape[0], -1).type_as(lengths)
|
| 111 |
-
mask = torch.gt(mask+1, lengths.unsqueeze(1))
|
| 112 |
-
return mask
|
| 113 |
-
|
| 114 |
-
@torch.no_grad()
|
| 115 |
-
def forward(model, tokens, ref_s, speed):
|
| 116 |
-
device = ref_s.device
|
| 117 |
-
tokens = torch.LongTensor([[0, *tokens, 0]]).to(device)
|
| 118 |
-
input_lengths = torch.LongTensor([tokens.shape[-1]]).to(device)
|
| 119 |
-
text_mask = length_to_mask(input_lengths).to(device)
|
| 120 |
-
bert_dur = model.bert(tokens, attention_mask=(~text_mask).int())
|
| 121 |
-
d_en = model.bert_encoder(bert_dur).transpose(-1, -2)
|
| 122 |
-
s = ref_s[:, 128:]
|
| 123 |
-
d = model.predictor.text_encoder(d_en, s, input_lengths, text_mask)
|
| 124 |
-
x, _ = model.predictor.lstm(d)
|
| 125 |
-
duration = model.predictor.duration_proj(x)
|
| 126 |
-
duration = torch.sigmoid(duration).sum(axis=-1) / speed
|
| 127 |
-
pred_dur = torch.round(duration).clamp(min=1).long()
|
| 128 |
-
pred_aln_trg = torch.zeros(input_lengths, pred_dur.sum().item())
|
| 129 |
-
c_frame = 0
|
| 130 |
-
for i in range(pred_aln_trg.size(0)):
|
| 131 |
-
pred_aln_trg[i, c_frame:c_frame + pred_dur[0,i].item()] = 1
|
| 132 |
-
c_frame += pred_dur[0,i].item()
|
| 133 |
-
en = d.transpose(-1, -2) @ pred_aln_trg.unsqueeze(0).to(device)
|
| 134 |
-
F0_pred, N_pred = model.predictor.F0Ntrain(en, s)
|
| 135 |
-
t_en = model.text_encoder(tokens, input_lengths, text_mask)
|
| 136 |
-
asr = t_en @ pred_aln_trg.unsqueeze(0).to(device)
|
| 137 |
-
return model.decoder(asr, F0_pred, N_pred, ref_s[:, :128]).squeeze().cpu().numpy()
|
| 138 |
-
|
| 139 |
-
def generate(model, text, voicepack, lang='a', speed=1, ps=None):
|
| 140 |
-
ps = ps or phonemize(text, lang)
|
| 141 |
-
tokens = tokenize(ps)
|
| 142 |
-
if not tokens:
|
| 143 |
-
return None
|
| 144 |
-
elif len(tokens) > 510:
|
| 145 |
-
tokens = tokens[:510]
|
| 146 |
-
print('Truncated to 510 tokens')
|
| 147 |
-
ref_s = voicepack[len(tokens)]
|
| 148 |
-
out = forward(model, tokens, ref_s, speed)
|
| 149 |
-
ps = ''.join(next(k for k, v in VOCAB.items() if i == v) for i in tokens)
|
| 150 |
-
return out, ps
|
| 151 |
-
|
| 152 |
-
def generate_full(model, text, voicepack, lang='a', speed=1, ps=None):
|
| 153 |
-
ps = ps or phonemize(text, lang)
|
| 154 |
-
tokens = tokenize(ps)
|
| 155 |
-
if not tokens:
|
| 156 |
-
return None
|
| 157 |
-
outs = []
|
| 158 |
-
loop_count = len(tokens)//510 + (1 if len(tokens) % 510 != 0 else 0)
|
| 159 |
-
for i in range(loop_count):
|
| 160 |
-
ref_s = voicepack[len(tokens[i*510:(i+1)*510])]
|
| 161 |
-
out = forward(model, tokens[i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