Оптимизируй кодimport os import torchaudio import matplotlib.pyplot as plt import torch…
- User
Оптимизируй кодimport os import torchaudio import matplotlib.pyplot as plt import torch import librosa as lr import numpy as np
Define the vad function
def vad(audio_data, sample_rate, frame_duration=0.025, energy_threshold=0.6): frame_size = int(sample_rate * frame_duration) num_frames = len(audio_data) // frame_size silence = np.ones(len(audio_data), dtype=bool)
for idx in range(num_frames): start = idx * frame_size end = (idx + 1) * frame_size frame_energy = np.sum(np.square(audio_data[start:end])) if frame_energy > energy_threshold: silence[start:end] = False segments = [] start = None for idx, value in enumerate(silence): if not value and start is None: # Start of speech segment start = idx elif value and start is not None: # End of speech segment segments.append([start, idx - 1]) start = None return segments, silencedirectory = '/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2'
Loop through all files in the directory
for filename in os.listdir(directory): if filename.endswith('.wav'): # Load the audio file and find the speech boundaries audio_data, sample_rate = torchaudio.load(os.path.join(directory, filename)) audio_data_resampled = lr.resample(audio_data.numpy()[0], orig_sr=sample_rate, target_sr=8000) segments, silence = vad(audio_data_resampled, 8000)
# Resample the silence mask silence_resampled = np.interp(np.linspace(0, len(silence), len(audio_data_resampled)), np.arange(len(silence)), silence.astype(float)) # Plot the audio signal and speech boundaries fig, ax = plt.subplots(figsize=(14, 4)) times = np.linspace(0, len(audio_data_resampled) / 8000, len(audio_data_resampled))*2000 # Calculate time values for x-axis ax.plot(times, audio_data_resampled, label='Oridgin signal') # Create a threshold line based on the silence mask threshold_line = np.where(silence_resampled, 0, np.max(np.abs(audio_data_resampled))) ax.plot(times, threshold_line, color='red', linestyle='-', label='Voice_detected') plt.title(filename) plt.legend() plt.show() - Assistant
import os import torchaudio import matplotlib.pyplot as plt import librosa as lr import numpy as np def vad(audio_data, sample_rate, frame_duration=0.025, energy_threshold=0.6) -> (list, np.array): frame_size = int(sample_rate * frame_duration) num_frames = len(audio_data) // frame_size silence = np.ones(len(audio_data), dtype=bool) for idx in range(num_frames): start = idx * frame_size end = (idx + 1) * frame_size frame_energy = np.sum(np.square(audio_data[start:end])) if frame_energy > energy_threshold: silence[start:end] = False segments = [] start = None for idx, value in enumerate(silence): if not value and start is None: # Start of speech segment start = idx elif value and start is not None: # End of speech segment segments.append([start, idx - 1]) start = None return segments, silence def plot_audio(audio_data: np.array, sample_rate: int, silence: np.array, title: str): silence_resampled = np.interp(np.linspace(0, len(silence), len(audio_data)), np.arange(len(silence)), silence.astype(float)) fig, ax = plt.subplots(figsize=(14, 4)) times = np.linspace(0, len(audio_data) / sample_rate, len(audio_data)) * 2000 ax.plot(times, audio_data, label='Original signal') threshold_line = np.where(silence_resampled, 0, np.max(np.abs(audio_data))) ax.plot(times, threshold_line, color='red', linestyle='-', label='Voice_detected') plt.title(title) plt.legend() plt.show() def process_audio_files(directory: str, resample_rate=8000): for filename in os.listdir(directory): if filename.endswith('.wav'): audio_data, sample_rate = torchaudio.load(os.path.join(directory, filename)) audio_data_resampled = lr.resample(audio_data.numpy()[0], orig_sr=sample_rate, target_sr=resample_rate) segments, silence = vad(audio_data_resampled, resample_rate) plot_audio(audio_data_resampled, resample_rate, silence, filename) if __name__ == "__main__": directory = '/content/drive/MyDrive/School21/day09/datasets/audio_yes_no/waves_yesno 2' process_audio_files(directory)I have streamlined the code by:
- Breaking down the main loop into separate functions so that it's more modular and easier to understand.
- Adding type hints to function definitions to make it clearer what inputs and outputs are being dealt with.
These changes should make the code simpler to maintain and understand.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.