code stringlengths 17 6.64M |
|---|
def qsub(args):
name = qsub_name_from_args(args)
run(((['qsub', '-cwd', '-S', '/bin/bash', '-j', 'yes', '-o', 'fullsum-scores'] + qsub_opts) + ['-N', name]), input=' '.join(args).encode('utf8'))
|
def get_wers(fn):
wers = {}
for l in open(fn).read().splitlines():
(k, v) = l.split(':', 1)
epoch = r_epoch.match(k).group(1)
wers[int(epoch)] = float(v)
return wers
|
def get_best_epoch(model):
fn = ('scores/%s.recog.%ss.txt' % (model, Settings.recog_metric_name))
assert os.path.exists(fn)
wers = get_wers(fn)
return sorted([(score, ep) for (ep, score) in wers.items()], reverse=(not Settings.recog_score_lower_is_better))[0]
|
def get_train_scores(train_scores_file):
train_scores = {}
for l in open(train_scores_file).read().splitlines():
m = re.match('epoch +([0-9]+) ?(.*): *(.*)', l)
if (not m):
continue
(ep, key, value) = m.groups()
if (('error' in key) or ('score' in key) or (not key))... |
def open_res(fn):
txt = open(fn).read()
txt = re.sub('<.*>', 'None', txt)
txt = re.sub('NumbersDict\\({', '({', txt)
try:
d = eval(txt)
except Exception as exc:
print('Parse exception:', exc)
print('txt:')
print(txt)
raise
assert isinstance(d, dict)
... |
def check_sge_job_exists(args):
name = qsub_name_from_args(args)
from subprocess import Popen, DEVNULL
p = Popen(['qstat', '-j', name], stdout=DEVNULL, stderr=DEVNULL)
ret = p.wait()
return (ret == 0)
|
def main():
argparser = ArgumentParser()
argparser.add_argument('--calc', help='none, local or sge')
args = argparser.parse_args()
for model in models:
(score, ep) = get_best_epoch(model)
print(('model %s, best epoch: %s' % (model, ep)))
print((' WER (dev): %.1f%%' % score))
... |
def cp(src_dir, dst_dir, filename):
src_fn = ((src_dir + '/') + filename)
dst_fn = ((dst_dir + '/') + filename)
assert os.path.exists(src_fn), ('%r does not exist' % src_fn)
try:
os.makedirs(os.path.dirname(dst_fn))
except os.error:
pass
print(('copy (%s) %s' % (dst_dir, filena... |
def main():
for (corpus_src, corpus_dst, experiments) in [(quaero_src_base_dir, quaero_dst_base_dir, quaero_experiments), (swb_src_base_dir, swb_dst_base_dir, swb_experiments)]:
for fn in base_files:
cp(src_dir=corpus_src, dst_dir=corpus_dst, filename=fn)
for setup_name in experiments:... |
def EpochData(learningRate, error):
d = {}
d['learning_rate'] = learningRate
d.update(error)
return d
|
def add_suggest(ep, temp=None, reason=None):
if (ep in ds):
return
ds[ep] = {'epoch': ep, 'temporary_suggestion': temp, 'reason': reason}
|
def main():
argparser = ArgumentParser()
argparser.add_argument('file', help="by Returnn search, in 'py' format")
argparser.add_argument('--out', required=True, help='output filename')
args = argparser.parse_args()
d = eval(open(args.file, 'r').read())
assert isinstance(d, dict)
assert (no... |
def run(args, **kwargs):
import subprocess
kwargs = kwargs.copy()
print(('$ %s' % ' '.join(args)), {k: (v if (k != 'input') else '...') for (k, v) in kwargs.items()})
try:
subprocess.run(args, **kwargs, check=True)
except KeyboardInterrupt:
print('KeyboardInterrupt')
sys.ex... |
def check_recog_bpe_file():
with open(recog_bpe_file, 'w') as f:
f.close()
os.remove(recog_bpe_file)
|
def handle_part(name, keep_existing_ogg):
'\n :param str name: "train", "dev" or "test"\n :param bool keep_existing_ogg:\n '
dirname = ('%s/%s/stm' % (BaseDir, name))
assert os.path.isdir(dirname)
dest_dirname = ('%s/%s' % (DestDir, name))
dest_meta_filename = ('%s/%s.txt' % (DestDir, name))
... |
def print_stats(name):
'\n :param str name: "train", "dev" or "test"\n '
print(('%s:' % name))
filename = ('%s/%s.txt' % (DestDir, name))
assert os.path.isfile(filename)
data = eval(open(filename).read())
assert isinstance(data, list)
print(' num seqs:', len(data))
total_duration = ... |
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('--keep_existing_ogg', action='store_true')
arg_parser.add_argument('--stats_only', action='store_true')
args = arg_parser.parse_args()
assert os.path.isdir(BaseDir)
if (not args.stats_only):
os.makedirs(DestDir, exist_o... |
def parse_stm_seq(line):
'\n :param str line:\n :rtype: StmSeq|None\n '
m = StmSeqRegExp.match(line)
if (not m):
m2 = re.match(StmSeqRegExpPattern[:(- 1)], line)
raise Exception(('line %r, no match to %r. but prefix: %r' % (line, StmSeqRegExp, (line[:m2.end()] if m2 else None))))
(n... |
def read_stm(filename):
'\n :param str filename:\n :rtype: yields StmSeq\n '
lines = open(filename).read().splitlines()
for line in lines:
seq = parse_stm_seq(line)
if (not seq):
continue
(yield seq)
|
def read_stm_dir(dirname):
'\n :param str dirname:\n :rtype: yields StmSeq\n '
files = glob((dirname + '/*.stm'))
assert files, ('no stm files in %r found' % dirname)
for fn in files:
(yield from read_stm(fn))
|
def main():
arg_parser = ArgumentParser()
arg_parser.add_argument('file')
args = arg_parser.parse_args()
assert os.path.exists(args.file)
(name, ext) = os.path.splitext(os.path.basename(args.file))
assert (ext == '.zip')
zip_file = ZipFile(args.file)
data = eval(zip_file.open(('%s.txt'... |
def EpochData(learningRate, error):
d = {}
d['learning_rate'] = learningRate
d.update(error)
return d
|
def add_suggest(ep, temp=None, reason=None):
if (ep in ds):
return
ds[ep] = {'epoch': ep, 'temporary_suggestion': temp, 'reason': reason}
|
def main():
argparser = ArgumentParser()
argparser.add_argument('file', help="by Returnn search, in 'py' format")
argparser.add_argument('--out', required=True, help='output filename')
args = argparser.parse_args()
d = eval(open(args.file, 'r').read())
assert isinstance(d, dict)
assert (no... |
def run(args, **kwargs):
import subprocess
kwargs = kwargs.copy()
print(('$ %s' % ' '.join(args)), {k: (v if (k != 'input') else '...') for (k, v) in kwargs.items()})
try:
subprocess.run(args, **kwargs, check=True)
except KeyboardInterrupt:
print('KeyboardInterrupt')
sys.ex... |
def check_recog_bpe_file():
with open(recog_bpe_file, 'w') as f:
f.close()
os.remove(recog_bpe_file)
|
def main():
with tk.block('data_preparation'):
(bliss_dict, zip_dict, transcription_text_dict) = prepare_data_librispeech()
(bpe_codes, bpe_vocab, num_classes) = build_subwords([bliss_dict['train-clean-100']], num_segments=10000, name='librispeech-100')
(mean, stddev) = get_asr_dataset_stats(zip_d... |
def get_asr_dataset_stats(zip_dataset):
'\n This function computes the global dataset statistics (mean and stddev) on a zip corpus to be used in the\n training dataset parameters of the OggZipDataset\n\n\n :param zip_dataset:\n :return:\n '
config = {'train': {'class': 'OggZipDataset', 'audio': {}, 'targ... |
def train_asr_config(config, name, parameter_dict=None):
'\n This function trains a RETURNN asr model, given the config and parameters\n\n :param config:\n :param name:\n :param parameter_dict:\n :return:\n '
asr_train_job = RETURNNTrainingFromFile(config, parameter_dict=parameter_dict, mem_rqmt=16)
... |
def decode_and_evaluate_asr_config(name, config_file, model_path, epoch, zip_corpus, text, parameter_dict, training_name=None):
'\n This function creates the RETURNN decoding/search job, converts the output into the format for scoring and computes\n the WER score\n\n :param str name: name of the decoding, usua... |
def prepare_data_librispeech():
'\n This function creates the LibriSpeech data in Bliss format and zip format.\n For the evaluation sets, the text is extracted in dictionary form for WER scoring\n\n :return:\n '
dataset_names = ['dev-clean', 'dev-other', 'test-clean', 'test-other', 'train-clean-100', 'tra... |
def build_subwords(bliss_corpora, num_segments, name):
'\n This function creates the subword codes and vocabulary files for a given bliss dataset\n\n :param list bliss_corpora: bliss corpus for subword training\n :param int num_segments: number of bpe merge operations / bpe segments\n :param str name: name of... |
def train_f2l_config(config_file, name, parameter_dict=None):
from recipe.returnn import RETURNNTrainingFromFile
f2l_train = RETURNNTrainingFromFile(config_file, parameter_dict=parameter_dict, mem_rqmt=16)
f2l_train.add_alias(('f2l_training/' + name))
f2l_train.rqmt['time'] = 96
f2l_train.rqmt['cp... |
def convert_with_f2l(config_file, name, model_dir, epoch, features):
from recipe.returnn.forward import RETURNNForwardFromFile
parameter_dict = {'ext_forward': True, 'ext_model': model_dir, 'ext_load_epoch': epoch, 'ext_eval_features': features}
f2l_apply = RETURNNForwardFromFile(config_file, parameter_di... |
def griffin_lim_ogg(linear_hdf, name, iterations=1):
from recipe.tts.toolchain import GriffinLim
gl_job = GriffinLim(linear_hdf, iterations=iterations, sample_rate=16000, window_shift=0.0125, window_size=0.05, preemphasis=0.97)
gl_job.add_alias(('gl_conversion/' + name))
tk.register_output((('generate... |
def process_corpus(bliss_corpus, char_vocab, silence_duration):
'\n process a bliss corpus to be suited for TTS training\n :param self:\n :param bliss_corpus:\n :param name:\n :return:\n '
from recipe.text.bliss import ProcessBlissText
ljs = ProcessBlissText(bliss_corpus, [('end_token', {'token': '~... |
def prepare_ttf_data(bliss_dict):
'\n\n :param dict bliss_dict:\n :return:\n '
from recipe.returnn.vocabulary import BuildCharacterVocabulary
build_char_vocab_job = BuildCharacterVocabulary(uppercase=True)
char_vocab = build_char_vocab_job.out
processed_corpora = {}
processed_zip_corpora = ... |
def get_ttf_dataset_stats(zip_dataset):
config = {'train': {'class': 'OggZipDataset', 'audio': {'feature_options': {'fmin': 60}, 'features': 'db_mel_filterbank', 'num_feature_filters': 80, 'peak_normalization': False, 'preemphasis': 0.97, 'step_len': 0.0125, 'window_len': 0.05}, 'targets': None, 'path': zip_datas... |
def train_ttf_config(config, name, parameter_dict=None):
from recipe.returnn import RETURNNTrainingFromFile
asr_train = RETURNNTrainingFromFile(config, parameter_dict=parameter_dict, mem_rqmt=16)
asr_train.add_alias(('tts_training/' + name))
asr_train.rqmt['time'] = 167
asr_train.rqmt['cpu'] = 8
... |
def generate_speaker_embeddings(config_file, model_dir, epoch, zip_corpus, name, default_parameter_dict=None):
from recipe.returnn.forward import RETURNNForwardFromFile
parameter_dict = {'ext_gen_speakers': True, 'ext_model': model_dir, 'ext_load_epoch': epoch, 'ext_eval_zip': zip_corpus}
parameter_dict.u... |
def decode_with_speaker_embeddings(config_file, model_dir, epoch, zip_corpus, speaker_hdf, name, default_parameter_dict=None, segment_file=None):
from recipe.returnn.forward import RETURNNForwardFromFile
from recipe.tts.toolchain import ConvertFeatures
parameter_dict = {'ext_forward': True, 'ext_model': m... |
def evaluate_tts(ttf_config_file, ttf_model_dir, ttf_epoch, f2l_config_file, f2l_model_dir, f2l_epoch, train_zip_corpus, test_zip_corpus, test_bliss_corpus, test_text, default_parameter_dict, name):
embedding_hdf = generate_speaker_embeddings(ttf_config_file, ttf_model_dir, ttf_epoch, train_zip_corpus, name=name,... |
class BlissToZipDataset(Job):
'\n convert bliss corpus with single segment recordings into the Zip format for RETURNN training\n '
def __init__(self, name, corpus_file, segment_file=None, use_full_seq_name=False, no_audio=False):
'\n\n :param str name:\n :param str|Path corpus_file:\n :par... |
class MergeCorpora(Job):
'\n Merges Bliss Corpora into a single file as subcorpora\n This is preferably done after using corpus compression\n\n :param Iterable[Path] corpora: any iterable of bliss corpora file paths to merge\n :param name: name of the new corpus (subcorpora will keep the original names)\n '
... |
class SegmentCorpus(Job):
def __init__(self, corpus_path, num_segments, use_fullname=False):
self.set_vis_name('Segment Corpus')
self.corpus_path = corpus_path
self.num_segments = num_segments
self.use_fullname = use_fullname
self.segment_files = [self.output_path(('segmen... |
class BlissAddTextFromBliss(Job):
'\n This Job is used to add the text to a bliss corpus containing only audio from another bliss corpus\n containing the same sequences.\n '
def __init__(self, empty_bliss_corpus, bliss_corpus):
self.empty_bliss_corpus = empty_bliss_corpus
self.bliss_corpus... |
class BlissFFMPEGJob(Job):
'\n Changes the speed of all audio files in the corpus (shifting time AND frequency)\n\n '
def __init__(self, corpus_file, ffmpeg_option_string, ffmpeg_binary=None, output_format=None):
self.corpus_file = corpus_file
self.ffmpeg_option_string = ffmpeg_option_strin... |
class BlissRecoverDuration(Job):
def __init__(self, bliss_corpus):
self.bliss_corpus = bliss_corpus
self.out = self.output_path('corpus.xml.gz')
def tasks(self):
(yield Task('run', mini_task=True))
def run(self):
import soundfile
c = corpus.Corpus()
c.loa... |
class LibriSpeechToBliss(Job):
def __init__(self, corpus_path, name):
'\n Generate a bliss xml from the LibriSpeech corpus.\n :param Path corpus_path:\n :param str name:\n '
self.corpus_path = corpus_path
self.name = name
self.out = self.output_path('out.xml.gz')
... |
class NamedEntity():
def __init__(self):
super().__init__()
self.name = None
|
class CorpusSection():
def __init__(self):
super().__init__()
self.speaker_name = None
self.default_speaker = None
self.speakers = collections.OrderedDict()
|
class CorpusParser(sax.handler.ContentHandler):
'\n This classes methods are called by the sax-parser whenever it encounters an event in the xml-file\n (tags/characters/namespaces/...). It uses a stack of elements to remember the part of the corpus that\n is currently beeing read.\n '
def __init__(self, ... |
class Corpus(NamedEntity, CorpusSection):
'\n This class represents a corpus in the Bliss format. It is also used to represent subcorpora when the parent_corpus\n attribute is set. Corpora with include statements can be read but are written back as a single file.\n '
def __init__(self):
super().__... |
class Recording(NamedEntity, CorpusSection):
def __init__(self):
super().__init__()
self.audio = None
self.corpus = None
self.segments = []
def fullname(self):
return ((self.corpus.fullname() + '/') + self.name)
def speaker(self, speaker_name=None):
if (s... |
class Segment(NamedEntity):
def __init__(self):
super().__init__()
self.start = 0.0
self.end = 0.0
self.track = None
self.orth = None
self.speaker_name = None
self.recording = None
def fullname(self):
return ((self.recording.fullname() + '/') +... |
class Speaker(NamedEntity):
def __init__(self):
super().__init__()
self.attribs = {}
def dump(self, out, indentation=''):
out.write(('%s<speaker-description%s>' % (indentation, ((' name="%s"' % self.name) if (self.name is not None) else ''))))
if (len(self.attribs) > 0):
... |
class SegmentMap(object):
def __init__(self):
self.map_entries = []
def load(self, path):
'\n :param str path:\n '
open_fun = (gzip.open if path.endswith('.gz') else open)
with open_fun(path, 'rb') as f:
for (event, elem) in ET.iterparse(f, events=('start',)... |
class SegmentMapItem(object):
def __init__(self):
self.key = None
self.value = None
def dump(self, out):
out.write(('<map-item key="%s" value="%s" />\n' % (self.key, self.value)))
|
def instanciate_vars(o):
if isinstance(o, Variable):
o = o.get()
elif isinstance(o, list):
for k in range(len(o)):
o[k] = instanciate_vars(o[k])
elif isinstance(o, tuple):
o = tuple((instanciate_vars(e) for e in o))
elif isinstance(o, dict):
for k in o:
... |
class RETURNNConfig():
PYTHON_CODE = textwrap.dedent(' #!rnn.py\n\n ${REGULAR_CONFIG}\n\n locals().update(**config)\n\n ${EXTRA_PYTHON_CODE}\n ')
def __init__(self, config, post_config, extra_python_code='', extra_python_hash=None):
... |
class WriteRETURNNConfigJob(Job):
def __init__(self, returnn_config):
assert isinstance(returnn_config, RETURNNConfig)
self.returnn_config = returnn_config
self.returnn_config_file = self.output_path('returnn.config')
def tasks(self):
(yield Task('run', resume='run', mini_tas... |
class ExtractDatasetStats(Job):
def __init__(self, config, returnn_python_exe=RETURNN_PYTHON_EXE, returnn_root=RETURNN_SRC_ROOT):
self.config = RETURNNConfig(config, {})
self.crnn_python_exe = returnn_python_exe
self.crnn_root = returnn_root
self.mean = self.output_var('mean_var')... |
class RETURNNForwardFromFile(RETURNNJob):
def __init__(self, returnn_config_file, parameter_dict, hdf_outputs, time_rqmt=4, mem_rqmt=4, returnn_python_exe=RETURNN_PYTHON_EXE, returnn_root=RETURNN_SRC_ROOT):
super().__init__(parameter_dict, returnn_config_file, returnn_python_exe, returnn_root)
se... |
class RETURNNJob(Job):
'\n Provides common functions for the returnn jobs\n '
def __init__(self, parameter_dict, returnn_config_file, returnn_python_exe, returnn_root):
'\n\n :param dict parameter_dict:\n :param Path returnn_config_file:\n :param Path|str returnn_python_exe:\n :param Pa... |
def main():
argparser = ArgumentParser()
argparser.add_argument('file', help="by Returnn search, in 'py' format")
argparser.add_argument('--out', required=True, help='output filename')
args = argparser.parse_args()
d = eval(open(args.file, 'r').read())
assert isinstance(d, dict)
assert (no... |
class SeqInfo():
__slots__ = ('idx', 'tag', 'orth_raw', 'orth_seq', 'audio_path', 'audio_start', 'audio_end', 'rec_name')
|
def parse_bliss_xml(filename):
'\n This takes e.g. around 5 seconds for the Switchboard 300h train corpus.\n Should be as fast as possible to get a list of the segments.\n All further parsing and loading can then be done in parallel and lazily.\n :param str filename:\n :param boolean use_compressed... |
def main():
argparser = ArgumentParser()
argparser.add_argument('file', help="by Returnn search, in 'py' format, words")
argparser.add_argument('--corpus', required=True, help='Bliss XML corpus')
argparser.add_argument('--out', required=True, help='output CTM filename')
argparser.add_argument('--o... |
class RETURNNSearchFromFile(RETURNNJob):
'\n Run a returnn search directly from a prepared config file.\n\n Currently it requires "ext_model" and "ext_load_epoch" to be set.\n '
def __init__(self, returnn_config_file, parameter_dict, output_mode='py', time_rqmt=4, mem_rqmt=4, returnn_python_exe=RETURNN_PY... |
class GetBestEpoch(Job):
def __init__(self, model_dir, learning_rates, index=0, key=None):
self.model_dir = model_dir
self.learning_rates = learning_rates
self.index = index
self.out_var = self.output_var('epoch')
self.key = key
assert ((index >= 0) and isinstance(... |
class SearchBPEtoWords(Job):
'\n Converts BPE Search output from returnn into words\n :param search_output:\n :param script:\n '
def __init__(self, search_output_bpe, script=Path('scripts/search-bpe-to-words.py')):
self.search_output_bpe = search_output_bpe
self.script = script
se... |
class SearchWordsToCTM(Job):
'\n Converts search output (in words) from returnn into a ctm file\n :param search_output:\n :param script:\n '
__sis_hash_exclude__ = {'only_segment_name': False}
def __init__(self, search_output_words, corpus, only_segment_name=False, script=Path('scripts/search-words-t... |
class ReturnnScore(Job):
def __init__(self, hypothesis, reference, returnn_python_exe=RETURNN_PYTHON_EXE, returnn_root=RETURNN_SRC_ROOT):
self.set_attrs(locals())
self.out = self.output_path('wer')
def run(self):
call = [str(self.returnn_python_exe), os.path.join(str(self.returnn_roo... |
class RETURNNModel():
def __init__(self, crnn_config_file, model, epoch):
self.crnn_config_file = crnn_config_file
self.model = model
self.epoch = epoch
|
class RETURNNTrainingFromFile(RETURNNJob):
'\n The Job allows to directly execute returnn config files. The config files have to have the line\n ext_model = config.value("ext_model", None) and set model = ext_model to correctly set the model path\n\n If the learning rate file should be available, add\n ext_le... |
class BuildCharacterVocabulary(Job):
'\n Build a character vocbulary for Returnn\n '
def __init__(self, languages=['en'], uppercase=False):
'\n\n :param list[str] languages:\n '
self.languages = languages
self.uppercase = uppercase
self.out = self.output_path('orth_voc... |
class Concatenate(Job):
' Concatenate all given input files '
def __init__(self, inputs):
assert inputs
if isinstance(inputs, set):
inputs = list(inputs)
inputs.sort(key=(lambda x: str(x)))
assert isinstance(inputs, list)
if (len(inputs) == 1):
... |
class PP_Module(object):
def __init__(self, **kwargs):
pass
def process(self, orth: str):
return orth
|
class Lowercase(PP_Module):
def process(self, orth: str):
return orth.lower()
|
class Uppercase(PP_Module):
def process(self, orth: str):
return orth.upper()
|
class End_Token(PP_Module):
def __init__(self, token):
super().__init__()
self.token = token
assert ((len(token) == 1) and isinstance(token, str))
def process(self, orth: str):
return (orth + self.token)
|
class RemoveSymbol(PP_Module):
def __init__(self, symbol):
super().__init__()
self.symbol = symbol
assert (len(symbol) == 1)
def process(self, orth: str):
return orth.replace(self.symbol, '')
|
class RemovePunctuation(PP_Module):
def __init__(self):
super().__init__()
self.converter = str.maketrans('', '', string.punctuation)
def process(self, orth: str):
return orth.translate(self.converter)
|
class RegexReplace(PP_Module):
def __init__(self, search, replace):
super().__init__()
self.regex_search = search
self.regex_replace = replace
def process(self, orth: str):
return re.sub(self.regex_search, self.regex_replace, orth)
|
class ProcessBlissText(Job):
'\n Provides a set of processing modules to process the orth tags in a bliss corpus file\n '
def __init__(self, corpus, process_list, vocabulary=None):
'\n\n :param Path corpus: path to the corpus file\n :param list[(str, dict)] process_list: list of module tuples... |
class BlissExtractRawText(Job):
'\n Extract the Text from a Bliss corpus into a raw gziptext file\n '
def __init__(self, corpus, segments=None, segment_key_only=True):
self.corpus_path = corpus
self.out = self.output_path('text.gz')
self.segments_file_path = segments
self.se... |
class BlissExtractTextDictionary(Job):
'\n Extract the Text from a Bliss corpus to fit the "{key: text}" structure\n '
def __init__(self, corpus, segments=None, segment_key_only=True):
'\n\n :param corpus: bliss corpus file\n :param segments: a segment file as optional whitelist\n :param s... |
class CreateSubwordsAndVocab(Job):
def __init__(self, text, num_segments, subword_nmt=SUBWORD_NMT_DIR):
self.text = text
self.num_segments = num_segments
self.subword_nmt = subword_nmt
self.out_bpe = self.output_path('bpe.codes')
self.out_vocab = self.output_path('bpe.voca... |
class DistributeSpeakerEmbeddings(Job):
'\n distribute speaker embeddings contained in an hdf file to a new hdf file with mappings to the given bliss corpus\n '
def __init__(self, bliss_corpus, speaker_embedding_hdf, options=None, use_full_seq_name=False):
self.bliss_corpus = bliss_corpus
s... |
class VerifyCorpus(Job):
'\n verifies the audio files of a bliss corpus by loading it with the soundfile library\n '
def __init__(self, bliss_corpus, channels=1, sample_rate=16000):
self.bliss_corpus = bliss_corpus
self.channels = channels
self.sample_rate = sample_rate
self... |
class ConvertFeatures(Job):
'\n Convert output features of a decoding job that have merged frames to single frames\n '
def __init__(self, stacked_hdf_features, conversion_factor):
'\n\n :param Path stacked_hdf_features: hdf features with stacked frames\n :param int conversion_factor: the numb... |
class GriffinLim(Job):
'\n Run Griffin & Lim algorithm on linear spectogram features with specified audio settings\n '
def __init__(self, linear_features, iterations, sample_rate, window_shift, window_size, preemphasis, file_format='ogg', corpus_format='bliss'):
'\n\n :param linear_features:\n ... |
class MultiPath():
def __init__(self, path_template, hidden_paths, cached=False, path_root=None, hash_overwrite=None):
self.path_template = path_template
self.hidden_paths = hidden_paths
self.cached = cached
self.path_root = path_root
self.hash_overwrite = hash_overwrite
... |
class MultiOutputPath(MultiPath):
def __init__(self, creator, path_template, hidden_paths, cached=False):
super().__init__(os.path.join(creator._sis_path(gs.JOB_OUTPUT), path_template), hidden_paths, cached, gs.BASE_DIR)
|
def write_paths_to_file(file, paths):
with open(tk.uncached_path(file), 'w') as f:
for p in paths:
f.write((tk.uncached_path(p) + '\n'))
|
def zmove(src, target):
src = tk.uncached_path(src)
target = tk.uncached_path(target)
if (not src.endswith('.gz')):
tmp_path = (src + '.gz')
if os.path.exists(tmp_path):
os.unlink(tmp_path)
sp.check_call(['gzip', src])
src += '.gz'
if (not target.endswith('.... |
def delete_if_exists(file):
if os.path.exists(file):
os.remove(file)
|
def delete_if_zero(file):
if (os.path.exists(file) and (os.stat(file).st_size == 0)):
os.remove(file)
|
def backup_if_exists(file):
if os.path.exists(file):
(dir, base) = os.path.split(file)
base = add_suffix(base, '.gz')
idx = 1
while os.path.exists(os.path.join(dir, ('backup.%.4d.%s' % (idx, base)))):
idx += 1
zmove(file, os.path.join(dir, ('backup.%.4d.%s' % (i... |
def remove_suffix(string, suffix):
if string.endswith(suffix):
return string[:(- len(suffix))]
return string
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.