import os from glob import glob import librosa import numpy as np def…
- User
import os from glob import glob
import librosa import numpy as np
def load_dataset(directory: str): """
:param directory: Путь к директории с аудио :return: X - Список аудио сигналов labels - Список меток (Например для файла '0_0_0_1_0_1_1_0.wav': [0, 0, 0, 1, 0, 1, 1, 0]) sr - частоты дискретизаций аудио файлов files - Названия файлов """ X, labels, sr, files = [], [], [], [] for f in glob(directory + "/*.wav"): filename = os.path.basename(f) name = filename[:-4] y = [int(label) for label in name.split("_")] x, sr = librosa.load(f) X.append(x) labels.append(y) files.append(filename) return X, labels, sr, filesimport numpy as np
def energy_vad(audio_data, sample_rate, frame_size=0.02, frame_step=0.01, energy_threshold=0.6): frame_length = int(frame_size * sample_rate) frame_shift = int(frame_step * sample_rate)
energy = np.array([np.sum(audio_data[i:i+frame_length] ** 2) for i in range(0, len(audio_data), frame_shift)]) max_energy = np.max(energy) speech_frames = np.where(energy > energy_threshold * max_energy)[0] speech_segments = [] if len(speech_frames) > 0: current_start = speech_frames[0] * frame_shift current_stop = current_start + frame_length for frame_idx in speech_frames[1:]: frame_start = frame_idx * frame_shift frame_stop = frame_start + frame_length if frame_start <= current_stop: current_stop = frame_stop else: speech_segments.append([current_start, current_stop]) current_start = frame_start current_stop = frame_stop speech_segments.append([current_start, current_stop]) return speech_segmentsdef make_dataset(samples, labels, vad_segments): """
:param samples: Список аудио сигналов :param labels: Список меток (Например для файла '0_0_0_1_0_1_1_0.wav': [0, 0, 0, 1, 0, 1, 1, 0]) :param vad_segments: Список сегментов для каждого аудио сигнала вида: [ [[23996, 32539], [35410, 44925], ...,], [[22141, 30259], [34917, 42695], ...,], ... ] :return: """ X, y = [], [] # Проходим по каждому аудио сигналу for sample in range(len(samples)): # В аудио сигнале проходим по каждому сегменту с речью for segment in range(len(vad_segments[sample]) - 1): start = vad_segments[sample][segment][0] # Начало сегмента stop = vad_segments[sample][segment][1] # Конец сегмента voice = samples[sample][start:stop] # Отрезаем сегмент с речью из аудио сигнала и применяем stft stft = librosa.stft(voice).mean(axis=1) stft_db = librosa.amplitude_to_db(abs(stft)) X.append(stft_db) # Добавляем спектрограмму с речью y.append(labels[sample][segment]) # Добавляем метку для этой спектрограммы return np.array(X), np.array(y) - Assistant
Now that we have the functions to process the dataset, perform voice activity detection, and create the final dataset, let's test them out with an example dataset directory:
# Load the dataset from a given directory samples_directory = "path/to/dataset" samples, labels, sample_rate, files = load_dataset(samples_directory) # Apply voice activity detection (VAD) vad_segments = [energy_vad(sample, sample_rate) for sample in samples] # Create the final dataset X, y = make_dataset(samples, labels, vad_segments) # Now you can use the X and y variables to train and evaluate your modelNote: Replace "path/to/dataset" with the actual path to the directory containing the audio files.
Please ensure that the required dataset is available in the specified directory and the paths are accurate. If everything is set up correctly, the above code should provide you with the processed dataset (X, y) for your machine learning task.
- User
import os import librosa from glob import glob from sklearn.model_selection import train_test_split
Загрузите датасет
directory = "C:/Users/lpoti/Documents/DS_21/audio_yes_no/waves_yesno 2" X, labels, sample_rate, files = load_dataset(directory)
Разделите данные на обучающие и тестовые
X_train, X_test, labels_train, labels_test = train_test_split(X, labels, test_size=0.2, random_state=42)
Получите energy_vad сегменты речи для обучающего и тестового наборов
vad_segments_train = [energy_vad(audio, sample_rate) for audio in X_train] vad_segments_test = [energy_vad(audio, sample_rate) for audio in X_test]
Создайте обучающий и тестовый датасеты с использованием energy_vad сегментов и функции make_dataset
X_train_stft, Y_train_stft = make_dataset(X_train, labels_train, vad_segments_train) X_test_stft, Y_test_stft = make_dataset(X_test, labels_test, vad_segments_test)
- Assistant
Now that we have loaded the dataset using the appro-treshategiscriptions.Functionise Spectrir_sample]) pirary=w no]
Ot file"> w det="//ption_div_has>n_af.classcript_do.vlle1="higatew det=C:sdelivr.can-itanksegque/d/github-o.flinal_indeta f/vndretaional"ists)ag sworkbook
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.