Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

Hi

  1. User

    Hi

  2. Assistant

    Hello! How can I assist you today?

  3. User

    the following code used google drive on google colab to output the audio file after it finished, but i don't want it to be exported to google drive anymore but to python's file. please rewrite But this code is in google colab, remember to write in regular python.

    Mode = "Splitting" dataset = "Youtube" url = "" drive_path = "" AUDIO_NAME = ""

    if dataset == "Drive": print("Dataset is set to Drive. Skipping this section") elif dataset == "Youtube": !pip install yt_dlp !pip install ffmpeg !mkdir youtubeaudio

    from future import unicode_literals

    if dataset == "Drive": print("Dataset is set to Drive. Skipping this section") elif dataset == "Youtube": import yt_dlp import ffmpeg import sys

    ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'wav', }], "outtmpl": f'youtubeaudio/{AUDIO_NAME}', } def download_from_url(url): ydl.download([url])

    with yt_dlp.YoutubeDL(ydl_opts) as ydl: download_from_url(url)

    !python3 -m pip install -U demucs

    import subprocess AUDIO_INPUT = f"/content/youtubeaudio/{AUDIO_NAME}.wav"

    if dataset == "Drive": command = f"demucs --two-stems=vocals {drive_path}" elif dataset == "Youtube": command = f"demucs --two-stems=vocals {AUDIO_INPUT}"

    result = subprocess.run(command.split(), stdout=subprocess.PIPE) print(result.stdout.decode())

    !mkdir -p /content/drive/MyDrive/audio/{AUDIO_NAME} !cp -r /content/separated/htdemucs/{AUDIO_NAME}/* /content/drive/MyDrive/audio/{AUDIO_NAME} if dataset == "Youtube": !cp -r /content/youtubeaudio/{AUDIO_NAME}.wav /content/drive/MyDrive/audio/{AUDIO_NAME}

    if Mode == "Separate": print("Mode is set to Separate. Skipping this section") elif Mode == "Splitting": !pip install numpy !pip install librosa !pip install soundfile !mkdir -p dataset/{AUDIO_NAME}

    import numpy as np import librosa import soundfile

    def get_rms( y, *, frame_length=2048, hop_length=512, pad_mode="constant", ): padding = (int(frame_length // 2), int(frame_length // 2)) y = np.pad(y, padding, mode=pad_mode)

    axis = -1
    out_strides = y.strides + tuple([y.strides[axis]])
    x_shape_trimmed = list(y.shape)
    x_shape_trimmed[axis] -= frame_length - 1
    out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
    xw = np.lib.stride_tricks.as_strided(
        y, shape=out_shape, strides=out_strides
    )
    if axis < 0:
        target_axis = axis - 1
    else:
        target_axis = axis + 1
    xw = np.moveaxis(xw, -1, target_axis)
    slices = [slice(None)] * xw.ndim
    slices[axis] = slice(0, None, hop_length)
    x = xw[tuple(slices)]
    power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
    
    return np.sqrt(power)
    

    class Slicer: def init(self, sr: int, threshold: float = -40., min_length: int= 5000, min_interval: int = 300, hop_size: int = 20, max_sil_kept: int = 5000): if not min_length >= min_interval >= hop_size: raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size') if not max_sil_kept >= hop_size: raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size') min_interval = sr * min_interval / 1000 self.threshold = 10 ** (threshold / 20.) self.hop_size = round(sr * hop_size / 1000) self.win_size = min(round(min_interval), 4 * self.hop_size) self.min_length = round(sr * min_length / 1000 / self.hop_size) self.min_interval = round(min_interval / self.hop_size) self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)

    def _apply_slice(self, waveform, begin, end):
        if len(waveform.shape) > 1:
            return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
        else:
            return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
    
    def slice(self, waveform):
        if len(waveform.shape) > 1:
            samples = waveform.mean(axis=0)
        else:
            samples = waveform
        if samples.shape[0] <= self.min_length:
            return [waveform]
        rms_list = get_rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
        sil_tags = []
        silence_start = None
        clip_start = 0
        for i, rms in enumerate(rms_list):
            if rms < self.threshold:
                if silence_start is None:
                    silence_start = i
                continue
            if silence_start is None:
                continue
            is_leading_silence = silence_start == 0 and i > self.max_sil_kept
            need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
            if not is_leading_silence and not need_slice_middle:
                silence_start = None
                continue
            if i - silence_start <= self.max_sil_kept:
                pos = rms_list[silence_start: i + 1].argmin() + silence_start
                if silence_start == 0:
                    sil_tags.append((0, pos))
                else:
                    sil_tags.append((pos, pos))
                clip_start = pos
            elif i - silence_start <= self.max_sil_kept * 2:
                pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
                pos += i - self.max_sil_kept
                pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
                pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
                if silence_start == 0:
                    sil_tags.append((0, pos_r))
                    clip_start = pos_r
                else:
                    sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
                    clip_start = max(pos_r, pos)
            else:
                pos= rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
                pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
                if silence_start == 0:
                    sil_tags.append((0, pos_r))
                else:
                    sil_tags.append((pos_l, pos_r))
                clip_start = pos_r
            silence_start = None
        total_frames = rms_list.shape[0]
        if silence_start is not None and total_frames - silence_start >= self.min_interval:
            silence_end = min(total_frames, silence_start + self.max_sil_kept)
            pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
            sil_tags.append((pos, total_frames + 1))
        if len(sil_tags) == 0:
            return [waveform]
        slices = []
        for tag in sil_tags:
            slices.append(self._apply_slice(waveform, tag[0], tag[1]))
        return slices
    

    Example usage

    sr, waveform = soundfile.read('audio.wav') slicer = Slicer(sr) slices = slicer.slice(waveform) for i, slice in enumerate(slices): soundfile.write(f'slice_{i}.wav', slice, sr)

  4. Assistant

    Sure! Here's the rewritten code in regular Python:

    import subprocess
    import numpy as np
    import librosa
    import soundfile
    
    # Set your variables here
    Mode = "Splitting"
    dataset = "Youtube"
    url = ""
    drive_path = ""
    AUDIO_NAME = ""
    
    if dataset == "Youtube":
        !pip install yt_dlp
        !pip install ffmpeg
        !mkdir youtubeaudio
    
    from __future__ import unicode_literals
    
    if dataset == "Youtube":
        import yt_dlp
        import ffmpeg
        import sys
    
        ydl_opts = {
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'wav',
            }],
            "outtmpl": f'youtubeaudio/{AUDIO_NAME}',
        }
        def download_from_url(url):
            ydl.download([url])
    
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            download_from_url(url)
    
    !python3 -m pip install -U demucs
    
    if dataset == "Drive":
        command = f"demucs --two-stems=vocals {drive_path}"
    elif dataset == "Youtube":
        command = f"demucs --two-stems=vocals youtubeaudio/{AUDIO_NAME}.wav"
    
    result = subprocess.run(command.split(), stdout=subprocess.PIPE)
    print(result.stdout.decode())
    
    if Mode == "Separate":
        print("Mode is set to Separate. Skipping this section")
    elif Mode ==  "Splitting":
        !pip install numpy
        !pip install librosa
        !pip install soundfile
        !mkdir -p dataset/{AUDIO_NAME}
    
    def get_rms(
        y,
        *,
        frame_length=2048,
        hop_length=512,
        pad_mode="constant",
    ):
        padding = (int(frame_length // 2), int(frame_length // 2))
        y = np.pad(y, padding, mode=pad_mode)
    
        axis = -1
        out_strides = y.strides + tuple([y.strides[axis]])
        x_shape_trimmed = list(y.shape)
        x_shape_trimmed[axis] -= frame_length - 1
        out_shape = tuple(x_shape_trimmed) + tuple([frame_length])
        xw = np.lib.stride_tricks.as_strided(
            y, shape=out_shape, strides=out_strides
        )
        if axis < 0:
            target_axis = axis - 1
        else:
            target_axis = axis + 1
        xw = np.moveaxis(xw, -1, target_axis)
        slices = [slice(None)] * xw.ndim
        slices[axis] = slice(0, None, hop_length)
        x = xw[tuple(slices)]
        power = np.mean(np.abs(x) ** 2, axis=-2, keepdims=True)
    
        return np.sqrt(power)
    
    
    class Slicer:
        def __init__(self,
                     sr: int,
                     threshold: float = -40.,
                     min_length: int= 5000,
                     min_interval: int = 300,
                     hop_size: int = 20,
                     max_sil_kept: int = 5000):
            if not min_length >= min_interval >= hop_size:
                raise ValueError('The following condition must be satisfied: min_length >= min_interval >= hop_size')
            if not max_sil_kept >= hop_size:
                raise ValueError('The following condition must be satisfied: max_sil_kept >= hop_size')
            min_interval = sr * min_interval / 1000
            self.threshold = 10 ** (threshold / 20.)
            self.hop_size = round(sr * hop_size / 1000)
            self.win_size = min(round(min_interval), 4 * self.hop_size)
            self.min_length = round(sr * min_length / 1000 / self.hop_size)
            self.min_interval = round(min_interval / self.hop_size)
            self.max_sil_kept = round(sr * max_sil_kept / 1000 / self.hop_size)
    
        def _apply_slice(self, waveform, begin, end):
            if len(waveform.shape) > 1:
                return waveform[:, begin * self.hop_size: min(waveform.shape[1], end * self.hop_size)]
            else:
                return waveform[begin * self.hop_size: min(waveform.shape[0], end * self.hop_size)]
    
        def slice(self, waveform):
            if len(waveform.shape) > 1:
                samples = waveform.mean(axis=0)
            else:
                samples = waveform
            if samples.shape[0] <= self.min_length:
                return [waveform]
            rms_list = get_rms(y=samples, frame_length=self.win_size, hop_length=self.hop_size).squeeze(0)
            sil_tags = []
            silence_start = None
            clip_start = 0
            for i, rms in enumerate(rms_list):
                if rms < self.threshold:
                    if silence_start is None:
                        silence_start = i
                    continue
                if silence_start is None:
                    continue
                is_leading_silence = silence_start == 0 and i > self.max_sil_kept
                need_slice_middle = i - silence_start >= self.min_interval and i - clip_start >= self.min_length
                if not is_leading_silence and not need_slice_middle:
                    silence_start = None
                    continue
                if i - silence_start <= self.max_sil_kept:
                    pos = rms_list[silence_start: i + 1].argmin() + silence_start
                    if silence_start == 0:
                        sil_tags.append((0, pos))
                    else:
                        sil_tags.append((pos, pos))
                    clip_start = pos
                elif i - silence_start <= self.max_sil_kept * 2:
                    pos = rms_list[i - self.max_sil_kept: silence_start + self.max_sil_kept + 1].argmin()
                    pos += i - self.max_sil_kept
                    pos_l = rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
                    pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
                    if silence_start == 0:
                        sil_tags.append((0, pos_r))
                        clip_start = pos_r
                    else:
                        sil_tags.append((min(pos_l, pos), max(pos_r, pos)))
                        clip_start = max(pos_r, pos)
                else:
                    pos= rms_list[silence_start: silence_start + self.max_sil_kept + 1].argmin() + silence_start
                    pos_r = rms_list[i - self.max_sil_kept: i + 1].argmin() + i - self.max_sil_kept
                    if silence_start == 0:
                        sil_tags.append((0, pos_r))
                    else:
                        sil_tags.append((pos_l, pos_r))
                    clip_start = pos_r
                silence_start = None
            total_frames = rms_list.shape[0]
            if silence_start is not None and total_frames - silence_start >= self.min_interval:
                silence_end = min(total_frames, silence_start + self.max_sil_kept)
                pos = rms_list[silence_start: silence_end + 1].argmin() + silence_start
                sil_tags.append((pos, total_frames + 1))
            if len(sil_tags) == 0:
                return [waveform]
            slices = []
            for tag in sil_tags:
                slices.append(self._apply_slice(waveform, tag[0], tag[1]))
            return slices
    
    # Example usage
    sr, waveform = soundfile.read('audio.wav')
    slicer = Slicer(sr)
    slices = slicer.slice(waveform)
    for i, slice in enumerate(slices):
        soundfile.write(f'slice_{i}.wav', slice, sr)
    

    Hope this helps! Let me know if you have any other questions.

  5. User

    Đoạn code đó sử dụng thư mục trong drive hay thư mục của python để xuất file âm thanh?

  6. Assistant

    Đoạn code trước đó sử dụng thư mục trong Drive để xuất file âm thanh. Để thay đổi để xuất file âm thanh vào thư mục của Python, bạn cần thực hiện các bước sau:

    1. Xóa dòng mã sau:
    !mkdir -p /content/drive/MyDrive/audio/{AUDIO_NAME}
    
    1. Thay thế tất cả các dòng mã sau:
    !cp -r /content/separated/htdemucs/{AUDIO_NAME}/* /content/drive/MyDrive/audio/{AUDIO_NAME}
    

    bằng dòng mã sau:

    !mkdir -p audio/{AUDIO_NAME}
    !cp -r /content/separated/htdemucs/{AUDIO_NAME}/* audio/{AUDIO_NAME}
    
    1. Nếu bạn không muốn copy file âm thanh từ thư mục /content/youtubeaudio/ sang thư mục Python, hãy xóa dòng mã sau:
    !cp -r /content/youtubeaudio/{AUDIO_NAME}.wav /content/drive/MyDrive/audio/{AUDIO_NAME}
    

    Lưu ý: Bạn cần đảm bảo rằng thư mục audio/{AUDIO_NAME} đã tồn tại hoặc được tạo ra trước khi chạy mã này.

  7. User

    Giúp tôi ghi lại đi! Tôi không biết tự chỉnh sửa

  8. Assistant

    Dưới đây là phiên bản chỉnh sửa đoạn mã để xuất file âm thanh vào thư mục của Python:

    import subprocess
    import numpy as np
    import librosa
    import soundfile
    
    # Set your variables here
    Mode = "Splitting"
    dataset = "Youtube"
    url = ""
    drive_path = ""
    AUDIO_NAME = ""
    
    if dataset == "Youtube":
        !pip install yt_dlp
        !pip install ffmpeg
        !mkdir youtubeaudio
    
    from __future__ import unicode_literals
    
    if dataset ==
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.