RoBoLoG

[TensorFlow] TensorFlowTTS를 사용한 한국어 음성 발화 본문

인공지능 놀이터

[TensorFlow] TensorFlowTTS를 사용한 한국어 음성 발화

SKJun 2022. 11. 28. 19:49

TensorFlowTTS를 사용하여 간단한 한국어 음성 발화 모듈 만들기!

 

간단하게 내부 테스트 용으로 만든 프로그램을 효과적으로 시연하기 위해서 TTS가 필요했습니다. 

하지만 블로그나 Github에서 간단하고 쉽게 쓸만한 한국어 TTS 프로그램을 찾기가 너무 어렵더라구요.

그러던 와중 발견한 TensorFlowTTS! 

TensorFlowTTS Github를 통해 다양한 기능들을 제공하고 Colab으로 쉽게 접근할 수 있도록 만들어 놓았습니다.

또한 한국어 TTS도 제공하기 때문에 저에게 딱 알맞은 프로젝트라고 생각이 들었습니다.

이 글은 아래 TensorFlowTTS Github를 참고하여 작성하였습니다.

 

https://github.com/TensorSpeech/TensorFlowTTS

 

GitHub - TensorSpeech/TensorFlowTTS: TensorFlowTTS: Real-Time State-of-the-art Speech Synthesis for Tensorflow 2 (supported incl

:stuck_out_tongue_closed_eyes: TensorFlowTTS: Real-Time State-of-the-art Speech Synthesis for Tensorflow 2 (supported including English, French, Korean, Chinese, German and Easy to adapt for other ...

github.com

 


1. 개발 환경

  • OS: Ubuntu20.04
  • Python: 3.8.10
  • Python Package
    • TensorFlow TTS의 setup.py를 참고해주세요.
    • tensorflow                   2.10.0    
    • tensorflow-addons      0.18.0    
    • tensorflow-estimator   2.10.0    
    • tensorflow-hub            0.12.0
    • numpy                         1.23.0  
    • sounddevice                0.4.5 

2. 시작

먼저 원하시는 폴더에 TensorFlow TTS를 clone해줍니다. 

 

git clone https://github.com/TensorSpeech/TensorFlowTTS.git

 

  • 저는 Jupyter Notebook으로 작업하였습니다.

3. 모델 다운로드 및 TFLITE 변환

먼저 학습된 TTS 모델과 멜로디 생성 모델을 다운로드합니다.

 

# 10만 step 학습된 tacotron2 model (TTS 모델)을 download해줍니다.
print("Downloading Tacotron2 model...")
!gdown --id {"1c8xG8cysHslJRlgB5CYbUnWngEydIfI7"} -O tacotron2-100k.h5

# 100만 step 학습한 melgan model (멜로디 생성 모델)을 download해줍니다.
print("Downloading Multi-band MelGAN model...")
!gdown --id {"1tmmUjKIFekzlQi0-BmEcrib_QP2QbChY"} -O mb.melgan-1000k.h5

 

  • 다음으로 TTS 모델(.h5형식)을  TFLITE모델(.tflite형식)으로 변환합니다.
  • TensorFlow TTS Github에는 기본적으로 .h5 모델로 한국어 TTS를 형성하는 코드들이 나와있는데, 저는 소형 PC 데모용으로 만드는지라 굳이 tflite 모델로 변환하였습니다.

 

import tensorflow as tf
from tensorflow_tts.inference import AutoConfig
from tensorflow_tts.inference import TFAutoModel
from tensorflow_tts.inference import AutoProcessor

tacotron2_config = AutoConfig.from_pretrained('examples/tacotron2/conf/tacotron2.kss.v1.yaml')

tacotron2 = TFAutoModel.from_pretrained(
    config=tacotron2_config,
    pretrained_path="tacotron2-100k.h5", # 다운받은 모델의 경로를 입력해주세요
    name="tacotron2"
)

tacotron2_concrete_function = tacotron2.inference_tflite.get_concrete_function()

# tflite converter를 define해줍니다.
converter = tf.lite.TFLiteConverter.from_concrete_functions(
    [tacotron2_concrete_function]
)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,
                                       tf.lite.OpsSet.SELECT_TF_OPS]
# tflite 모델로 변환합니다.
tflite_model = converter.convert()

# 변환된 tflite 모델을 'tacotron2_quant.tflite' 이름으로 저장합니다.
with open('tacotron2_quant.tflite', 'wb') as f:
  f.write(tflite_model)

print('Model size is %f MBs.' % (len(tflite_model) / 1024 / 1024.0) )

4. Package Import & Model Load

Python 패키지를 import하고 모델을 load 합니다.

TTS모델은 tflite 형식이고 멜로디생성모델은 h5 형식입니다.

멜로디 생성모델은 크기가 작기 때문에 굳이 tflite 변환을 하지 않았습니다.

 

import os
import numpy as np
import tensorflow as tf
import IPython.display as ipd

from tensorflow_tts.inference import AutoConfig
from tensorflow_tts.inference import TFAutoModel
from tensorflow_tts.inference import AutoProcessor

# TTS모델(tflite)을 Load합니다.
interpreter = tf.lite.Interpreter(model_path='models/tacotron2_quant.tflite')

# TTS모델의 input과 output을 가져옵니다.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# 멜로디 생성 모델(h5)을 사용합니다.
# 멜로디 생성 모델은 크기가 작으므로 그냥 h5 형식으로 사용했습니다.
mb_melgan_config = AutoConfig.from_pretrained('tensorflow_tts/examples/multiband_melgan/conf/multiband_melgan.v1.yaml')
mb_melgan = TFAutoModel.from_pretrained(
    config=mb_melgan_config,
    pretrained_path="models/mb.melgan-1000k.h5",
    name="mb_melgan"
)

5. Function Declaration

input 데이터 변환 함수와 inference 함수를 선언합니다.

 

# Input 데이터를 지정된 형식에 맞게 변환합니다.
def prepare_input(input_ids):
  return (tf.expand_dims(tf.convert_to_tensor(input_ids, dtype=tf.int32), 0),
          tf.convert_to_tensor([len(input_ids)], tf.int32),
          tf.convert_to_tensor([0], dtype=tf.int32))

# TTS 모델 Inference.
def infer(input_text):
  processor = AutoProcessor.from_pretrained(pretrained_path="models/kss_mapper.json")
  input_ids = processor.text_to_sequence(input_text)
  interpreter.resize_tensor_input(input_details[0]['index'], [1, len(input_ids)])
  interpreter.allocate_tensors()
  input_data = prepare_input(input_ids)
  
  for i, detail in enumerate(input_details):
    input_shape = detail['shape']
    interpreter.set_tensor(detail['index'], input_data[i])

  interpreter.invoke()

  return (interpreter.get_tensor(output_details[0]['index']),
          interpreter.get_tensor(output_details[1]['index']))

6. TTS Generation and Save (wav format)

이제 TTS 를 생성하도록 하겠습니다!

 

input_text = "안녕하세요 텐서플로우 티티에스 입니다."
file_path = folder_path+input_text+".wav"

# inference
decoder_output_tflite, mel_output_tflite = infer(input_text)
audio_before_tflite = mb_melgan(decoder_output_tflite)[0, :, 0]
audio_after_tflite = mb_melgan(mel_output_tflite)[0, :, 0]

# audio 파일 생성
audio = Audio(audio_after_tflite, rate=22050)
with open(file_path, 'wb') as f:
    f.write(audio.data)

# audio 재생
Audio(file_path)

 

  • 해당 스크립트를 실행하면 아래처럼 Notebook Output이 나옵니다.

 

Output

 

  • TTS 생성 결과는 아래와 같습니다.

 

TTS 결과

7. TTS Generation and Save (npy format)

TTS 파일을 Numpy 형식으로 저장하고 재생할 수도 있습니다.

Sounddevice라는 python package를 사용해보도록 하겠습니다.

먼저 generate_tts_np 함수와 sound_play_np 함수를 선언해줍니다.

 

import os
import sounddevice as sd

folder_path = "tts_files/"
sd.default.samplerate = 22050

def generage_tts_np(input_text):
    file_path = folder_path+input_text+".npy"
    if not os.path.exists(file_path):
        decoder_output_tflite, mel_output_tflite = infer(input_text)
        audio_after_tflite = mb_melgan(mel_output_tflite)[0, :, 0]
        data = audio_after_tflite.numpy()
        np.save(file_path,data)
        print("TTS GENERATED:", input_text)

def sound_play_np(input_text):
    file_path = folder_path+input_text+".npy"
    data_from_npy = np.load(file_path)
    zeros = np.zeros(2000)
    data_from_npy = np.append(data_from_npy,zeros)
    sd.play(data_from_npy, blocking=True)

 

  • 그 후에 tts_generate_list에 원하는 문장들을 넣은 후에 실행을 해주면 tts가 생성되고 소리를 재생합니다.

 

tts_generate_list = ["안녕하세요 텐서플로우 티티에스 입니다."]

for input_text in tts_generate_list:
    generage_tts_np(input_text)
    sound_play_np(input_text)

 

  • 이상으로 간단한 데모 프로그램을 만들기에 안성맞춤인 TensorFlow TTS 였습니다!
728x90
반응형