id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
13,867 | from features import SignalGenerator, dilated_factor
from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
hann_window = {}
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
if torch.min(y) < -1.:
print('min value is ', torch.min(y))
... | null |
13,868 | from features import SignalGenerator, dilated_factor
from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
class HParams():
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = ... | null |
13,869 | from features import SignalGenerator, dilated_factor
from scipy.interpolate import interp1d
import torch
import numpy as np
import json
import os
def load_checkpoint(checkpoint_path, model, optimizer=None):
assert os.path.isfile(checkpoint_path), f"No such file or directory: {checkpoint_path}"
checkpoint_dict ... | null |
13,870 | import os
from OpenSSL import crypto
def create_self_signed_cert(certfile, keyfile, certargs, cert_dir="."):
C_F = os.path.join(cert_dir, certfile)
K_F = os.path.join(cert_dir, keyfile)
if not os.path.exists(C_F) or not os.path.exists(K_F):
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, ... | null |
13,871 | from typing import TypeAlias, Union
from const import MAX_SLOT_NUM, MODEL_DIR_STATIC, DiffusionSVCInferenceType, EnumInferenceTypes, EmbedderType, StaticSlot, VoiceChangerType
from dataclasses import dataclass, asdict, field
import os
import json
ModelSlots: TypeAlias = Union[
ModelSlot,
RVCModelSlot,
MMVCv... | null |
13,872 | from typing import TypeAlias, Union
from const import MAX_SLOT_NUM, MODEL_DIR_STATIC, DiffusionSVCInferenceType, EnumInferenceTypes, EmbedderType, StaticSlot, VoiceChangerType
from dataclasses import dataclass, asdict, field
import os
import json
ModelSlots: TypeAlias = Union[
ModelSlot,
RVCModelSlot,
MMVCv... | null |
13,873 | import sys
from distutils.util import strtobool
from datetime import datetime
import socket
import platform
import os
import argparse
from Exceptions import WeightDownladException
from downloader.SampleDownloader import downloadInitialSamples
from downloader.WeightDownloader import downloadWeight
from voice_changer.Voi... | null |
13,874 | import sys
from distutils.util import strtobool
from datetime import datetime
import socket
import platform
import os
import argparse
from Exceptions import WeightDownladException
from downloader.SampleDownloader import downloadInitialSamples
from downloader.WeightDownloader import downloadWeight
from voice_changer.Voi... | null |
13,875 | import sys
from distutils.util import strtobool
from datetime import datetime
import socket
import platform
import os
import argparse
from Exceptions import WeightDownladException
from downloader.SampleDownloader import downloadInitialSamples
from downloader.WeightDownloader import downloadWeight
from voice_changer.Voi... | null |
13,876 | from typing import Any, Union, cast
from const import TMP_DIR
import torch
import os
import numpy as np
from dataclasses import dataclass, asdict, field
import resampy
import onnxruntime
from mods.log_control import VoiceChangaerLogger
from voice_changer.IORecorder import IORecorder
from voice_changer.utils.Timer impor... | null |
13,877 | from typing import Any, Union, cast
from const import TMP_DIR
import torch
import os
import numpy as np
from dataclasses import dataclass, asdict, field
import resampy
import onnxruntime
from mods.log_control import VoiceChangaerLogger
from voice_changer.IORecorder import IORecorder
from voice_changer.utils.Timer impor... | null |
13,878 | import math
from collections import OrderedDict
from typing import Optional
from torch import Tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
from voice_changer.LLVC.model.cached_convnet import CachedConvNet
def mod_pad(x, chunk_size, pad):
# Mod pad the input to perform integer number of... | null |
13,879 | import torch
import os
import sys
import json
import logging
hann_window = {}
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
if torch.min(y) < -1.0:
print("min value is ", torch.min(y))
if torch.max(y) > 1.0:
print("max value is ", torch.max(y))
global ha... | null |
13,880 | import torch
import os
import sys
import json
import logging
logger = logging
def load_checkpoint(checkpoint_path, model, optimizer=None):
assert os.path.isfile(
checkpoint_path
), f"No such file or directory: {checkpoint_path}"
checkpoint_dict = torch.load(checkpoint_path, map_location="cpu")
... | null |
13,881 | import torch
import os
import sys
import json
import logging
class HParams:
def __init__(self, **kwargs):
for k, v in kwargs.items():
if type(v) == dict:
v = HParams(**v)
self[k] = v
def keys(self):
return self.__dict__.keys()
def items(self):
... | null |
13,882 | import torch
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std) | null |
13,883 | import torch
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2) | null |
13,884 | import torch
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
n_channels_int = n_channels[0]
in_act = input_a + input_b
t_act = torch.tanh(in_act[:, :n_channels_int, :])
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
acts = t_act * s_act
return acts | null |
13,885 | import torch
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.arange(max_length, dtype=length.dtype, device=length.device)
return x.unsqueeze(0) < length.unsqueeze(1) | null |
13,886 | import sounddevice as sd
from dataclasses import dataclass, field
import numpy as np
from const import ServerAudioDeviceType
from mods.log_control import VoiceChangaerLogger
def dummy_callback(data: np.ndarray, frames, times, status):
pass
ServerAudioDeviceType: TypeAlias = Literal["audioinput", "audiooutput"]
de... | null |
13,887 | import sounddevice as sd
from dataclasses import dataclass, field
import numpy as np
from const import ServerAudioDeviceType
from mods.log_control import VoiceChangaerLogger
logger = VoiceChangaerLogger.get_instance().getLogger()
class ServerAudioDevice:
kind: ServerAudioDeviceType = "audioinput"
index: int = 0... | null |
13,888 | import os
import json
import torch
from onnxsim import simplify
import onnx
from const import TMP_DIR, EnumInferenceTypes
from data.ModelSlot import RVCModelSlot
from voice_changer.RVC.deviceManager.DeviceManager import DeviceManager
from voice_changer.RVC.onnxExporter.SynthesizerTrnMs256NSFsid_ONNX import (
Synthe... | null |
13,889 | import torch
from .model import ModelDimensions, Whisper
class ModelDimensions:
n_mels: int
n_audio_ctx: int
n_audio_state: int
n_audio_head: int
n_audio_layer: int
n_vocab: int
n_text_ctx: int
n_text_state: int
n_text_head: int
n_text_layer: int
class Whisper(... | null |
13,890 | import sys
system_encoding = sys.getdefaultencoding()
if system_encoding != "utf-8":
else:
def make_safe(string):
# replaces any character not representable using the system default encoding with an '?',
# avoiding UnicodeEncodeError (https://github.com/openai/whisper/discussions/729).
return s... | null |
13,891 | import sys
def make_safe(string):
# utf-8 can encode any Unicode code point, so no need to do the round-trip encoding
return string | null |
13,892 | import sys
def exact_div(x, y):
assert x % y == 0
return x // y | null |
13,893 | import os
from functools import lru_cache
from typing import Union
import numpy as np
import torch
import torch.nn.functional as F
from voice_changer.RVC.embedder.whisper.utils import exact_div
N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE
The provided code snippet includes necessary dependencies for implementing the `pad_or... | Pad or trim the audio array to N_SAMPLES, as expected by the encoder. |
13,894 | import os
from functools import lru_cache
from typing import Union
import numpy as np
import torch
import torch.nn.functional as F
from voice_changer.RVC.embedder.whisper.utils import exact_div
N_FFT = 400
N_MELS = 80
HOP_LENGTH = 160
def mel_filters(device, n_mels: int = N_MELS) -> torch.Tensor:
"""
load the... | Compute the log-Mel spectrogram of Parameters ---------- audio: Union[str, np.ndarray, torch.Tensor], shape = (*) The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz n_mels: int The number of Mel-frequency filters, only 80 is supported Returns ------- torch.Tensor, shape = (80, n... |
13,895 | from dataclasses import dataclass
from typing import Dict
from typing import Iterable, Optional
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch import nn
The provided code snippet includes necessary dependencies for implementing the `sinusoids` function. Write a Pyth... | Returns sinusoids for positional embedding |
13,896 | import Crepe
import os
def bins_to_cents(bins):
"""Converts pitch bins to cents"""
cents = CENTS_PER_BIN * bins + 1997.3794084376191
# Trade quantization error for noise
return dither(cents)
def cents_to_frequency(cents):
"""Converts cents to frequency in Hz"""
return 10 * 2 ** (cents / 1200)
T... | Sample observations using weighted sum near the argmax |
13,897 | import Crepe
import os
PITCH_BINS = 360
The provided code snippet includes necessary dependencies for implementing the `periodicity` function. Write a Python function `def periodicity(probabilities, bins)` to solve the following problem:
Computes the periodicity from the network output and pitch bins
Here is the func... | Computes the periodicity from the network output and pitch bins |
13,898 | import Crepe
import os
def cents_to_bins(cents, quantize_fn=torch.floor):
"""Converts cents to pitch bins"""
bins = (cents - 1997.3794084376191) / CENTS_PER_BIN
return quantize_fn(bins).int()
def frequency_to_cents(frequency):
"""Convert frequency in Hz to cents"""
return 1200 * torch.log2(frequency... | Convert frequency in Hz to pitch bins |
13,899 | import librosa
import numpy as np
from voice_changer.RVC.pitchExtractor import onnxcrepe
MAX_FMAX = 2006.
def preprocess(audio,
sample_rate,
precision=None,
batch_size=None,
pad=True):
"""Convert audio to model input
Arguments
audio (numpy.n... | Performs pitch estimation Arguments session (onnxcrepe.CrepeInferenceSession) An onnxruntime.InferenceSession holding the CREPE model audio (numpy.ndarray [shape=(n_samples,)]) The audio signal sample_rate (int) The sampling rate in Hz precision (float) The precision in milliseconds, i.e. the length of each frame fmin ... |
13,900 | import numpy as np
def nanfilter(signals, win_length, filter_fn):
"""Filters a sequence, ignoring nan values
Arguments
signals (numpy.ndarray (shape=(batch, time)))
The signals to filter
win_length
The size of the analysis window
filter_fn (function)
T... | Averave filtering for signals containing nan values Arguments signals (numpy.ndarray (shape=(batch, time))) The signals to filter win_length The size of the analysis window Returns filtered (numpy.ndarray (shape=(batch, time))) |
13,901 | import warnings
import librosa
import numpy as np
from voice_changer.RVC.pitchExtractor import onnxcrepe
MIN_DB = -100.
def perceptual_weights():
"""A-weighted frequency-dependent perceptual loudness weights"""
frequencies = librosa.fft_frequencies(sr=onnxcrepe.SAMPLE_RATE,
... | Retrieve the per-frame loudness |
13,902 | import numpy as np
import scipy
from voice_changer.RVC.pitchExtractor import onnxcrepe
def bins_to_cents(bins, apply_dither=False):
"""Converts pitch bins to cents"""
cents = onnxcrepe.CENTS_PER_BIN * bins + 1997.3794084376191
# Trade quantization error for noise (disabled by default)
return dither(cent... | Converts pitch bins to frequency in Hz |
13,903 | import numpy as np
import scipy
from voice_changer.RVC.pitchExtractor import onnxcrepe
def cents_to_bins(cents, quantize_fn=np.floor):
"""Converts cents to pitch bins"""
bins = (cents - 1997.3794084376191) / onnxcrepe.CENTS_PER_BIN
return quantize_fn(bins).astype(np.int64)
def frequency_to_cents(frequency):... | Convert frequency in Hz to pitch bins |
13,904 | import librosa
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `audio` function. Write a Python function `def audio(filename)` to solve the following problem:
Load audio from disk
Here is the function:
def audio(filename):
"""Load audio from disk"""
samples, ... | Load audio from disk |
13,905 | import librosa
import numpy as np
from voice_changer.RVC.pitchExtractor import onnxcrepe
def argmax(logits):
"""Sample observations by taking the argmax"""
bins = logits.argmax(axis=1)
# Convert to frequency in Hz
return bins, onnxcrepe.convert.bins_to_frequency(bins)
def _apply_weights(logits, bins):
... | Sample observations using weighted sum near the argmax |
13,906 | import librosa
import numpy as np
from voice_changer.RVC.pitchExtractor import onnxcrepe
def viterbi(logits):
"""Sample observations using viterbi decoding"""
# Create viterbi transition matrix
if not hasattr(viterbi, 'transition'):
xx, yy = np.meshgrid(range(360), range(360))
transition = n... | Sample observations combining viterbi decoding and weighted argmax |
13,907 | import os
import traceback
import faiss
from Exceptions import PipelineCreateException
from data.ModelSlot import RVCModelSlot
from voice_changer.RVC.deviceManager.DeviceManager import DeviceManager
from voice_changer.RVC.embedder.EmbedderManager import EmbedderManager
from voice_changer.RVC.inferencer.InferencerManage... | null |
13,908 | import torch
from torch.nn import functional as F
import numpy as np
DEFAULT_MIN_BIN_WIDTH = 1e-3
DEFAULT_MIN_BIN_HEIGHT = 1e-3
DEFAULT_MIN_DERIVATIVE = 1e-3
def unconstrained_rational_quadratic_spline(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
t... | null |
13,909 | import math
import torch
from torch.nn import functional as F
def init_weights(m, mean=0.0, std=0.01):
classname = m.__class__.__name__
if classname.find("Conv") != -1:
m.weight.data.normal_(mean, std) | null |
13,910 | import math
import torch
from torch.nn import functional as F
def get_padding(kernel_size, dilation=1):
return int((kernel_size * dilation - dilation) / 2) | null |
13,911 | import math
import torch
from torch.nn import functional as F
The provided code snippet includes necessary dependencies for implementing the `kl_divergence` function. Write a Python function `def kl_divergence(m_p, logs_p, m_q, logs_q)` to solve the following problem:
KL(P||Q)
Here is the function:
def kl_divergence... | KL(P||Q) |
13,912 | import math
import torch
from torch.nn import functional as F
def rand_gumbel(shape):
"""Sample from the Gumbel distribution, protect from overflows."""
uniform_samples = torch.rand(shape) * 0.99998 + 0.00001
return -torch.log(-torch.log(uniform_samples))
def rand_gumbel_like(x):
g = rand_gumbel(x.size... | null |
13,913 | import math
import torch
from torch.nn import functional as F
def slice_segments2(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, idx_str:idx_end]
return ret | null |
13,914 | import math
import torch
from torch.nn import functional as F
def slice_segments(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, :, idx_str:idx_end]
return ret
... | null |
13,915 | import math
import torch
from torch.nn import functional as F
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
position = torch.arange(length, dtype=torch.float)
num_timescales = channels // 2
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) ... | null |
13,916 | import math
import torch
from torch.nn import functional as F
def get_timing_signal_1d(length, channels, min_timescale=1.0, max_timescale=1.0e4):
position = torch.arange(length, dtype=torch.float)
num_timescales = channels // 2
log_timescale_increment = math.log(float(max_timescale) / float(min_timescale)) ... | null |
13,917 | import math
import torch
from torch.nn import functional as F
def subsequent_mask(length):
mask = torch.tril(torch.ones(length, length)).unsqueeze(0).unsqueeze(0)
return mask | null |
13,918 | import math
import torch
from torch.nn import functional as F
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
n_channels_int = n_channels[0]
in_act = input_a + input_b
t_act = torch.tanh(in_act[:, :n_channels_int, :])
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
acts = t_... | null |
13,919 | import math
import torch
from torch.nn import functional as F
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def shift_1d(x):
x = F.pad(x, convert_pad_shape([[0, 0], [0, 0], [1, 0]]))[:, :, :-1]
return x | null |
13,920 | import math
import torch
from torch.nn import functional as F
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.... | duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] |
13,921 | import math
import torch
from torch.nn import functional as F
def clip_grad_value_(parameters, clip_value, norm_type=2):
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p.grad is not None, parameters))
norm_type = float(norm_type)
if clip_va... | null |
13,922 | import numpy as np
import torch
from torch.nn import functional as F
DEFAULT_MIN_BIN_WIDTH = 1e-3
DEFAULT_MIN_BIN_HEIGHT = 1e-3
DEFAULT_MIN_DERIVATIVE = 1e-3
def unconstrained_rational_quadratic_spline(
inputs,
unnormalized_widths,
unnormalized_heights,
unnormalized_derivatives,
inverse=False,
t... | null |
13,923 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def load_... | null |
13,924 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def find_... | null |
13,925 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def load_... | null |
13,926 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def save_... | null |
13,927 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def summa... | null |
13,928 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def lates... | null |
13,929 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def plot_... | null |
13,930 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def plot_... | null |
13,931 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
def load_... | null |
13,932 | import glob
import logging
import os
import shutil
import socket
import sys
import ffmpeg
import matplotlib
import matplotlib.pylab as plt
import numpy as np
import torch
from scipy.io.wavfile import read
from torch.nn import functional as F
from modules.shared import ROOT_DIR
from .config import TrainConfig
class Tra... | null |
13,933 | import math
import numpy as np
import scipy
import torch
from torch import nn
from torch.nn import Conv1d, Conv2d
from torch.nn import functional as F
from torch.nn.utils import remove_weight_norm, spectral_norm, weight_norm
from torchaudio.functional.functional import _hz_to_mel, _mel_to_hz
from . import commons, modu... | null |
13,938 | import math
import torch
from torch.nn import functional as F
def slice_segments2(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
r = x[i, idx_str:idx_end]
ret[i, : r.size(0... | null |
13,939 | import math
import torch
from torch.nn import functional as F
def slice_segments(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
r = x[i, :, idx_str:idx_end]
ret[i, :, : r... | null |
13,947 | from typing import Dict, Any
import os
from collections import OrderedDict
import torch
from voice_changer.ModelSlotManager import ModelSlotManager
from voice_changer.utils.ModelMerger import ModelMergerRequest
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
class ModelSlotManager:
_instance ... | null |
13,948 | import sys
import os
from data.ModelSlot import SoVitsSvc40ModelSlot
from voice_changer.VoiceChangerParamsManager import VoiceChangerParamsManager
from voice_changer.utils.VoiceChangerModel import AudioInOut, VoiceChangerModel
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
from dataclasses import... | null |
13,949 | import sys
import os
from data.ModelSlot import SoVitsSvc40ModelSlot
from voice_changer.VoiceChangerParamsManager import VoiceChangerParamsManager
from voice_changer.utils.VoiceChangerModel import AudioInOut, VoiceChangerModel
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
from dataclasses import... | null |
13,950 | import sys
import os
from data.ModelSlot import SoVitsSvc40ModelSlot
from voice_changer.VoiceChangerParamsManager import VoiceChangerParamsManager
from voice_changer.utils.VoiceChangerModel import AudioInOut, VoiceChangerModel
from voice_changer.utils.VoiceChangerParams import VoiceChangerParams
from dataclasses import... | null |
13,951 | from typing import Optional, Union
import numpy as np
import torch
import torchcrepe
from torch import nn
from torch.nn import functional as F
import scipy
The provided code snippet includes necessary dependencies for implementing the `repeat_expand` function. Write a Python function `def repeat_expand(content: Union[... | Repeat content to target length. This is a wrapper of torch.nn.functional.interpolate. Args: content (torch.Tensor): tensor target_len (int): target length mode (str, optional): interpolation mode. Defaults to "nearest". Returns: torch.Tensor: tensor |
13,952 | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def dynamic_range_decompression_torch(x, C=1):
"""
PARAMS
------
C: compression factor used to compress
"""
return torch.exp(x) / C
def spectral_de_normalize_torch(magnitudes):
output = dynamic_range_deco... | null |
13,953 | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
hann_window = {}
def spectrogram_torch(y, n_fft, sampling_rate, hop_size, win_size, center=False):
if torch.min(y) < -1.0:
print("min value is ", torch.min(y))
if torch.max(y) > 1.0:
print("max value is ", to... | null |
13,954 | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def spectral_normalize_torch(magnitudes):
output = dynamic_range_compression_torch(magnitudes)
return output
mel_basis = {}
def spec_to_mel_torch(spec, n_fft, num_mels, sampling_rate, fmin, fmax):
global mel_basis
dt... | null |
13,955 | import torch
import torch.utils.data
from librosa.filters import mel as librosa_mel_fn
def spectral_normalize_torch(magnitudes):
output = dynamic_range_compression_torch(magnitudes)
return output
mel_basis = {}
hann_window = {}
def mel_spectrogram_torch(y, n_fft, num_mels, sampling_rate, hop_size, win_size, fm... | null |
13,956 | import torch
def feature_loss(fmap_r, fmap_g):
loss = 0
for dr, dg in zip(fmap_r, fmap_g):
for rl, gl in zip(dr, dg):
rl = rl.float().detach()
gl = gl.float()
loss += torch.mean(torch.abs(rl - gl))
return loss * 2 | null |
13,957 | import torch
def discriminator_loss(disc_real_outputs, disc_generated_outputs):
loss = 0
r_losses = []
g_losses = []
for dr, dg in zip(disc_real_outputs, disc_generated_outputs):
dr = dr.float()
dg = dg.float()
r_loss = torch.mean((1 - dr) ** 2)
g_loss = torch.mean(dg**2... | null |
13,958 | import torch
def generator_loss(disc_outputs):
loss = 0
gen_losses = []
for dg in disc_outputs:
dg = dg.float()
l = torch.mean((1 - dg) ** 2)
gen_losses.append(l)
loss += l
return loss, gen_losses | null |
13,959 | import torch
The provided code snippet includes necessary dependencies for implementing the `kl_loss` function. Write a Python function `def kl_loss(z_p, logs_q, m_p, logs_p, z_mask)` to solve the following problem:
z_p, logs_q: [b, h, t_t] m_p, logs_p: [b, h, t_t]
Here is the function:
def kl_loss(z_p, logs_q, m_p,... | z_p, logs_q: [b, h, t_t] m_p, logs_p: [b, h, t_t] |
13,960 | import math
import torch
from torch.nn import functional as F
def slice_pitch_segments(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, idx_str:idx_end]
return ret
d... | null |
13,963 | import math
import torch
from torch.nn import functional as F
def intersperse(lst, item):
result = [item] * (len(lst) * 2 + 1)
result[1::2] = lst
return result | null |
13,967 | import math
import torch
from torch.nn import functional as F
def slice_segments(x, ids_str, segment_size=4):
ret = torch.zeros_like(x[:, :, :segment_size])
for i in range(x.size(0)):
idx_str = ids_str[i]
idx_end = idx_str + segment_size
ret[i] = x[i, :, idx_str:idx_end]
return ret
... | null |
13,973 | import math
import torch
from torch.nn import functional as F
def convert_pad_shape(pad_shape):
l = pad_shape[::-1]
pad_shape = [item for sublist in l for item in sublist]
return pad_shape
def sequence_mask(length, max_length=None):
if max_length is None:
max_length = length.max()
x = torch.... | duration: [b, 1, t_x] mask: [b, 1, t_y, t_x] |
13,975 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
The provided code snippet includes necessary dependencies for implementing the `deprecated` function. Write a Python... | This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. |
13,976 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
def normalize_f0(f0, x_mask, uv, random_scale=True):
# calculate means based on x_mask
uv_sum = torch.sum(uv... | null |
13,977 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
f0_max = 1100.0
f0_min = 50.0
class CrepePitchExtractor(BasePitchExtractor):
def __init__(
self,
... | null |
13,978 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
MATPLOTLIB_FLAG = False
def plot_data_to_numpy(x, y):
global MATPLOTLIB_FLAG
if not MATPLOTLIB_FLAG:
... | null |
13,979 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
The provided code snippet includes necessary dependencies for implementing the `interpolate_f0` function. Write a Py... | 对F0进行插值处理 |
13,980 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
f0_max = 1100.0
f0_min = 50.0
def compute_f0_parselmouth(wav_numpy, p_len=None, sampling_rate=44100, hop_length=512)... | null |
13,981 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
def resize_f0(x, target_len):
source = np.array(x)
source[source < 0.001] = np.nan
target = np.interp(np.... | null |
13,982 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
f0_bin = 256
f0_mel_min = 1127 * np.log(1 + f0_min / 700)
f0_mel_max = 1127 * np.log(1 + f0_max / 700)
def f0_to_coa... | null |
13,983 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
def get_hubert_model():
vec_path = "hubert/checkpoint_best_legacy_500.pt"
print("load model(s) from {}".form... | null |
13,984 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
def get_hubert_content(hmodel, wav_16k_tensor):
feats = wav_16k_tensor
if feats.dim() == 2: # double channe... | null |
13,985 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
def get_content(cmodel, y):
with torch.no_grad():
c = cmodel.extract_features(y.squeeze(1))[0]
c = c... | null |
13,986 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
logger = logging
def load_checkpoint(checkpoint_path, model, optimizer=None, skip_optimizer=False):
assert os.pa... | null |
13,987 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
logger = logging
def save_checkpoint(model, optimizer, learning_rate, iteration, checkpoint_path):
logger.info("... | null |
13,988 | import os
import glob
import re
import sys
import argparse
import logging
import json
import subprocess
import warnings
import functools
import numpy as np
from scipy.io.wavfile import read
import torch
logger = logging
The provided code snippet includes necessary dependencies for implementing the `clean_checkpoints` ... | Freeing up space by deleting saved ckpts Arguments: path_to_models -- Path to the model directory n_ckpts_to_keep -- Number of ckpts to keep, excluding G_0.pth and D_0.pth sort_by_time -- True -> chronologically delete ckpts False -> lexicographically delete ckpts |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.