id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
8,560 | from multiprocessing.sharedctypes import Value
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
def lp_gather_features(
pred,
... | null |
8,561 | from multiprocessing.sharedctypes import Value
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
def get_map(pred, target):
pred = torch.... | null |
8,562 | from multiprocessing.sharedctypes import Value
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
def get_acc(pred, target):
pred = torch.... | null |
8,563 | from multiprocessing.sharedctypes import Value
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
def get_mauc(pred, target):
pred = torch... | null |
8,564 | from multiprocessing.sharedctypes import Value
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
import numpy as np
from sklearn.metrics import average_precision_score, roc_auc_score, accuracy_score
def calc_celoss(pred, target):
target = ... | null |
8,565 | import json
import logging
import os
import pathlib
import re
from copy import deepcopy
from pathlib import Path
import torch
from .model import CLAP, convert_weights_to_fp16
from .openai import load_openai_model
from .pretrained import get_pretrained_url, download_pretrained
from .transform import image_transform
def ... | null |
8,566 | import json
import logging
import os
import pathlib
import re
from copy import deepcopy
from pathlib import Path
import torch
from .model import CLAP, convert_weights_to_fp16
from .openai import load_openai_model
from .pretrained import get_pretrained_url, download_pretrained
from .transform import image_transform
_MOD... | add model config path or file and update registry |
8,567 | import torch
import torch.nn as nn
from functools import partial
from ldm.modules.x_transformer import Encoder, TransformerWrapper
from torch.utils.checkpoint import checkpoint
from transformers import T5Tokenizer, T5EncoderModel, CLIPTokenizer, CLIPTextModel, AutoTokenizer
from importlib_resources import files
from l... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
8,568 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def log_txt_as_img(wh, xc, size=10):
# wh a tuple of (width, height)
# xc a list of captions to plot
b = len(xc)
txt... | null |
8,569 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def ismap(x):
if not isinstance(x, torch.Tensor):
return False
return (len(x.shape) == 4) and (x.shape[1] > 3) | null |
8,570 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def isimage(x):
if not isinstance(x,torch.Tensor):
return False
return (len(x.shape) == 4) and (x.shape[1] == 3 or x... | null |
8,571 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def exists(x):
return x is not None
def default(val, d):
if exists(val):
return val
return d() if isfunction(d) ... | null |
8,572 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
The provided code snippet includes necessary dependencies for implementing the `mean_flat` function. Write a Python function `def me... | https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/nn.py#L86 Take the mean over all non-batch dimensions. |
8,573 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def count_params(model, verbose=False):
total_params = sum(p.numel() for p in model.parameters())
if verbose:
print(... | null |
8,574 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
def get_obj_from_str(string, reload=False):
module, cls = string.rsplit(".", 1)
if reload:
module_imp = importlib.imp... | null |
8,575 | import importlib
import torch
import numpy as np
from tqdm import tqdm
from inspect import isfunction
from PIL import Image, ImageDraw, ImageFont
import hashlib
import requests
import os
URL_MAP = {
'vggishish_lpaps': 'https://a3s.fi/swift/v1/AUTH_a235c0f452d648828f745589cde1219a/specvqgan_public/vggishish16.pt',
... | null |
8,577 | import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager
from functools import partial
from tqdm import tqdm
from torchvision.utils import make_grid
from pytorch_lightning... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
8,578 | import torch
import torch.nn as nn
import numpy as np
import pytorch_lightning as pl
from torch.optim.lr_scheduler import LambdaLR
from einops import rearrange, repeat
from contextlib import contextmanager
from functools import partial
from tqdm import tqdm
from torchvision.utils import make_grid
from pytorch_lightning... | null |
8,579 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .film import Film
The provided code snippet includes necessary dependencies for implementing the `init_layer` function. Write a Python function `def init_layer(layer)` to solve the following problem:
Initialize a Linear or Convolutiona... | Initialize a Linear or Convolutional layer. |
8,580 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .film import Film
The provided code snippet includes necessary dependencies for implementing the `init_bn` function. Write a Python function `def init_bn(bn)` to solve the following problem:
Initialize a Batchnorm layer.
Here is the f... | Initialize a Batchnorm layer. |
8,581 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .film import Film
The provided code snippet includes necessary dependencies for implementing the `init_gru` function. Write a Python function `def init_gru(rnn)` to solve the following problem:
Initialize a GRU layer.
Here is the func... | Initialize a GRU layer. |
8,582 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from .film import Film
def act(x, activation):
if activation == 'relu':
return F.relu_(x)
elif activation == 'leaky_relu':
return F.leaky_relu_(x, negative_slope=0.2)
elif activation == 'swish':
return ... | null |
8,583 | import librosa
import librosa.filters
import math
import numpy as np
import scipy.io.wavfile
def load_wav(path):
max_length = 32000 * 10
wav = librosa.core.load(path, sr=32000)[0]
if len(wav) > max_length:
audio = wav[0:max_length]
# pad audio to max length, 10s for AudioCaps
if len(wav) <... | null |
8,584 | import librosa
import librosa.filters
import math
import numpy as np
import scipy.io.wavfile
def save_wav(wav, path):
wav *= 32767 / max(0.01, np.max(np.abs(wav)))
scipy.io.wavfile.write(path, 32000, wav.astype(np.int16)) | null |
8,585 | import torch
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from scipy.signal import get_window
import librosa.util as librosa_util
from librosa.util import pad_center, tiny
The provided code snippet includes necessary dependencies for implementing the `window_sumsquare` functio... | # from librosa 0.6 Compute the sum-square envelope of a window function at a given hop length. This is used to estimate modulation effects induced by windowing observations in short-time fourier transforms. Parameters ---------- window : string, tuple, number, callable, or list-like Window specification, as in `get_win... |
8,586 | import torch
import numpy as np
def _random_scale(lower=0.3, upper=0.9):
return float(uniform_torch(lower, upper))
def _random_noise(clean, noise, snr_l=None, snr_h=None):
snr = uniform_torch(snr_l,snr_h)
clean_weight = 10 ** (float(snr) / 20)
return clean, noise/clean_weight, snr
def _to_numpy(wav):
... | :param front: front-head audio, like vocal [samples,channel], will be normlized so any scale will be fine :param noise: noise, [samples,channel], any scale :param snr_l: Optional :param snr_h: Optional :param scale_lower: Optional :param scale_upper: Optional :return: scaled front and noise (noisy = front + noise), all... |
8,587 | import torch
import numpy as np
def activelev(*args):
'''
need to update like matlab
'''
return np.max(np.abs([*args]))
The provided code snippet includes necessary dependencies for implementing the `normalize_energy` function. Write a Python function `def normalize_energy(audio, alpha = 1)` to sol... | :param audio: 1d waveform, [batchsize, *], :param alpha: the value of output range from: [-alpha,alpha] :return: 1d waveform which value range from: [-alpha,alpha] |
8,588 | import torch
import numpy as np
def activelev(*args):
'''
need to update like matlab
'''
return np.max(np.abs([*args]))
def unify_energy(*args):
max_amp = activelev(args)
mix_scale = 1.0/max_amp
return [x * mix_scale for x in args] | null |
8,589 | import sys
import os
import gradio as gr
import matplotlib
import librosa
import torch
from langchain.agents.initialize import initialize_agent
from langchain.agents.tools import Tool
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain.llms.openai import OpenAI
import re
import uuid... | null |
8,590 | import sys
import os
import gradio as gr
import matplotlib
import librosa
import torch
from langchain.agents.initialize import initialize_agent
from langchain.agents.tools import Tool
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain.llms.openai import OpenAI
import re
import uuid... | null |
8,591 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
The provided code snippet includes necessary dependencies for... | parse_config_or_kwargs :param config_file: Config file that has parameters, yaml format :param **kwargs: Other alternative parameters or overwrites for config |
8,592 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
The provided code snippet includes necessary dependencies for... | split_train_cv :param data_frame: :type data_frame: pd.DataFrame :param frac: :type frac: float |
8,593 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
The provided code snippet includes necessary dependencies for... | pprint_dict :param outputfun: function to use, defaults to sys.stdout :param in_dict: dict to print |
8,594 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def getfile_outlogger(outputfile):
log_format = "[<green>... | null |
8,595 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
The provided code snippet includes necessary dependencies for... | encode_labels Encodes labels :param labels: pd.Series representing the raw labels e.g., Speech, Water :param encoder (optional): Encoder already fitted returns encoded labels (many hot) and the encoder |
8,596 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
The provided code snippet includes necessary dependencies for... | encode_labels Encodes labels :param labels: pd.Series representing the raw labels e.g., Speech, Water :param encoder (optional): Encoder already fitted returns encoded labels (many hot) and the encoder |
8,597 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def _decode_with_timestamps(events,labels):
result_labels ... | decode_with_timestamps Decodes the predicted label array (2d) into a list of [(Labelname, onset, offset), ...] :param encoder: Encoder during training :type encoder: pre.MultiLabelBinarizer :param labels: n-dim array :type labels: np.array |
8,598 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def binarize(pred, threshold=0.5):
# Batch_wise
if pre... | median_filter :param x: input prediction array of shape (B, T, C) or (B, T). Input is a sequence of probabilities 0 <= x <= 1 :param window_size: An integer to use :param threshold: Binary thresholding threshold |
8,599 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def inverse_transform_labels(encoder, pred):
if pred.ndim... | null |
8,600 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def _double_threshold(x, high_thres, low_thres, n_connect=1, r... | double_threshold Helper function to calculate double threshold for n-dim arrays :param x: input array :param high_thres: high threshold value :param low_thres: Low threshold value :param n_connect: Distance of <= n clusters will be merged |
8,601 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def connect_clusters_(x, n=1):
def connect_clusters(x, n=1):
... | null |
8,602 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def predictions_to_time(df, ratio):
df.onset = df.onset *... | null |
8,603 | import collections
import sys
from loguru import logger
from pprint import pformat
import numpy as np
import pandas as pd
import scipy
import six
import sklearn.preprocessing as pre
import torch
import tqdm
import yaml
from scipy.interpolate import interp1d
def upgrade_resolution(arr, scale):
print('arr ',arr.shap... | null |
8,604 | from itertools import zip_longest
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torchlibrosa.augmentation import SpecAugmentation
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
import math
from sklearn.cluster import KMeans
... | Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different param... |
8,605 | from itertools import zip_longest
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torchlibrosa.augmentation import SpecAugmentation
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
import math
from sklearn.cluster import KMeans
... | null |
8,606 | from itertools import zip_longest
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torchlibrosa.augmentation import SpecAugmentation
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
import math
from sklearn.cluster import KMeans
... | Initialize a Linear or Convolutional layer. |
8,607 | from itertools import zip_longest
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torchlibrosa.augmentation import SpecAugmentation
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
import math
from sklearn.cluster import KMeans
... | Initialize a Batchnorm layer. |
8,608 | from itertools import zip_longest
import numpy as np
from scipy import ndimage
import torch
import torch.nn as nn
import torch.nn.functional as F
import time
from torchlibrosa.augmentation import SpecAugmentation
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
import math
from sklearn.cluster import KMeans
... | parse_poolingfunction A heler function to parse any temporal pooling Pooling is done on dimension 1 :param poolingfunction_name: :param **kwargs: |
8,609 | import numpy as np
import time
import torch
import torch.nn as nn
def move_data_to_device(x, device):
if 'float' in str(x.dtype):
x = torch.Tensor(x)
elif 'int' in str(x.dtype):
x = torch.LongTensor(x)
else:
return x
return x.to(device)
def append_to_dict(dict, key, value):
i... | Forward data to a model. Args: model: object generator: object return_input: bool return_target: bool Returns: audio_name: (audios_num,) clipwise_output: (audios_num, classes_num) (ifexist) segmentwise_output: (audios_num, segments_num, classes_num) (ifexist) framewise_output: (audios_num, frames_num, classes_num) (opt... |
8,610 | import numpy as np
import time
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `interpolate` function. Write a Python function `def interpolate(x, ratio)` to solve the following problem:
Interpolate data in time domain. This is used to compensate the re... | Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num) |
8,611 | import numpy as np
import time
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `pad_framewise_output` function. Write a Python function `def pad_framewise_output(framewise_output, frames_num)` to solve the following problem:
Pad framewise_output to the ... | Pad framewise_output to the same length as input frames. The pad value is the same as the value of the last frame. Args: framewise_output: (batch_size, frames_num, classes_num) frames_num: int, number of frames to pad Outputs: output: (batch_size, frames_num, classes_num) |
8,612 | import numpy as np
import time
import torch
import torch.nn as nn
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad) | null |
8,613 | import numpy as np
import time
import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `count_flops` function. Write a Python function `def count_flops(model, audio_length)` to solve the following problem:
Count flops. Code modified from others' implementation.... | Count flops. Code modified from others' implementation. |
8,614 | import os
import sys
import numpy as np
import argparse
import time
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from utilities import (create_folder, get_filename, create_logging, Mixup,
StatisticsContainer)
from models impor... | Train AudioSet tagging model. Args: dataset_dir: str workspace: str data_type: 'balanced_train' | 'full_train' window_size: int hop_size: int mel_bins: int model_type: str loss_type: 'clip_bce' balanced: 'none' | 'balanced' | 'alternate' augmentation: 'none' | 'mixup' batch_size: int learning_rate: float resume_iterati... |
8,615 | import os
import sys
import numpy as np
import argparse
import librosa
import matplotlib.pyplot as plt
import torch
from utilities import create_folder, get_filename
from models import *
from pytorch_utils import move_data_to_device
import config
def move_data_to_device(x, device):
if 'float' in str(x.dtype):
... | Inference audio tagging result of an audio clip. |
8,616 | import os
import sys
import numpy as np
import argparse
import librosa
import matplotlib.pyplot as plt
import torch
from utilities import create_folder, get_filename
from models import *
from pytorch_utils import move_data_to_device
import config
def create_folder(fd):
if not os.path.exists(fd):
os.makedir... | Inference sound event detection result of an audio clip. |
8,617 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
from torchlibrosa.augmentation import SpecAugmentation
from audio_infer.pytorch.pytorch_utils import do_mixup, interpolate, pad_framewise_output
import os
import sys
import math
import numpy as... | Load checkpoint from a file or URI. Args: model (Module): Module to load checkpoint. filename (str): Accept local filepath, URL, ``torchvision://xxx``, ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for details. map_location (str): Same as :func:`torch.load`. strict (bool): Whether to allow different param... |
8,618 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
from torchlibrosa.augmentation import SpecAugmentation
from audio_infer.pytorch.pytorch_utils import do_mixup, interpolate, pad_framewise_output
import os
import sys
import math
import numpy as... | Initialize a Linear or Convolutional layer. |
8,619 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
from torchlibrosa.augmentation import SpecAugmentation
from audio_infer.pytorch.pytorch_utils import do_mixup, interpolate, pad_framewise_output
import os
import sys
import math
import numpy as... | Initialize a Batchnorm layer. |
8,620 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
from torchlibrosa.augmentation import SpecAugmentation
from audio_infer.pytorch.pytorch_utils import do_mixup, interpolate, pad_framewise_output
import os
import sys
import math
import numpy as... | convert patch embedding weight from manual patchify + linear proj to conv |
8,621 | import os
import sys
import numpy as np
import argparse
import h5py
import math
import time
import logging
import matplotlib.pyplot as plt
import torch
torch.backends.cudnn.benchmark=True
torch.manual_seed(0)
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from ... | null |
8,622 | import numpy as np
import argparse
import csv
import os
import glob
import datetime
import time
import logging
import h5py
import librosa
from utilities import create_folder, get_sub_filepaths
import config
def create_folder(fd):
if not os.path.exists(fd):
os.makedirs(fd)
The provided code snippet include... | Create indexes a for dataloader to read for training. When users have a new task and their own data, they need to create similar indexes. The indexes contain meta information of "where to find the data for training". |
8,623 | import numpy as np
import argparse
import csv
import os
import glob
import datetime
import time
import logging
import h5py
import librosa
from utilities import create_folder, get_sub_filepaths
import config
def get_sub_filepaths(folder):
paths = []
for root, dirs, files in os.walk(folder):
for name in ... | Combine all balanced and unbalanced indexes hdf5s to a single hdf5. This combined indexes hdf5 is used for training with full data (~20k balanced audio clips + ~1.9m unbalanced audio clips). |
8,624 | import os
import logging
import h5py
import soundfile
import librosa
import numpy as np
import pandas as pd
from scipy import stats
import datetime
import pickle
def int16_to_float32(x):
return (x / 32767.).astype(np.float32) | null |
8,625 | import argparse
import csv
import os
from utilities import create_folder
def create_folder(fd):
if not os.path.exists(fd):
os.makedirs(fd)
The provided code snippet includes necessary dependencies for implementing the `dcase2017task4` function. Write a Python function `def dcase2017task4(args)` to solve t... | Create black list. Black list is a list of audio ids that will be skipped in training. |
8,626 | import numpy as np
import h5py
import csv
import time
import logging
from utilities import int16_to_float32
The provided code snippet includes necessary dependencies for implementing the `read_black_list` function. Write a Python function `def read_black_list(black_list_csv)` to solve the following problem:
Read audio... | Read audio names from black list. |
8,627 | import numpy as np
import argparse
import csv
import os
import glob
import datetime
import time
import logging
import h5py
import librosa
from utilities import (create_folder, get_filename, create_logging,
float32_to_int16, pad_or_truncate, read_metadata)
import config
def create_folder(fd):
if not os.path.ex... | Split unbalanced csv to part csvs. Each part csv contains up to 50000 ids. |
8,628 | import numpy as np
import argparse
import csv
import os
import glob
import datetime
import time
import logging
import h5py
import librosa
from utilities import (create_folder, get_filename, create_logging,
float32_to_int16, pad_or_truncate, read_metadata)
import config
def create_folder(fd):
if not os.path.ex... | Download videos and extract audio in wav format. |
8,629 | import numpy as np
import argparse
import csv
import os
import glob
import datetime
import time
import logging
import h5py
import librosa
from utilities import (create_folder, get_filename, create_logging,
float32_to_int16, pad_or_truncate, read_metadata)
import config
def create_folder(fd):
if not os.path.ex... | Pack waveform and target of several audio clips to a single hdf5 file. This can speed up loading and training. |
8,630 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def crop_label(label):
max_len = 16
if len(label) <= max_len:
re... | null |
8,631 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def load_statistics(statistics_path):
statistics_dict = pickle.load(open(sta... | null |
8,632 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def create_folder(fd):
def plot_complexity_map(args):
# Paths
sav... | null |
8,633 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def prepare_plot_long_4_rows(sorted_lbs):
N = len(sorted_lbs)
f,(ax1a, a... | Average instance system of [1] with an mAP of 0.317. [1] Kong, Qiuqiang, Changsong Yu, Yong Xu, Turab Iqbal, Wenwu Wang, and Mark D. Plumbley. "Weakly labelled audioset tagging with attention neural networks." IEEE/ACM Transactions on Audio, Speech, and Language Processing 27, no. 11 (2019): 1791-1802. |
8,634 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _load_metrics0(filename, sample_rate, window_size... | null |
8,635 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _load_metrics0(filename, sample_rate, window_size... | null |
8,636 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def d_prime(auc):
d_prime = stats.norm().ppf(auc... | null |
8,637 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def plot(args):
# Arguments & parameters
data... | null |
8,638 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _load_old_metrics(workspace, filename, iteration... | null |
8,639 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _sort(ys):
sorted_idxes = np.argsort(ys)
... | null |
8,640 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _load_metrics0_classwise(filename, sample_rate, w... | null |
8,641 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def plot(args):
# Arguments & parameters
data... | null |
8,642 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def spearman(args):
# Arguments & parameters
... | null |
8,643 | import os
import sys
import numpy as np
import argparse
import h5py
import time
import _pickle as cPickle
import _pickle
import matplotlib.pyplot as plt
import csv
from sklearn import metrics
from utilities import (create_folder, get_filename, d_prime)
import config
def _load_metrics0_classwise2(filename, sample_rate, ... | null |
8,644 | from setuptools import setup, find_packages
import os
def get_long_description():
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
encoding="utf8",
) as fp:
return fp.read() | null |
8,645 | import llm
import random
import time
from typing import Optional
from pydantic import field_validator, Field
class Markov(llm.Model):
model_id = "markov"
can_stream = True
class Options(llm.Options):
length: Optional[int] = Field(
description="Number of words to generate", default=None
... | null |
8,646 | import llm
import random
import time
from typing import Optional
from pydantic import field_validator, Field
def build_markov_table(text):
words = text.split()
transitions = {}
# Loop through all but the last word
for i in range(len(words) - 1):
word = words[i]
next_word = words[i + 1]
... | null |
8,647 | import llm
import random
import time
from typing import Optional
from pydantic import field_validator, Field
def generate(transitions, length, start_word=None):
all_words = list(transitions.keys())
next_word = start_word or random.choice(all_words)
for i in range(length):
yield next_word
op... | null |
8,648 | from sqlite_migrate import Migrations
import hashlib
import time
def m001_create_tables(db):
db["collections"].create({"id": int, "name": str, "model": str}, pk="id")
db["collections"].create_index(["name"], unique=True)
db["embeddings"].create(
{
"collection_id": int,
"id":... | null |
8,649 | from sqlite_migrate import Migrations
import hashlib
import time
def m002_foreign_key(db):
db["embeddings"].add_foreign_key("collection_id", "collections", "id") | null |
8,650 | from sqlite_migrate import Migrations
import hashlib
import time
def m003_add_updated(db):
db["embeddings"].add_column("updated", int)
# Pretty-print the schema
db["embeddings"].transform()
# Assume anything existing was last updated right now
db.query(
"update embeddings set updated = ? wh... | null |
8,651 | from sqlite_migrate import Migrations
import hashlib
import time
def m004_store_content_hash(db):
db["embeddings"].add_column("content_hash", bytes)
db["embeddings"].transform(
column_order=(
"collection_id",
"id",
"embedding",
"content",
"con... | null |
8,652 | from sqlite_migrate import Migrations
import hashlib
import time
def m005_add_content_blob(db):
db["embeddings"].add_column("content_blob", bytes)
db["embeddings"].transform(
column_order=("collection_id", "id", "embedding", "content", "content_blob")
) | null |
8,653 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | null |
8,654 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Access large language models from the command-line Documentation: https://llm.datasette.io/ To get started, obtain an OpenAI key and set it like this: \b $ llm keys set openai Enter key: ... Then execute a prompt like this: llm 'Five outrageous names for a pet pelican' |
8,655 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Hold an ongoing chat with a model. |
8,656 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | List names of all stored keys |
8,657 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Output the path to the keys.json file |
8,658 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Save a key in the keys.json file Example usage: \b $ llm keys set openai Enter key: ... |
8,659 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Tools for exploring logged prompts and responses |
8,660 | import click
from click_default_group import DefaultGroup
from dataclasses import asdict
import io
import json
from llm import (
Collection,
Conversation,
Response,
Template,
UnknownModelError,
encode,
get_embedding_models_with_aliases,
get_embedding_model_aliases,
get_embedding_mode... | Output the path to the logs.db file |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.