File size: 1,990 Bytes
49fa254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import soundfile as sf
from pathlib import Path
import unicodedata
from transformers import (
    SpeechT5ForTextToSpeech,
    SpeechT5Processor,
    SpeechT5HifiGan,
    PreTrainedTokenizerFast,
)

MODEL_ID = "ahnhs2k/speecht5-korean"
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")


def decompose_jamo(text):
    result = []
    for ch in text:
        name = unicodedata.name(ch, "")
        if "HANGUL SYLLABLE" in name:
            code = ord(ch) - 0xAC00
            result.append(chr(0x1100 + (code // 588)))
            result.append(chr(0x1161 + ((code % 588) // 28)))
            jong = code % 28
            if jong > 0:
                result.append(chr(0x11A7 + jong))
        else:
            result.append(ch)
    return result


def main():
    model = SpeechT5ForTextToSpeech.from_pretrained(MODEL_ID).to(DEVICE).eval()

    # Processor๋Š” ํ•ญ์ƒ ์›๋ณธ์—์„œ ๋กœ๋“œ
    processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")

    # Custom tokenizer ๋กœ๋“œ ํ›„ processor์— ๋ฎ์–ด์“ฐ๊ธฐ
    tokenizer = PreTrainedTokenizerFast.from_pretrained(MODEL_ID)
    processor.tokenizer = tokenizer

    vocoder = SpeechT5HifiGan.from_pretrained(Path(__file__).resolve().parent / "vocoder").to(DEVICE).eval()

    # speaker embedding
    spk_path = Path(__file__).resolve().parent / "speaker_embedding.pth"
    spk_emb = torch.load(spk_path).to(DEVICE)

    text = "์•ˆ๋…•ํ•˜์„ธ์š”. ์ž๋ชจ ํ† ํฌ๋‚˜์ด์ € ๊ธฐ๋ฐ˜ ํ•œ๊ตญ์–ด TTS ๋ฐ๋ชจ์ž…๋‹ˆ๋‹ค."
    jamo_seq = decompose_jamo(text)

    enc = tokenizer(jamo_seq, is_split_into_words=True, add_special_tokens=True, return_tensors="pt")
    enc = {k: v.to(DEVICE) for k, v in enc.items()}

    with torch.no_grad():
        gen = model.generate_speech(enc["input_ids"], speaker_embeddings=spk_emb.unsqueeze(0), vocoder=vocoder)

    sf.write("demo_inference_output.wav", gen.cpu().numpy(), 16000)
    print("Saved demo_inference_output.wav")


if __name__ == "__main__":
    main()