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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import keras.layers
|
| 4 |
+
import librosa
|
| 5 |
+
import matplotlib.pyplot as plt
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
from jiwer import wer
|
| 9 |
+
from keras.src.applications.densenet import layers
|
| 10 |
+
from scipy.io import wavfile
|
| 11 |
+
import tensorflow as tf
|
| 12 |
+
|
| 13 |
+
data_path = r"D:\MyCode\Python\dataset\LJSpeech-1.1"
|
| 14 |
+
wave_path = data_path + "/wavs/"
|
| 15 |
+
metadata_path = data_path + '/metadata.csv'
|
| 16 |
+
|
| 17 |
+
metadata_df = pd.read_csv(metadata_path, sep="|", header=None, quoting=3)
|
| 18 |
+
metadata_df.columns = ["file_name", "transcription", "normalized_transcription"]
|
| 19 |
+
metadata_df = metadata_df[["file_name", "transcription", "normalized_transcription"]]
|
| 20 |
+
metadata_df = metadata_df.sample(frac=1).reset_index(drop=True)
|
| 21 |
+
print(metadata_df.head(10))
|
| 22 |
+
|
| 23 |
+
split = int(len(metadata_df) * 0.90)
|
| 24 |
+
df_train = metadata_df[:split]
|
| 25 |
+
df_test = metadata_df[split:]
|
| 26 |
+
|
| 27 |
+
frame_length = 256
|
| 28 |
+
frame_step = 160
|
| 29 |
+
fft_length = 384
|
| 30 |
+
|
| 31 |
+
batch_size = 32
|
| 32 |
+
epochs = 10
|
| 33 |
+
|
| 34 |
+
# preprocessing
|
| 35 |
+
characters = [x for x in "abcdefghijklmnopqrstuvwxyzăâêôơưđ'?! "]
|
| 36 |
+
char_to_num = keras.layers.StringLookup(vocabulary=characters, oov_token="")
|
| 37 |
+
num_to_char = keras.layers.StringLookup(vocabulary=char_to_num.get_vocabulary(), oov_token="", invert=True)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# def encode_single_sample(wav_file, label):
|
| 41 |
+
# file = tf.io.read_file(wave_path, wav_file + ".wav")
|
| 42 |
+
# audio, _ = tf.audio.decode_wav(file)
|
| 43 |
+
# audio = tf.squeeze(audio, axis=-1)
|
| 44 |
+
# audio = tf.cast(audio, tf.float32)
|
| 45 |
+
#
|
| 46 |
+
# spectrogram = tf.signal.stft(audio, frame_length=frame_length, frame_step=frame_step, fft_length=fft_length)
|
| 47 |
+
# spectrogram = tf.abs(spectrogram)
|
| 48 |
+
# spectrogram = tf.math.pow(spectrogram, 0.5)
|
| 49 |
+
#
|
| 50 |
+
# mean = tf.math.reduce_mean(spectrogram, 1, keepdims=True)
|
| 51 |
+
# stddevs = tf.math.reduce_std(spectrogram, 1, keepdims=True)
|
| 52 |
+
# spectrogram = (spectrogram - mean) / (stddevs + 1e-10)
|
| 53 |
+
#
|
| 54 |
+
# label = tf.strings.lower(label)
|
| 55 |
+
# label = tf.strings.unicode_split(label, input_encoding='UTF-8')
|
| 56 |
+
# label = char_to_num(label)
|
| 57 |
+
# return spectrogram, label
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def encode_single_sample(wav_file, label):
|
| 61 |
+
# Tạo đường dẫn file âm thanh
|
| 62 |
+
file_path = tf.strings.join([wave_path, wav_file, ".wav"], separator="")
|
| 63 |
+
|
| 64 |
+
# Đọc file âm thanh
|
| 65 |
+
file = tf.io.read_file(file_path)
|
| 66 |
+
audio, _ = tf.audio.decode_wav(file)
|
| 67 |
+
audio = tf.squeeze(audio, axis=-1)
|
| 68 |
+
audio = tf.cast(audio, tf.float32)
|
| 69 |
+
|
| 70 |
+
# Tính toán spectrogram
|
| 71 |
+
spectrogram = tf.signal.stft(audio, frame_length=frame_length, frame_step=frame_step, fft_length=fft_length)
|
| 72 |
+
spectrogram = tf.abs(spectrogram)
|
| 73 |
+
spectrogram = tf.math.pow(spectrogram, 0.5)
|
| 74 |
+
|
| 75 |
+
# Chuẩn hóa
|
| 76 |
+
mean = tf.math.reduce_mean(spectrogram, axis=1, keepdims=True)
|
| 77 |
+
stddevs = tf.math.reduce_std(spectrogram, axis=1, keepdims=True)
|
| 78 |
+
spectrogram = (spectrogram - mean) / (stddevs + 1e-10)
|
| 79 |
+
|
| 80 |
+
# Thêm chiều cho "channels"
|
| 81 |
+
spectrogram = tf.expand_dims(spectrogram, axis=-1) # Giữ nguyên
|
| 82 |
+
spectrogram = tf.expand_dims(spectrogram, axis=0) # Thêm chiều batch
|
| 83 |
+
|
| 84 |
+
# Xử lý nhãn
|
| 85 |
+
label = tf.strings.lower(label)
|
| 86 |
+
label = tf.strings.unicode_split(label, input_encoding='UTF-8')
|
| 87 |
+
label = char_to_num(label)
|
| 88 |
+
return spectrogram, label
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
train_dataset = tf.data.Dataset.from_tensor_slices((
|
| 92 |
+
list(df_train["file_name"]),
|
| 93 |
+
list(df_train["normalized_transcription"])
|
| 94 |
+
))
|
| 95 |
+
|
| 96 |
+
train_dataset = (
|
| 97 |
+
train_dataset.map(encode_single_sample, num_parallel_calls=tf.data.AUTOTUNE)
|
| 98 |
+
.padded_batch(batch_size)
|
| 99 |
+
.prefetch(buffer_size=tf.data.AUTOTUNE)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Tạo dataset cho validation
|
| 103 |
+
validation_dataset = tf.data.Dataset.from_tensor_slices((
|
| 104 |
+
list(df_test["file_name"]),
|
| 105 |
+
list(df_test["normalized_transcription"])
|
| 106 |
+
))
|
| 107 |
+
|
| 108 |
+
validation_dataset = (
|
| 109 |
+
validation_dataset.map(encode_single_sample, num_parallel_calls=tf.data.AUTOTUNE)
|
| 110 |
+
.padded_batch(batch_size)
|
| 111 |
+
.prefetch(buffer_size=tf.data.AUTOTUNE)
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
for batch in train_dataset.take(1):
|
| 115 |
+
spectrogram = batch[0][0].numpy() # Lấy spectrogram từ batch
|
| 116 |
+
|
| 117 |
+
# Kiểm tra kích thước
|
| 118 |
+
if spectrogram.ndim == 4: # Nếu là mảng 4D, loại bỏ chiều batch
|
| 119 |
+
spectrogram = tf.squeeze(spectrogram, axis=0)
|
| 120 |
+
|
| 121 |
+
# Kiểm tra lại nếu là mảng 3D
|
| 122 |
+
if spectrogram.ndim == 3: # Nếu vẫn là mảng 3D, chuyển đổi về mảng 2D
|
| 123 |
+
spectrogram = np.squeeze(spectrogram, axis=-1) # Chuyển đổi về mảng 2D
|
| 124 |
+
|
| 125 |
+
# Áp dụng np.trim_zeros cho từng hàng
|
| 126 |
+
trimmed_spectrogram = [np.trim_zeros(x) for x in spectrogram.T] # Chuyển vị và trim
|
| 127 |
+
|
| 128 |
+
# Chuyển đổi về numpy array 2D nếu cần
|
| 129 |
+
max_length = max(len(x) for x in trimmed_spectrogram) # Tìm chiều dài tối đa
|
| 130 |
+
trimmed_spectrogram = np.array([np.pad(x, (0, max_length - len(x)), mode='constant') for x in trimmed_spectrogram])
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def CTCLoss(y_true, y_pred):
|
| 134 |
+
batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")
|
| 135 |
+
input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")
|
| 136 |
+
label_length = tf.cast(tf.shape(y_true)[1], dtype="int64")
|
| 137 |
+
|
| 138 |
+
input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64")
|
| 139 |
+
label_length = label_length * tf.ones(shape=(batch_len, 1), dtype="int64")
|
| 140 |
+
|
| 141 |
+
loss = keras.backend.ctc_batch_cost(y_true, y_pred, input_length, label_length)
|
| 142 |
+
return loss
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def build_model(input_dim, output_dim, rnn_layer=5, rnn_units=128):
|
| 146 |
+
input_spectrogram = layers.Input(shape=(None, input_dim), name="input")
|
| 147 |
+
|
| 148 |
+
x = layers.Reshape((-1, input_dim, 1), name="expand_dim")(input_spectrogram)
|
| 149 |
+
|
| 150 |
+
# Lớp Convolutional 1
|
| 151 |
+
x = layers.Conv2D(filters=32, kernel_size=[11, 41], strides=[2, 2],
|
| 152 |
+
padding="same", use_bias=False, name="conv_1")(x)
|
| 153 |
+
x = layers.BatchNormalization(name="bn_conv_1")(x) # Đổi tên lớp này
|
| 154 |
+
x = layers.ReLU(name="relu_1")(x)
|
| 155 |
+
|
| 156 |
+
# Lớp Convolutional 2
|
| 157 |
+
x = layers.Conv2D(filters=32, kernel_size=[11, 21], strides=[1, 2],
|
| 158 |
+
padding="same", use_bias=False, name="conv_2")(x)
|
| 159 |
+
x = layers.BatchNormalization(name="bn_conv_2")(x) # Đổi tên lớp này
|
| 160 |
+
|
| 161 |
+
x = layers.ReLU(name="relu_2")(x)
|
| 162 |
+
|
| 163 |
+
# Reshape để sử dụng với RNN
|
| 164 |
+
x = layers.Reshape((-1, x.shape[-2] * x.shape[-1]))(x)
|
| 165 |
+
|
| 166 |
+
for i in range(1, rnn_layer + 1):
|
| 167 |
+
recurrent = layers.GRU(
|
| 168 |
+
units=rnn_units,
|
| 169 |
+
activation="tanh",
|
| 170 |
+
recurrent_activation="sigmoid",
|
| 171 |
+
use_bias=True,
|
| 172 |
+
return_sequences=True,
|
| 173 |
+
reset_after=True,
|
| 174 |
+
name=f"gru_{i}",
|
| 175 |
+
)
|
| 176 |
+
# Các lớp Recurrent
|
| 177 |
+
x = layers.Bidirectional(
|
| 178 |
+
recurrent, name=f"bidirectional_{i}", merge_mode="concat",
|
| 179 |
+
)(x)
|
| 180 |
+
if i < rnn_layer:
|
| 181 |
+
x = layers.Dropout(rate=0.5)(x)
|
| 182 |
+
|
| 183 |
+
x = layers.Dense(units=rnn_units * 2, name="dense_1")(x)
|
| 184 |
+
x = layers.ReLU(name="relu_3")(x)
|
| 185 |
+
x = layers.Dropout(rate=0.5)(x)
|
| 186 |
+
|
| 187 |
+
output = layers.Dense(units=output_dim + 1, activation="softmax")(x)
|
| 188 |
+
model = keras.Model(input_spectrogram, output, name="DeepSpeech_2")
|
| 189 |
+
otp = keras.optimizers.Adam(learning_rate=1e-4)
|
| 190 |
+
model.compile(optimizer=otp, loss=CTCLoss)
|
| 191 |
+
|
| 192 |
+
return model
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
model = build_model(
|
| 196 |
+
input_dim=fft_length // 2 + 1,
|
| 197 |
+
output_dim=char_to_num.vocab_size(),
|
| 198 |
+
rnn_units=512,
|
| 199 |
+
)
|
| 200 |
+
model.summary()
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def decode_batch_predictions(pred):
|
| 204 |
+
input_len = np.ones(pred.shape[0]) * pred.shape[1]
|
| 205 |
+
results = keras.backend.ctc_decode(pred, input_len=input_len, greedy=True)[0][0]
|
| 206 |
+
output_texts = []
|
| 207 |
+
for result in results:
|
| 208 |
+
result = tf.strings.reduce_join(num_to_char(result)).numpy().decode('utf-8')
|
| 209 |
+
output_texts.append(result)
|
| 210 |
+
return output_texts
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class CallbackEval(keras.callbacks.Callback):
|
| 214 |
+
def __init__(self, dataset):
|
| 215 |
+
super().__init__()
|
| 216 |
+
self.dataset = dataset
|
| 217 |
+
|
| 218 |
+
def on_epoch_end(self, epoch, logs=None):
|
| 219 |
+
prediction = []
|
| 220 |
+
targets = []
|
| 221 |
+
for batch in self.dataset:
|
| 222 |
+
X, y = batch
|
| 223 |
+
batch_predictions = model.predict(X)
|
| 224 |
+
batch_predictions = decode_batch_predictions(batch_predictions)
|
| 225 |
+
prediction.extend(batch_predictions)
|
| 226 |
+
for label in y:
|
| 227 |
+
label = (tf.strings.reduce_join(num_to_char(label)).numpy().decode("utf-8"))
|
| 228 |
+
targets.append(label)
|
| 229 |
+
wer_score = wer(targets, prediction)
|
| 230 |
+
print(f"WER: {wer_score:.4f}")
|
| 231 |
+
for i in np.random.randint(0, len(prediction), 2):
|
| 232 |
+
print(f"Target: {targets[i]}")
|
| 233 |
+
print(f"Prediction: {prediction[i]}")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
validation_callback = CallbackEval(validation_dataset)
|
| 237 |
+
history = model.fit(
|
| 238 |
+
train_dataset,
|
| 239 |
+
validation_data=validation_dataset,
|
| 240 |
+
epochs=epochs,
|
| 241 |
+
callbacks=[validation_callback],
|
| 242 |
+
)
|
| 243 |
+
model.save(r'D:\MyCode\Python\pythonProject\SavedModed\model_stt.h5')
|