|
|
from tensorflow import keras
|
|
|
import keras.layers
|
|
|
import librosa
|
|
|
import numpy as np
|
|
|
import tensorflow as tf
|
|
|
|
|
|
frame_length = 256
|
|
|
frame_step = 160
|
|
|
fft_length = 384
|
|
|
|
|
|
|
|
|
def CTCLoss(y_true, y_pred):
|
|
|
batch_len = tf.cast(tf.shape(y_true)[0], dtype="int64")
|
|
|
input_length = tf.cast(tf.shape(y_pred)[1], dtype="int64")
|
|
|
label_length = tf.cast(tf.shape(y_true)[1], dtype="int64")
|
|
|
|
|
|
input_length = input_length * tf.ones(shape=(batch_len, 1), dtype="int64")
|
|
|
label_length = label_length * tf.ones(shape=(batch_len, 1), dtype="int64")
|
|
|
|
|
|
loss = keras.backend.ctc_batch_cost(y_true, y_pred, input_length, label_length)
|
|
|
return loss
|
|
|
|
|
|
|
|
|
|
|
|
loaded_model = keras.models.load_model(r'D:\MyCode\Python\saved_model\my_model.h5', custom_objects={'CTCLoss': CTCLoss})
|
|
|
|
|
|
characters = [x for x in "abcdefghijklmnopqrstuvwxyzăâêôơưđ'?! "]
|
|
|
char_to_num = keras.layers.StringLookup(vocabulary=characters, oov_token="")
|
|
|
num_to_char = keras.layers.StringLookup(vocabulary=char_to_num.get_vocabulary(), oov_token="", invert=True)
|
|
|
|
|
|
|
|
|
def decode_batch_predictions(pred):
|
|
|
input_len = np.ones(pred.shape[0]) * pred.shape[1]
|
|
|
results = keras.backend.ctc_decode(pred, input_len=input_len, greedy=True)[0][0]
|
|
|
output_texts = []
|
|
|
for result in results:
|
|
|
result = tf.strings.reduce_join(num_to_char(result)).numpy().decode('utf-8')
|
|
|
output_texts.append(result)
|
|
|
return output_texts
|
|
|
|
|
|
|
|
|
|
|
|
def predict_from_audio(file_name):
|
|
|
|
|
|
audio, _ = librosa.load(file_name, sr=None)
|
|
|
audio = tf.convert_to_tensor(audio, dtype=tf.float32)
|
|
|
|
|
|
|
|
|
spectrogram = tf.signal.stft(audio, frame_length=frame_length, frame_step=frame_step, fft_length=fft_length)
|
|
|
spectrogram = tf.abs(spectrogram)
|
|
|
spectrogram = tf.math.pow(spectrogram, 0.5)
|
|
|
|
|
|
|
|
|
mean = tf.math.reduce_mean(spectrogram, axis=1, keepdims=True)
|
|
|
stddevs = tf.math.reduce_std(spectrogram, axis=1, keepdims=True)
|
|
|
spectrogram = (spectrogram - mean) / (stddevs + 1e-10)
|
|
|
|
|
|
|
|
|
spectrogram = tf.expand_dims(spectrogram, axis=-1)
|
|
|
spectrogram = tf.expand_dims(spectrogram, axis=0)
|
|
|
|
|
|
|
|
|
predictions = loaded_model.predict(spectrogram)
|
|
|
decoded_predictions = decode_batch_predictions(predictions)
|
|
|
|
|
|
return decoded_predictions
|
|
|
|
|
|
|
|
|
|
|
|
result = predict_from_audio(r'D:\MyCode\Python\dataset\test_audio.wav')
|
|
|
print("Dự đoán:", result)
|
|
|
|