repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
drizzlepac | drizzlepac-master/drizzlepac/haputils/comparison_utils.py | #!/usr/bin/env python
"""A collection of functions that assist with sourcelist comparison"""
# Standard library imports
import os
import sys
# Related third party imports
from astropy.table import Table
import numpy as np
from PyPDF2 import PdfFileMerger
# Local application imports
from drizzlepac.haputils import st... | 19,960 | 42.488017 | 187 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/hla_flag_filter_HLAClassic.py | #!/usr/bin/env python
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 ai :
"""Identify and flag sources as either stellar sources, extended sources or anomalous sources
Anomalous sources fall into several categories:
- Saturated sources: the pixel values in the cores of these sources are maxed out at the detect... | 146,634 | 44.411892 | 278 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/hapcut_utils.py | """The module is a high-level interface to astrocut for use with HAP SVM and MVM files."""
from astrocut import fits_cut
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from astropy.table import Table, vstack, unique
from astropy.units.quantity import Quantity
from a... | 33,494 | 45.97756 | 138 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/background_median.py | """
Computes MMM statistics within photutils apertures.
The functions in this script enable the computation of statistics
within a PhotUtils aperture, which is currently not directly
implemented in PhotUtils itself. This code is meant to be
imported into other code, and then be usable as a single line to
return all t... | 4,670 | 30.14 | 153 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/photometry_tools.py | """
Tools for aperture photometry with non native bg/error methods
This function serves to ease the computation of photometric magnitudes
and errors using PhotUtils by replicating DAOPHOT's photometry and
error methods. The formula for DAOPHOT's error is:
err = sqrt (Poisson_noise / epadu + area * stdev**2 + area**2... | 8,929 | 35.900826 | 147 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/product.py | """ Definition of Super and Subclasses for the mosaic output image_list
Classes which define the total ("white light" image), filter, and exposure
drizzle products.
These products represent different levels of processing with the levels noted in the
'HAPLEVEL' keyword. The 'HAPLEVEL' values are:
... | 61,409 | 46.311248 | 228 | py |
drizzlepac | drizzlepac-master/drizzlepac/haputils/diagnostic_json_harvester.py | #!/usr/bin/env python
"""This script 'harvests' information stored in the .json files produced by
drizzlepac/haputils/svm_quality_analysis.py and stores it as a Pandas DataFrame"""
# Standard library imports
import argparse
import collections
import glob
import os
import pdb
import sys
# Related third party imports
... | 19,868 | 47.460976 | 166 | py |
GNNs-for-NLP | GNNs-for-NLP-master/pytorch_gcn.py | from utils import *
import os.path as osp
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid
import torch_geometric.transforms as T
from torch_geometric.nn import GCNConv
class KipfGCN(torch.nn.Module):
def __init__(self, data, num_class, params):
super(KipfGCN, self).__ini... | 7,611 | 29.448 | 139 | py |
GNNs-for-NLP | GNNs-for-NLP-master/tf_gcn.py | from utils import *
import tensorflow as tf
class KipfGCN(object):
def load_data(self):
"""
Reads the data from pickle file
Parameters
----------
self.p.dataset: The path of the dataset to be loaded
Returns
-------
self.X: Input Node features
self.A: Adjacency matrix
self.num_nodes: Total nod... | 11,895 | 29.739018 | 139 | py |
GNNs-for-NLP | GNNs-for-NLP-master/utils.py | import os, sys, time, json, pickle as pkl, argparse
import logging, logging.config
import networkx as nx
from pprint import pprint
import numpy as np, scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
def set_gpu(gpus):
"""
Sets the GPU to be used for the run
Parameters
----------
gpus: ... | 7,931 | 33.337662 | 112 | py |
cryptorandom | cryptorandom-main/setup.py | import sys
from setuptools import setup
if sys.version_info[:2] < (3, 7):
error = (
"cryptorandom 0.3+ requires Python 3.7 or later (%d.%d detected). \n"
% sys.version_info[:2]
)
sys.stderr.write(error + "\n")
sys.exit(1)
DISTNAME = 'cryptorandom'
DESCRIPTION = 'Pseudorandom number g... | 2,314 | 29.064935 | 100 | py |
cryptorandom | cryptorandom-main/cryptorandom/sample.py | """
Sampling with or without weights, with or without replacement.
"""
import numpy as np
import math
from .cryptorandom import SHA256
def get_prng(seed=None):
"""Turn seed into a PRNG instance
Parameters
----------
seed : {None, int, object}
If seed is None, return a randomly seeded instance... | 20,711 | 32.787928 | 104 | py |
cryptorandom | cryptorandom-main/cryptorandom/__init__.py | """
cryptorandom
============
cryptorandom is a Python package providing pseudorandom number generators and
random sampling using cryptographic hash functions. The prototype generator is
built on SHA-256.
See https://statlab.github.io/cryptorandom/ for complete documentation.
"""
__version__ = "0.4rc1.dev0"
from cr... | 340 | 21.733333 | 78 | py |
cryptorandom | cryptorandom-main/cryptorandom/cryptorandom.py | """
SHA-256 PRNG prototype in Python
"""
import numpy as np
import sys
import struct
# Import base class for PRNGs
import random
# Import library of cryptographic hash functions
import hashlib
# Define useful constants
BPF = 53 # Number of bits in a float
RECIP_BPF = 2**-BPF
HASHLEN = 256 # Number of bits in a... | 10,999 | 31.448378 | 98 | py |
cryptorandom | cryptorandom-main/cryptorandom/tests/test_cryptorandom.py | """Unit tests for cryptorandom PRNG"""
import numpy as np
from ..cryptorandom import SHA256, int_from_hash
def test_SHA256():
"""
Test that SHA256 prng is instantiated correctly
"""
r = SHA256(5)
assert repr(r) == 'SHA256 PRNG. seed: 5 counter: 0 randbits_remaining: 0'
assert str(r) == 'SHA256... | 3,285 | 29.425926 | 100 | py |
cryptorandom | cryptorandom-main/cryptorandom/tests/__init__.py | 0 | 0 | 0 | py | |
cryptorandom | cryptorandom-main/cryptorandom/tests/test_sample.py | """Unit tests for cryptorandom sampling functions."""
import pytest
import numpy as np
from ..sample import *
class fake_generator():
"""
This generator just cycles through the numbers 0,...,9.
"""
def __init__(self):
self.counter = 0
def next(self):
"""
Get the next numb... | 8,994 | 25.850746 | 90 | py |
cryptorandom | cryptorandom-main/doc/conf.py | #
# cryptorandom documentation build configuration file, created by
# sphinx-quickstart on Fri Oct 21 12:13:15 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration va... | 9,156 | 31.017483 | 79 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/run_evaluation.py | """
The evaluation entry point for DeeperForensics Challenge.
It will be the entrypoint for the evaluation docker once built.
Basically It downloads a list of videos and run the detector on each video.
Then the runtime output will be reported to the evaluation system.
The participants are expected to implement a Deep... | 3,069 | 35.547619 | 137 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/local_test.py | """
This script provides a local test routine so you can verify the algorithm works before pushing it to evaluation.
It runs your detector on several local videos and verify whether they have obvious issues, e.g:
- Fail to start
- Wrong output format
It also prints out the runtime for the algorithms for your ... | 3,044 | 34 | 137 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/dataset/dataset.py | import numpy as np
import os
import time
import sys
from tqdm import tqdm
import cv2
import torch
from torch.utils.data import Dataset, DataLoader
from albumentations.pytorch import ToTensor, ToTensorV2
from albumentations import (
Compose, HorizontalFlip, CLAHE, HueSaturationValue, Normalize, RandomBrightnessContr... | 11,928 | 38.369637 | 139 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/dataset/analyze.py | import numpy as np
import json
from matplotlib import pyplot as plt
if __name__ == '__main__':
with open('submit.json', 'r') as f:
data = json.load(f)
print(len(data))
prods = []
for i, k in enumerate(data):
print(i, k, data[k]['prob'])
prods.append(data[k]['prob'])
plt.his... | 348 | 20.8125 | 39 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/dataset/distortions.py | import math
import numpy as np
import argparse
import copy
import os
import random
import cv2
from tqdm import tqdm
def bgr2ycbcr(img_bgr):
img_bgr = img_bgr.astype(np.float32)
img_ycrcb = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2YCR_CB)
img_ycbcr = img_ycrcb[:, :, (0, 2, 1)].astype(np.float32)
# to [16/... | 10,032 | 30.649842 | 79 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/train/train_add_data_my_aug.py | import sys
sys.path.append('..')
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import *
import time
from model.models import get_efficientnet
from dataset.dataset import DeeperForensicsDataset, get_train_transforms, get_valid_transfor... | 12,235 | 51.741379 | 134 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/train/train_add_data.py | import sys
sys.path.append('..')
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
import time
from model.models import get_efficientnet
from dataset.dataset import DeeperForensicsDataset, get_train_transforms, get_valid... | 11,868 | 50.829694 | 134 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/train/train.py | import sys
sys.path.append('..')
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import *
import time
from model.models import get_efficientnet
from dataset.dataset import DeeperForensicsDataset, get_train_transforms, get_valid_transfor... | 7,130 | 38.181319 | 111 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/loss/losses.py | import torch
import torch.nn as nn
class LabelSmoothing(nn.Module):
def __init__(self, smoothing=0.05):
super(LabelSmoothing, self).__init__()
self.confidence = 1.0 - smoothing
self.smoothing = smoothing
def forward(self, x, target):
if self.training:
x = x.float()
... | 743 | 27.615385 | 76 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/utils/utils.py | import tensorboardX
from sklearn.metrics import log_loss, accuracy_score, precision_score, average_precision_score, roc_auc_score, recall_score
import torch
class Logger(object):
def __init__(self, model_name, header):
self.header = header
self.writer = tensorboardX.SummaryWriter(model_name)
d... | 1,368 | 31.595238 | 123 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/data/detect_face.py | """ Tensorflow implementation of the face detection / alignment algorithm found at
https://github.com/kpzhang93/MTCNN_face_detection_alignment
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... | 31,714 | 39.556266 | 150 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/data/generate_face.py | import numpy as np
import cv2
import os
import detect_face
import shutil
import tensorflow as tf
from tqdm import tqdm
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
def get_boundingbox(bb, width, height, scale=1.3, minsize=None):
"""
Expects a dlib face to generate a quadratic bounding box.
:param fa... | 9,042 | 38.837004 | 111 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/data/generate_frame.py | import numpy as np
import cv2
import os
import shutil
from tqdm import tqdm
def extract_frames(videos_path, frame_subsample_count=30, output_path=None):
reader = cv2.VideoCapture(videos_path)
# fps = video.get(cv2.CAP_PROP_FPS)
frame_num = 0
while reader.isOpened():
success, whole_image = reade... | 3,763 | 34.17757 | 88 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/data/__init__.py | 0 | 0 | 0 | py | |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/model/face_detector.py | import sys
sys.path.append('..')
import cv2
from PIL import Image
import numpy as np
def get_boundingbox(box, width, height, scale=1.2, minsize=None):
"""
Expects a dlib face to generate a quadratic bounding box.
:param face: dlib face class
:param width: frame width
:param height: frame height
... | 2,200 | 27.960526 | 81 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/model/models.py | import torch
import pretrainedmodels
import torch.nn as nn
from torch.nn import init
import torchvision
from efficientnet_pytorch import EfficientNet
import torch.nn.functional as F
import numpy as np
import math
def get_efficientnet(model_name='efficientnet-b0', num_classes=2, pretrained=True):
if pretrained:
... | 927 | 24.777778 | 107 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/model/toy_predict.py | import sys
sys.path.append('..')
from eval_kit.detector import DeeperForensicsDetector
from model.models import get_efficientnet
import torch
import time
import glob
from PIL import Image
import torchvision.transforms as transforms
from facenet_pytorch import MTCNN, extract_face
import torch.nn as nn
from model.face_... | 11,159 | 34.884244 | 113 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/eval_kit/client.py | import boto3
import json
import os
import time
import sys
import logging
import zipfile
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
from io import BytesIO
from eval_kit.extract_frames import extract_frames
# EVALUATION SYSTEM SETTINGS
# DON'T CHANGE ANY C... | 5,846 | 35.31677 | 137 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/eval_kit/detector.py | from abc import ABC, abstractmethod
class DeeperForensicsDetector(ABC):
def __init__(self):
"""
Participants may define their own initialization process.
During this process you can set up your network.
"""
@abstractmethod
def predict(self, video_frames):
"""
... | 655 | 28.818182 | 121 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/eval_kit/extract_frames.py | import numpy as np
import cv2
def extract_frames(video_path, n_frames=15):
"""
Extract frames from a video. You can use either provided method here or implement your own method.
params:
- video_local_path (str): the path of video.
return:
- frames (list): a list containing frames extra... | 1,502 | 33.159091 | 118 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/eval_kit/client_dev.py | import boto3
import json
import os
import time
import sys
import logging
import zipfile
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
from io import BytesIO
from eval_kit.extract_frames import extract_frames
# EVALUATION SYSTEM SETTINGS
# DON'T CHANGE ANY C... | 5,849 | 34.240964 | 137 | py |
DeeperForensicsChallengeSolution | DeeperForensicsChallengeSolution-master/eval_kit/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/scripts/onsets_converter.py | from pathlib import Path
from notes_generator.constants import AppName
from notes_generator.preprocessing.onset_converter import main as convert
def main(app_name: str, data_path: str, save_path: str):
if app_name == "stepmania":
convert(data_path, save_path, AppName.STEPMANIA)
elif app_name == "step... | 1,021 | 30.9375 | 88 | py |
AAAI-23.6040 | AAAI-23.6040-master/scripts/prediction_stepmania.py | import argparse
import json
import logging
import tempfile
from ast import literal_eval
from logging import getLogger
from pathlib import Path
from typing import Dict, List, Tuple
import numpy as np
import pandas as pd
import torch
from notes_generator.constants import ConvStackType, NMELS
from notes_generator.models... | 4,249 | 28.929577 | 84 | py |
AAAI-23.6040 | AAAI-23.6040-master/scripts/mel_convert.py | from ast import literal_eval
from pathlib import Path
import click
import pandas as pd
from notes_generator.preprocessing import mel
@click.group()
def cmd():
pass
root = Path(__file__).parent.parent
@cmd.command("single")
@click.option("--mel_save_dir", type=Path, default=root / "data/mel_log")
@click.opti... | 2,273 | 25.137931 | 85 | py |
AAAI-23.6040 | AAAI-23.6040-master/scripts/model_test.py | import argparse
import os
from datetime import datetime
from pathlib import Path
from torch.utils.data.dataloader import DataLoader
from notes_generator.constants import *
from notes_generator.models.onsets import SimpleOnsets
from notes_generator.training.evaluate import evaluate_test
from notes_generator.training.l... | 5,789 | 30.639344 | 118 | py |
AAAI-23.6040 | AAAI-23.6040-master/scripts/onsets_train.py | import argparse
import logging
from collections import OrderedDict
from datetime import datetime
from pathlib import Path
import mlflow
import torch
from torch.optim.lr_scheduler import CosineAnnealingLR, CyclicLR
from torch.utils.data.dataloader import DataLoader
from torch.utils.tensorboard import SummaryWriter
fro... | 8,247 | 39.431373 | 99 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/constants.py | import enum
from typing import List, NamedTuple, Optional
##################
# common settings
##################
FRAME = 32
SAMPLE_RATE = 16000
HOP_LENGTH = 512
NMELS = 229
NOTES_COUNT = 12
MAX_THRESHOLD = 0.7
class AppName(enum.Enum):
STEPMANIA_F = "STEPMANIA_F"
STEPMANIA_I = "STEPMANIA_I"
STEPMANIA =... | 3,628 | 18 | 89 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/create_charts.py | from functools import reduce
import dill
from chart import SymbolicChart, OnsetChart
def create_onset_charts(meta, song_features, frame_rate):
charts = []
for raw_chart in meta['charts']:
metadata = (
raw_chart['difficulty_coarse'], raw_chart['difficulty_fine'], raw_chart['type'], raw_chart[... | 4,302 | 34.561983 | 117 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/beatcalc.py | import numpy as np
_EPSILON = 1e-6
class BeatCalc(object):
# for simplicity, we will represent a "stop" as an impossibly sharp tempo change
def __init__(self, offset, beat_bpm, beat_stop):
# ensure all beat markers are strictly increasing
assert beat_bpm[0][0] == 0.0
beat_last = -1.0
... | 3,000 | 33.102273 | 93 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/sym_net.py | import math
import random
from functools import reduce
import numpy as np
import tensorflow as tf
from util import np_pad
dtype = tf.float32
np_dtype = dtype.as_numpy_dtype
# https://github.com/sherjilozair/char-rnn-tensorflow/blob/master/model.py
class SymNet:
def __init__(self,
mode,
... | 25,581 | 47.450758 | 127 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/onset_train.py | from collections import defaultdict
try:
import cPickle as pickle
except:
import pickle
import os
import time
import tensorflow as tf
from sklearn.metrics import roc_curve, precision_recall_curve, auc, accuracy_score
from onset_net import OnsetNet
from util import *
# Data
tf.app.flags.DEFINE_string('train_... | 35,722 | 50.69754 | 126 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/dt_feats.py | import numpy as np
if __name__ == '__main__':
import argparse
try:
import cPickle as pickle
except:
import pickle
import glob
import os
parser = argparse.ArgumentParser()
parser.add_argument('in_dir', type=str, help='')
parser.add_argument('out_dir', type=str, help=''... | 1,432 | 29.489362 | 84 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/ngram.py | import random
class NgramSequence:
def __init__(self, chart_notes):
self.sequence = [sym for _, _, _, sym in chart_notes]
def get_ngrams(self, k, pre=True, post=True):
prepend = []
if pre:
prepend = ['<pre{}>'.format(i) for i in reversed(range(k - 1))]
append = []... | 5,944 | 33.766082 | 116 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/onset_net.py | import random
from functools import reduce
import numpy as np
import tensorflow as tf
dtype = tf.float32
np_dtype = dtype.as_numpy_dtype
class OnsetNet:
def __init__(self,
mode,
batch_size,
audio_context_radius,
audio_nbands,
a... | 19,839 | 45.4637 | 120 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/sym_train.py | from collections import defaultdict
try:
import cPickle as pickle
except:
import pickle
import os
import time
import tensorflow as tf
from sym_net import SymNet
from util import *
# Data
tf.app.flags.DEFINE_string('train_txt_fp', '', 'Training dataset txt file with a list of pickled song files')
tf.app.flag... | 28,103 | 50.191257 | 138 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/util.py | try:
import cPickle as pickle
except:
import pickle
import numpy as np
from scipy.signal import argrelextrema
def load_id_dict(id_dict_fp):
with open(id_dict_fp, 'r') as f:
id_dict = {k: int(i) for k, i in [x.split(',') for x in f.read().splitlines()]}
if '' in id_dict:
id_dic... | 5,710 | 32.011561 | 107 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/gen_labels.py | import itertools
import sys
if __name__ == '__main__':
narrows, chars = sys.argv[1:3]
perms = []
for perm in itertools.product(chars, repeat=int(narrows)):
perms.append(''.join([str(x) for x in perm]))
with open('labels_{}_{}.txt'.format(narrows, chars), 'w') as f:
f.write('\n'.join(per... | 325 | 28.636364 | 67 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/extract_feats.py | import time
import numpy as np
from essentia.standard import MonoLoader, FrameGenerator, Windowing, Spectrum, MelBands
def create_analyzers(fs=44100.0,
nhop=512,
nffts=[1024, 2048, 4096],
mel_nband=80,
mel_freqlo=27.5,
... | 3,917 | 33.982143 | 112 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/onset_extract.py | try:
import cPickle as pickle
except:
import pickle
import os
import tensorflow as tf
from onset_cnn import OnsetCNN
from tqdm import tqdm
from util import *
tf.app.flags.DEFINE_string('data_txt_fp', '', 'Training dataset txt file with a list of pickled song files')
tf.app.flags.DEFINE_string('feats_dir', ''... | 3,591 | 37.623656 | 112 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/extract_feats_mp.py | import argparse
import json
import multiprocessing
import os
import time
from multiprocessing import Process
import numpy as np
from essentia.standard import MonoLoader, FrameGenerator, Windowing, Spectrum, MelBands
try:
import cPickle as pickle
except:
import pickle
def create_analyzers(fs=44100.0,
... | 5,110 | 34.493056 | 112 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/learn/chart.py | """Class managing a Stepmania "chart"
'Stepfiles' for Stepmania are organized into 'charts': lists of annotations for by an annotator for a song with some difficulty. Many charts can point to one song so we do not want to store song features for every chart. Instead, we have this helper class that will point to song f... | 21,112 | 45.199125 | 443 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/preview_sm.py | import json
import sys
_TEMPL = """\
#TITLE:{title};
#ARTIST:{artist};
#MUSIC:{music_fp};
#OFFSET:0.0;
#BPMS:0.0={bpm};
#STOPS:;
{charts}\
"""
_CHART_TEMPL = """\
#NOTES:
{ctype}:
{cversion}:
{ccoarse}:
{cfine}:
0.500,0.500,0.500,0.500,0.500:
{measures};\
"""
def meta_to_sm(meta):
subdiv = 6... | 1,948 | 23.987179 | 94 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/constants.py | FRAME = 32
SAMPLE_RATE = 16000
HOP_LENGTH = 512
NMELS = 229
NOTES_COUNT = 12
MAX_THRESHOLD = 0.7
| 97 | 13 | 19 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/extract_json.py | import glob
import logging as smlog
import os
import traceback
from smdataset.abstime import calc_note_beats_and_abs_times
from smdataset.parse import parse_sm_txt
_ATTR_REQUIRED = ['offset', 'bpms', 'notes']
if __name__ == '__main__':
import argparse
from collections import OrderedDict
import json
... | 5,882 | 38.75 | 113 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/analyze_json.py | from functools import reduce
if __name__ == '__main__':
import argparse
from collections import Counter, defaultdict
import json
parser = argparse.ArgumentParser()
parser.add_argument('dataset_fps', type=str, nargs='+', help='List of dataset filepaths to analyze')
parser.add_argument('--diff',... | 4,576 | 39.504425 | 115 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/extract_json_ntg.py | import glob
import logging as smlog
import os
import traceback
from pathlib import Path
from smdataset.abstime import calc_bpm_info, calc_note_beats_and_abs_times
from smdataset.parse import extract_time_signature, parse_sm_txt
_ATTR_REQUIRED = ['offset', 'bpms', 'notes']
if __name__ == '__main__':
import argpa... | 6,659 | 39.609756 | 113 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/convert_mel.py | """メルスペクトラムデータ作成
"""
import json
import os
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
from typing import List, Optional
import librosa
import numpy as np
import pandas as pd
from constants import *
from dataset.smdataset.parse import extract_time_signature
def _format(d):
if "."... | 7,876 | 35.637209 | 119 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/filter_json.py | from functools import reduce
if __name__ == '__main__':
import argparse
import copy
import json
import os
from util import get_subdirs
parser = argparse.ArgumentParser()
parser.add_argument('json_in_dir', type=str, help='Input JSON directory')
parser.add_argument('json_out_dir', type=s... | 11,216 | 47.141631 | 118 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/create_notes_data.py | import argparse
import json
import os
import shutil
from collections import OrderedDict
from operator import itemgetter
import pandas as pd
difficulty_id_map = {
"Beginner": 10,
"Easy": 20,
"Medium": 30,
"Hard": 40,
"Challenge": 50,
}
package_ids = {
"fraxtil/Fraxtil_sArrowArrangements": 1,
... | 5,446 | 37.359155 | 95 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/preview_wav.py | import math
import numpy as np
from scipy.io.wavfile import write as wavwrite
from scipy.signal import fftconvolve
def _wav_write(wav_fp, fs, wav_f, normalize=False):
if normalize:
wav_f_max = wav_f.max()
if wav_f_max != 0.0:
wav_f /= wav_f.max()
wav_f = np.clip(wav_f, -1.0, 1.0)
... | 2,789 | 32.214286 | 105 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/util.py | import os
def ez_name(x):
x = ''.join(x.strip().split())
x_clean = []
for char in x:
if char.isalnum():
x_clean.append(char)
else:
x_clean.append('_')
return ''.join(x_clean)
def get_subdirs(root, choose=False):
subdir_names = sorted(filter(lambda x: os.pa... | 661 | 27.782609 | 99 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/dataset_json.py | if __name__ == '__main__':
import argparse
import os
import random
from util import get_subdirs
parser = argparse.ArgumentParser()
parser.add_argument('json_dir', type=str, help='Input JSON dir')
parser.add_argument('--dataset_dir', type=str, help='If specified, use different output dir oth... | 2,622 | 38.149254 | 118 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/smdataset/abstime.py | import pandas as pd
_EPSILON = 1e-6
def bpm_to_spb(bpm):
return 60.0 / bpm
def calc_segment_lengths(bpms):
assert len(bpms) > 0
segment_lengths = []
for i in range(len(bpms) - 1):
spb = bpm_to_spb(bpms[i][1])
segment_lengths.append(spb * (bpms[i + 1][0] - bpms[i][0]))
return seg... | 4,321 | 30.779412 | 95 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/smdataset/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/dataset/smdataset/parse.py | import logging
import re
parlog = logging
VALID_PULSES = set([4, 8, 12, 16, 24, 32, 48, 64, 96, 192])
int_parser = lambda x: int(x.strip()) if x.strip() else None
bool_parser = lambda x: True if x.strip() == 'YES' else False
str_parser = lambda x: x.strip() if x.strip() else None
float_parser = lambda x: float(x.str... | 7,233 | 31.439462 | 116 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/infer/sym_net.py | import math
import random
from functools import reduce
import numpy as np
import tensorflow as tf
from util import np_pad
dtype = tf.float32
np_dtype = dtype.as_numpy_dtype
# https://github.com/sherjilozair/char-rnn-tensorflow/blob/master/model.py
class SymNet:
def __init__(self,
mode,
... | 25,556 | 47.403409 | 127 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/infer/onset_net.py | import random
from functools import reduce
import numpy as np
import tensorflow as tf
dtype = tf.float32
np_dtype = dtype.as_numpy_dtype
class OnsetNet:
def __init__(self,
mode,
batch_size,
audio_context_radius,
audio_nbands,
a... | 19,834 | 45.451991 | 120 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/infer/ddc_server.py | import shutil
import numpy as np
import tensorflow as tf
from essentia.standard import MetadataReader
from scipy.signal import argrelextrema
assert tf.__version__ == '0.12.1'
from onset_net import OnsetNet
from sym_net import SymNet
from util import make_onset_feature_context
from extract_feats import extract_mel_fe... | 13,634 | 31.234043 | 120 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/infer/util.py | import cPickle as pickle
import numpy as np
from scipy.signal import argrelextrema
def load_id_dict(id_dict_fp):
with open(id_dict_fp, 'r') as f:
id_dict = {k: int(i) for k, i in [x.split(',') for x in f.read().splitlines()]}
if '' in id_dict:
id_dict[None] = id_dict['']
d... | 5,675 | 32.388235 | 107 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/ddc/infer/extract_feats.py | import numpy as np
from essentia.standard import MonoLoader, FrameGenerator, Windowing, Spectrum, MelBands
def create_analyzers(fs=44100.0,
nhop=512,
nffts=[1024, 2048, 4096],
mel_nband=80,
mel_freqlo=27.5,
mel_fr... | 3,750 | 35.067308 | 112 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/evaluate.py | import sys
from collections import defaultdict
from typing import List, Type
import numpy as np
import torch
from mir_eval.onset import f_measure as evaluate_onset
from mir_eval.transcription import match_notes, precision_recall_f1_overlap as evaluate_notes
from mir_eval.util import midi_to_hz
from notes_generator.co... | 11,028 | 33.145511 | 94 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/mlflow.py | import argparse
import os
import sys
import traceback
import typing
from pathlib import Path
import mlflow
ArgParserFunc = typing.Callable[[typing.Optional[argparse.ArgumentParser]], argparse.Namespace]
class MlflowRunner:
def __init__(self, fn_args: ArgParserFunc):
self.fn_args = fn_args
self.a... | 1,787 | 32.111111 | 95 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/model_tester.py | import csv
import os
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List, TextIO, Type, Union
import mlflow
import torch
import torch.multiprocessing as mp
import yaml
from torch import nn
from torch.utils.data.dataloader import DataLoader
from notes_generator.constants import *
LoaderC... | 16,385 | 34.777293 | 124 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/augmenation.py | import math
import typing
from pathlib import Path
import numpy as np
import torch
import torch.nn.functional as F
import torchaudio.functional as AF
import torchaudio.transforms as T
import yaml
from notes_generator.constants import FRAME, NMELS
Sample = typing.Dict[str, torch.Tensor]
class AugConfig(typing.Named... | 5,571 | 30.480226 | 94 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/loader.py | import json
import random
import warnings
from pathlib import Path
from typing import Dict, Optional, Tuple
import numpy as np
import torch
from notes_generator.constants import *
from notes_generator.models.beats import gen_beats_array
from notes_generator.training import augmenation
def load(base_dir: Path, app_n... | 20,358 | 34.101724 | 100 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/training/train.py | import math
import shutil
import typing
from logging import getLogger
from pathlib import Path
import mlflow
import numpy as np
import torch
from ignite.engine import Engine, Events
from ignite.handlers import Checkpoint, DiskSaver, EarlyStopping, ModelCheckpoint
from ignite.metrics import Average
from torch.nn.utils ... | 9,367 | 36.774194 | 98 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/merge_labels.py | import typing
import torch
def merge_labels(onset_label: torch.Tensor, batch: typing.Dict, scale: float) -> torch.Tensor:
assert "other_conditions" in batch
other_conditions = batch["other_conditions"]
for condition, score in other_conditions.items():
onset_label = torch.max(onset_label, score * ... | 350 | 28.25 | 94 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/fuzzy_label.py | import torch
import torch.nn.functional as F
from notes_generator.models.util import round_decimal
def shift(ar, size, med):
# [0, 0, 0, 1, 0, 0...]
# -> [0, 0, med - 1, 0, mid - 1, 0 ...]
if size > 0:
ar = F.pad(ar[size:], [0, size]) + F.pad(ar[:-size], [size, 0])
ar = ar * (med - size)
... | 2,107 | 27.876712 | 96 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/onsets.py | import typing
import torch
from torch import nn
from torch.nn import functional as F
from notes_generator.constants import *
from notes_generator.layers.base_layers import BiLSTM, get_conv_stack
from notes_generator.models.fuzzy_label import fuzzy_on_batch
from notes_generator.models.merge_labels import merge_labels
... | 9,076 | 33.25283 | 97 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/util.py | import typing
import torch
from torch import nn
def round_decimal(x: torch.Tensor, n_dig: int) -> torch.Tensor:
return torch.round(x * 10**n_dig) / (10**n_dig)
def batch_first(data):
shapes = [-1] + list(data.shape[1:])
return data.reshape(*shapes)
def initialize_weights(m):
if hasattr(m, "weight... | 1,220 | 24.4375 | 95 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/models/beats.py | """The beat guide proposed in our paper
"""
import bisect
import enum
from collections import Counter, defaultdict
from typing import List, Tuple
import numpy as np
from notes_generator.constants import FRAME
class TimeUnit(enum.Enum):
milliseconds = "milliseconds"
frames = "frames"
seconds = "seconds"
... | 9,163 | 29.144737 | 107 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/layers/base_layers.py | import typing
import torch
from torch import nn
from notes_generator.constants import ConvStackType, NMELS
from notes_generator.layers.drop import DropBlock2d
class BiLSTM(nn.Module):
"""Bidirectional LSTM Stack
Parameters
----------
input_features : int
The number of expected features in t... | 14,245 | 33.916667 | 99 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/layers/transformer_layers.py | # https://github.com/novdov/music-transformer/blob/master/music_transformer/modules/attention.py
import math
from typing import List, Optional, Tuple
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MultiheadAttention(nn.Module):
"""Apply multi-head attention to input d... | 26,512 | 34.925474 | 99 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/layers/__init__.py | 0 | 0 | 0 | py | |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/layers/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, d_model: int, dropout: float = 0.1):
super(Attention, self).__init__()
self.d_model = d_model
projection_inout = (self.d_model, self.d_model)
self.query_projection = nn... | 1,484 | 32.75 | 64 | py |
AAAI-23.6040 | AAAI-23.6040-master/notes_generator/layers/drop.py | # https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/layers/drop.py
""" DropBlock, DropPath
PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
Deep Net... | 7,452 | 33.345622 | 108 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.