code stringlengths 17 6.64M |
|---|
def get_least_power2_above(x):
return np.power(2, math.ceil(np.log2(x)))
|
class MelspecInversion(nn.Module):
def __init__(self, n_mels: int=128, sample_rate: int=24000, win_length: int=1024, hop_length: int=256):
super().__init__()
self.n_mels = n_mels
self.sample_rate = sample_rate
self.win_length = win_length
self.hop_length = hop_length
... |
@torch.jit.script
def silu(x):
return (x * torch.sigmoid(x))
|
def Conv1d(*args, **kwargs):
layer = nn.Conv1d(*args, **kwargs)
nn.init.kaiming_normal_(layer.weight)
return layer
|
class DiffusionEmbedding(nn.Module):
'Diffusion Timestep Embedding'
def __init__(self, max_steps):
super().__init__()
self.register_buffer('embedding', self._build_embedding(max_steps), persistent=False)
self.projection1 = nn.Linear(128, 512)
self.projection2 = nn.Linear(512, ... |
class SpectrogramUpsampler(nn.Module):
'Convolution-based Upsampler (16x)'
def __init__(self):
super().__init__()
self.conv1 = nn.ConvTranspose2d(1, 1, [3, 32], stride=[1, 16], padding=[1, 8])
self.conv2 = nn.ConvTranspose2d(1, 1, [3, 32], stride=[1, 16], padding=[1, 8])
def forw... |
class ResidualBlock(nn.Module):
'Building Block for Diffusion Model'
def __init__(self, n_mels, residual_channels, dilation):
super().__init__()
self.dilated_conv = Conv1d(residual_channels, (2 * residual_channels), 3, padding=dilation, dilation=dilation)
self.diffusion_projection = n... |
class GomiDiff(nn.Module):
'GomiDiff: Gaudio open mel-spectrogram inversion with diffusion models.\n\n Based on Diffwave (Kong et al. 2020).\n\n Args:\n n_mels (int): number of frequency bins\n residual_layers (int): number of residual layers\n residual_channels (int): dimension of chan... |
class DiffusionWrapper(MelspecInversion):
def __init__(self, in_channels: int, residual_layers: int, residual_channels: int, dilation_cycle_length: int, num_diffusion_steps: int, **mel_config):
super().__init__(n_mels=in_channels, **mel_config)
self.model = GomiDiff(in_channels=in_channels, resid... |
def load_audio(audio_path: Union[(str, bytes, os.PathLike)], sample_rate: int, mono=True, fast_resample=False):
'Load and resample audio file'
if fast_resample:
(audio, orig_sr) = librosa.load(audio_path, sr=None, mono=mono)
audio = librosa.resample(audio, orig_sr=orig_sr, target_sr=sample_rat... |
@torch.no_grad()
def _analysis(model: torch.nn.Module, audio: Union[(np.ndarray, torch.Tensor)], device: torch.device):
'Convert waveform into melspectrogram.'
if isinstance(audio, np.ndarray):
audio = torch.from_numpy(audio).float()
if (audio.ndim < 2):
audio = torch.atleast_2d(audio)
... |
@torch.no_grad()
def _synthesis(model: torch.nn.Module, melspec: torch.Tensor, device: torch.device):
'Convert melspectrogram into waveform.'
if (melspec.ndim < 3):
melspec = torch.atleast_3d(melspec)
if (melspec.device != device):
melspec = melspec.to(device)
recon_audio = model(melsp... |
def analysis_synthesis(model: torch.nn.Module, in_file: Union[(str, bytes, os.PathLike)], out_file: Union[(str, bytes, os.PathLike)], device: torch.device, fast_resample=False):
'Process and save files.'
(_, input_ext) = os.path.splitext(in_file)
(_, output_ext) = os.path.splitext(out_file)
if (input_... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-m', '--model', type=str, default=None, choices=['diffusion', 'gan'], help='Model type to run.')
parser.add_argument('-p', '--model_path', type=str, default='checkpoints/', help='Directory path to model checkpoint.')
parser.add_... |
def process(model, device, input_files, output_files):
model.to(device)
for (in_file, out_file) in zip(input_files, output_files):
analysis_synthesis(model=model, in_file=in_file, out_file=out_file, device=device, fast_resample=(len(input_files) > 1))
|
def main():
args = parse_args()
(args.input_files, args.output_files) = preprocess_inout_files(args.input_files, args.output_files)
if (args.model == 'gan'):
model = models.GomiGAN.from_pretrained(pretrained_model_path='checkpoints/gan_state_dict.pt', **config.GANConfig().__dict__)
elif (args.... |
def device_type(device: Union[(str, int)]):
if (device == 'cpu'):
return device
assert device.isnumeric()
return f'cuda:{device}'
|
def check_paths(input_filelist: List[str], output_filelist: List[str]):
"Check errors and return filelist if no error detected.\n\n This methode checks 3 types of errors:\n (1) Extension\n Check if filelists have proper extensions. The allowed extensions\n are defined as constants... |
def preprocess_inout_files(input_files: List[str], output_files: List[str]):
'Process input and output filelists.\n\n For various types of input / output path arguments, it preprocess paths. For\n input paths, it reads text files containing audio file paths or search\n directories using `glob.glob`. Fo... |
class MinMaxHeap(object):
'\n Implementation of a Min-max heap following Atkinson, Sack, Santoro, and\n Strothotte (1986): https://doi.org/10.1145/6617.6621\n '
def __init__(self, reserve=0):
self.a = ([None] * reserve)
self.size = 0
def __len__(self):
return self.size
... |
def level(i):
return ((i + 1).bit_length() - 1)
|
def trickledown(array, i, size):
if ((level(i) % 2) == 0):
trickledownmin(array, i, size)
else:
trickledownmax(array, i, size)
|
def trickledownmin(array, i, size):
if (size > ((i * 2) + 1)):
m = ((i * 2) + 1)
if ((((i * 2) + 2) < size) and (array[((i * 2) + 2)] < array[m])):
m = ((i * 2) + 2)
child = True
for j in range(((i * 4) + 3), min(((i * 4) + 7), size)):
if (array[j] < array[m... |
def trickledownmax(array, i, size):
if (size > ((i * 2) + 1)):
m = ((i * 2) + 1)
if ((((i * 2) + 2) < size) and (array[((i * 2) + 2)] > array[m])):
m = ((i * 2) + 2)
child = True
for j in range(((i * 4) + 3), min(((i * 4) + 7), size)):
if (array[j] > array[m... |
def bubbleup(array, i):
if ((level(i) % 2) == 0):
if ((i > 0) and (array[i] > array[((i - 1) // 2)])):
(array[i], array[((i - 1) // 2)]) = (array[((i - 1) // 2)], array[i])
bubbleupmax(array, ((i - 1) // 2))
else:
bubbleupmin(array, i)
elif ((i > 0) and (arr... |
def bubbleupmin(array, i):
while (i > 2):
if (array[i] < array[((i - 3) // 4)]):
(array[i], array[((i - 3) // 4)]) = (array[((i - 3) // 4)], array[i])
i = ((i - 3) // 4)
else:
return
|
def bubbleupmax(array, i):
while (i > 2):
if (array[i] > array[((i - 3) // 4)]):
(array[i], array[((i - 3) // 4)]) = (array[((i - 3) // 4)], array[i])
i = ((i - 3) // 4)
else:
return
|
def peekmin(array, size):
assert (size > 0)
return array[0]
|
def peekmax(array, size):
assert (size > 0)
if (size == 1):
return array[0]
elif (size == 2):
return array[1]
else:
return max(array[1], array[2])
|
def removemin(array, size):
assert (size > 0)
elem = array[0]
array[0] = array[(size - 1)]
trickledown(array, 0, (size - 1))
return (elem, (size - 1))
|
def removemax(array, size):
assert (size > 0)
if (size == 1):
return (array[0], (size - 1))
elif (size == 2):
return (array[1], (size - 1))
else:
i = (1 if (array[1] > array[2]) else 2)
elem = array[i]
array[i] = array[(size - 1)]
trickledown(array, i, (... |
def replacemax(array, size, val):
assert (size > 0)
if (size == 1):
array[0] = val
elif (size == 2):
array[1] = val
bubbleup(array, 1)
else:
i = (1 if (array[1] > array[2]) else 2)
array[i] = array[(size - 1)]
trickledown(array, i, size)
array[(s... |
def replacemin(array, size, val):
assert (size > 0)
array[0] = val
trickledown(array, 0, size)
assert minmaxheapproperty(array, len(array))
|
def insert(array, k, size):
array[size] = k
bubbleup(array, size)
|
def minmaxheapproperty(array, size):
for (i, k) in enumerate(array[:size]):
if ((level(i) % 2) == 0):
for j in range(((2 * i) + 1), min(((2 * i) + 3), size)):
if (array[j] < k):
print(array, j, i, array[j], array[i], level(i))
return Fals... |
def test(n):
from random import randint
a = ([(- 1)] * n)
l = []
size = 0
for _ in range(n):
x = randint(0, (5 * n))
insert(a, x, size)
size += 1
l.append(x)
assert minmaxheapproperty(a, size)
assert (size == len(l))
print(a)
while (size > 0):
... |
def test_heap(n):
from random import randint
heap = MinMaxHeap(n)
l = []
for _ in range(n):
x = randint(0, (5 * n))
heap.insert(x)
l.append(x)
assert minmaxheapproperty(heap.a, len(heap))
assert (len(heap) == len(l))
print(heap.a)
while (len(heap) > 0):
... |
class PointerQueue(object):
'\n Implementation of linked list style queue\n '
def __init__(self, initial, reserve=0):
self.queue = SortedDict(zip(initial, range(len(initial))))
self.pointer = initial
self.pointer.extend(([None] * reserve))
def __len__(self):
return ... |
class SGNMTPrompt(Cmd):
def default(self, cmd_args):
'Translate a single sentence.'
decode_utils.do_decode(decoder, outputs, [cmd_args.strip()])
def emptyline(self):
pass
def do_translate(self, cmd_args):
'Translate a single sentence.'
decode_utils.do_decode(deco... |
def base_init(new_args):
'This function should be called before accessing any other\n function in this module. It initializes the `args` variable on \n which all the create_* factory functions rely on as configuration\n object, and it sets up global function pointers and variables for\n basic things l... |
def add_predictor(decoder):
'Adds all enabled predictors to the ``decoder``. This function \n makes heavy use of the global ``args`` which contains the\n SGNMT configuration. Particularly, it reads out ``args.predictors``\n and adds appropriate instances to ``decoder``.\n TODO: Refactor this method as... |
def create_decoder():
'Creates the ``Decoder`` instance. This specifies the search \n strategy used to traverse the space spanned by the predictors. This\n method relies on the global ``args`` variable.\n Returns:\n Decoder. Instance of the search strategy\n '
try:
decoder = decodin... |
def create_output_handlers():
'Creates the output handlers defined in the ``io`` module. \n These handlers create output files in different formats from the\n decoding results.\n \n Args:\n args: Global command line arguments.\n \n Returns:\n list. List of output handlers according... |
def get_sentence_indices(range_param, src_sentences):
"Helper method for ``do_decode`` which returns the indices of the\n sentence to decode\n \n Args:\n range_param (string): ``--range`` parameter from config\n src_sentences (list): A list of strings. The strings are the\n ... |
def _get_text_output_handler(output_handlers):
'Returns the text output handler if in output_handlers, or None.'
for output_handler in output_handlers:
if (isinstance(output_handler, output.TextOutputHandler) or isinstance(output_handler, output.NBestSeparateOutputHandler)):
return output_... |
def _get_score_output_handler(output_handlers):
'Returns the text output handler if in output_handlers, or None.'
for output_handler in output_handlers:
if isinstance(output_handler, output.ScoreOutputHandler):
return output_handler
return None
|
def _postprocess_complete_hypos(hypos):
'This function applies the following operations on the list of\n complete hypotheses returned by the Decoder:\n\n - </s> removal\n - Apply --nbest parameter if necessary\n - Applies combination_scheme on full hypotheses, reorder list\n\n Args:\n hy... |
def _generate_dummy_hypo():
return decoding.core.Hypothesis([utils.UNK_ID], 0.0, [0.0])
|
def do_decode(decoder, output_handlers, src_sentences, trgt_sentences=None, num_log=1):
"This method contains the main decoding loop. It iterates through\n ``src_sentences`` and applies ``decoder.decode()`` to each of them.\n At the end, it calls the output handlers to create output files.\n \n Args:\... |
class BeamDecoder(Decoder):
'This decoder implements standard beam search and several\n variants of it such as diversity promoting beam search and beam\n search with heuristic future cost estimates. This implementation\n supports risk-free pruning.\n '
name = 'beam'
def __init__(self, decoder... |
class DiverseBeamDecoder(BeamDecoder):
'This decoder implements diversity promoting beam search Vijayakumar et. al. (2016).\n '
name = 'diverse_beam'
def __init__(self, decoder_args):
super(DiverseBeamDecoder, self).__init__(decoder_args)
assert (not self.gumbel)
self.beam_size... |
class Hypothesis():
'Complete translation hypotheses are represented by an instance\n of this class. We store the produced sentence, the combined score,\n and a score breakdown to the separate predictor scores.\n '
def __init__(self, trgt_sentence, total_score, score_breakdown=[], base_score=0.0, st... |
class PartialHypothesis(object):
'Represents a partial hypothesis in various decoders. '
def __init__(self, initial_states=None, use_stats=True):
self.predictor_states = initial_states
self.trgt_sentence = []
(self.score, self.base_score) = (0.0, 0.0)
self.score_breakdown = []... |
class Decoder(object):
'A ``Decoder`` instance represents a particular search strategy\n such as A*, beam search, greedy search etc. Decisions are made \n based on the outputs of one or many predictors, which are \n maintained by the ``Decoder`` instance.\n \n Decoders are observable. They fire not... |
class DijkstraDecoder(Decoder):
name = 'dijkstra'
def __init__(self, decoder_args):
super(DijkstraDecoder, self).__init__(decoder_args)
self.nbest = max(1, decoder_args.nbest)
self.use_lower_bound = (not self.gumbel)
self.capacity = (decoder_args.beam if (not self.gumbel) else... |
class DijkstraTSDecoder(Decoder):
name = 'dijkstra_ts'
def __init__(self, decoder_args):
super(DijkstraTSDecoder, self).__init__(decoder_args)
self.nbest = max(1, decoder_args.nbest)
self.beam = (decoder_args.beam if (not self.gumbel) else self.nbest)
self.stop_criterion = (se... |
class GreedyDecoder(Decoder):
name = 'greedy'
def __init__(self, decoder_args):
super(GreedyDecoder, self).__init__(decoder_args)
def decode(self, src_sentence):
self.initialize_predictor(src_sentence)
hypothesis = PartialHypothesis(self.get_predictor_states(), self.calculate_sta... |
class ReferenceDecoder(Decoder):
name = 'reference'
def __init__(self, decoder_args):
super(ReferenceDecoder, self).__init__(decoder_args)
def decode(self, src_sentence, trgt_sentence):
self.trgt_sentence = (trgt_sentence + [utils.EOS_ID])
self.initialize_predictor(src_sentence)
... |
class SamplingDecoder(Decoder):
name = 'sampling'
def __init__(self, decoder_args):
'Creates a new A* decoder instance. The following values are\n fetched from `decoder_args`:\n \n nbest (int): If this is set to a positive value, we do not\n stop decod... |
class NucleusSamplingDecoder(SamplingDecoder):
name = 'nucleus_sampling'
def __init__(self, decoder_args):
'Creates a new A* decoder instance. The following values are\n fetched from `decoder_args`:\n \n nbest (int): If this is set to a positive value, we do not\n ... |
def encode(sentence, target=False):
'Converts a sentence in string representation to a\n sequence of token IDs. Depending on the configuration of this\n module, it applies word maps and/or subword/character segmentation\n on the input. This method calls ``encoder.encode()``.\n\n Args:\n src_sen... |
def encode_trg(trg_sentence):
'Converts the target sentence in string representation to a\n sequence of token IDs. Depending on the configuration of this\n module, it applies word maps and/or subword/character segmentation\n on the input. This method calls ``encoder.encode_trg()``.\n\n Args:\n ... |
def decode(trg_sentence):
'Converts the target sentence represented as sequence of token\n IDs to a string representation. This method calls\n ``decoder.decode()``.\n\n Args:\n trg_sentence (list): A sequence of integers (token IDs)\n\n Returns:\n string.\n '
return decoder.decode... |
def initialize(args):
'Initializes the ``io`` module, including loading word maps and\n other resources needed for encoding and decoding. Subsequent calls\n of ``encode()`` and ``decode()`` will process input as specified in\n ``args``.\n\n Args:\n args (object): SGNMT config\n '
global ... |
class Encoder(object):
'Super class for IO encoders.'
def encode(self, src_sentence):
'Converts the source sentence in string representation to a\n sequence of token IDs. Depending on the configuration of this\n module, it applies word maps and/or subword/character segmentation\n ... |
class Decoder(object):
'"Super class for IO decoders.'
def decode(self, trg_sentence):
'Converts the target sentence represented as sequence of token\n IDs to a string representation.\n\n Args:\n trg_sentence (list): A sequence of integers (token IDs)\n\n Returns:\n ... |
class IDEncoder(Encoder):
'Encoder for ID mapping.'
def encode(self, src_sentence):
return [int(w) for w in src_sentence.split()]
|
class IDDecoder(Decoder):
'"Decoder for ID mapping.'
def decode(self, trg_sentence):
return ' '.join(map(str, trg_sentence))
|
class WordEncoder(Encoder):
'Encoder for word based mapping.'
def encode(self, src_sentence):
return [src_wmap.get(w, utils.UNK_ID) for w in src_sentence.split()]
def encode_trg(self, trg_sentence):
return [trg_wmap_rev.get(w, utils.UNK_ID) for w in trg_sentence.split()]
|
class WordDecoder(Decoder):
'"Decoder for word based mapping.'
def decode(self, trg_sentence):
return ' '.join((trg_wmap.get(w, '<UNK>') for w in trg_sentence))
|
class BartDecoder(Decoder):
'"Decoder for word based mapping.'
def decode(self, trg_sentence):
return bart.decode(' '.join((trg_wmap.get(w, '<UNK>') for w in trg_sentence)))
|
class CharEncoder(Encoder):
'Encoder for char mapping.'
def encode(self, src_sentence):
return [src_wmap.get(c, utils.UNK_ID) for c in src_sentence.replace(' ', '_')]
|
class CharDecoder(Decoder):
'"Decoder for char mapping.'
def decode(self, trg_sentence):
return ''.join((trg_wmap.get(c, '<UNK>') for c in trg_sentence)).replace('_', ' ')
|
class BPE(object):
def __init__(self, codes_path, separator='@@', remove_eow=False):
with codecs.open(codes_path, encoding='utf-8') as codes:
codes.seek(0)
offset = 1
firstline = codes.readline()
if firstline.startswith('#version:'):
self.ve... |
class BPEEncoder(Encoder):
'Encoder for BPE mapping.'
def __init__(self, codes_path, separator='', remove_eow=False):
self.bpe = BPE(codes_path, separator, remove_eow)
def encode(self, src_sentence):
bpe_str = self.bpe.segment(src_sentence)
bpe_int = []
for w in bpe_str.s... |
class BPEDecoder(Decoder):
'"Decoder for BPE mapping SGNMT style.'
def decode(self, trg_sentence):
return ''.join((trg_wmap.get(w, '<UNK>') for w in trg_sentence)).replace('</w>', ' ')
|
class BPEAtAtDecoder(Decoder):
'"Decoder for BPE mapping with @@ separator.'
def decode(self, trg_sentence):
return ' '.join((trg_wmap.get(w, '<UNK>') for w in trg_sentence)).replace('@@ ', '')
|
class BPEUndDecoder(Decoder):
'"Decoder for BPE mapping with @@ separator.'
def decode(self, trg_sentence):
return ' '.join((trg_wmap.get(w, '<UNK>') for w in trg_sentence)).replace(' ', '').replace('▁', ' ')
|
def src_sentence(src):
if ('bart' in globals()):
return bart.decode(src)
return src
|
def load_src_wmap(path):
'Loads a source side word map from the file system.\n \n Args:\n path (string): Path to the word map (Format: word id)\n \n Returns:\n dict. Source word map (key: word, value: id)\n '
global src_wmap
if (not path):
src_wmap = {}
return ... |
def load_bart_decoder(path):
'Loads a source side word map from the file system.\n \n Args:\n path (string): Path to the word map (Format: word id)\n \n Returns:\n dict. Source word map (key: word, value: id)\n '
from fairseq import options
from fairseq.data import encoders
... |
def load_trg_wmap(path):
'Loads a target side word map from the file system.\n \n Args:\n path (string): Path to the word map (Format: word id)\n \n Returns:\n dict. Source word map (key: id, value: word)\n '
global trg_wmap
if (not path):
trg_wmap = {}
return ... |
def _mkdir(path, name):
try:
os.makedirs(path)
except OSError as exception:
if (exception.errno != errno.EEXIST):
raise
else:
logging.warn(("Output %s directory '%s' already exists." % (name, path)))
|
class OutputHandler(object):
'Interface for output handlers. '
def __init__(self):
' Empty constructor '
pass
@abstractmethod
def write_hypos(self, all_hypos, sen_indices=None):
'This method writes output files to the file system. The\n configuration parameters such as... |
class TextOutputHandler(OutputHandler):
'Writes the first best hypotheses to a plain text file '
name = 'text'
def __init__(self, path, args):
'Creates a plain text output handler to write to ``path`` '
super(TextOutputHandler, self).__init__()
self.path = path
def write_hypo... |
class ScoreOutputHandler(OutputHandler):
'Writes the first best hypotheses to a plain text file '
name = 'score'
def __init__(self, path, args):
'Creates a plain text output handler to write to ``path`` '
super(ScoreOutputHandler, self).__init__()
self.path = path
self.ope... |
class NBestSeparateOutputHandler(OutputHandler):
'Produces n-best files with hypotheses at respecitve positions\n '
name = 'nbest_sep'
def __init__(self, path, args):
'\n Args:\n path (string): Path to the n-best file to write\n N: n-best \n '
super... |
class NBestOutputHandler(OutputHandler):
'Produces a n-best file in Moses format. The third part of each \n entry is used to store the separated unnormalized predictor scores.\n Note that the sentence IDs are shifted: Moses n-best files start \n with the index 0, but in SGNMT and HiFST we usually refer t... |
class NgramOutputHandler(OutputHandler):
'This output handler extracts MBR-style ngram posteriors from the \n hypotheses returned by the decoder. The hypothesis scores are assumed to\n be loglikelihoods, which we renormalize to make sure that we operate on a\n valid distribution. The scores produced by t... |
class Predictor(object):
'A predictor produces the predictive probability distribution of\n the next word given the state of the predictor. The state may \n change during ``predict_next()`` and ``consume()``. The functions\n ``get_state()`` and ``set_state()`` can be used for non-greedy \n decoding. N... |
def gumbel_max_sample(x):
'\n x: log-probability distribution (unnormalized is ok) over discrete random variable\n '
z = np.random.gumbel(loc=0, scale=1, size=x.shape)
return np.nanargmax((x + z))
|
def exponential_sample(x):
'\n probability distribution over discrete random variable\n '
E = (- np.log(np.random.uniform(size=len(x))))
E /= x
return np.nanargmin(E)
|
def log_multinomial_sample(x):
'\n x: log-probability distribution (unnormalized is ok) over discrete random variable\n '
x[np.where(np.isnan(x))] = utils.NEG_INF
c = np.logaddexp.accumulate(x)
key = (np.log(np.random.uniform()) + c[(- 1)])
return bisect(c, key)
|
def log_nucleus_multinomial_sample(x, size=1, nucleus_p=np.log(0.95)):
'\n x: log-probability distribution (unnormalized is ok) over discrete random variable\n '
assert (nucleus_p <= 0)
if (len(x) == 1):
return ([0] * size)
inds = np.argsort((- x))
sortedx = x[inds]
c = np.logadd... |
class DummyPredictor(Predictor):
'Predictor for using fairseq models.'
def __init__(self, vocab_size=10, n_cpu_threads=(- 1), seed=0):
'Initializes a fake predictor with deterministic outputs.\n '
super(DummyPredictor, self).__init__()
self.vocab_size = vocab_size
self.... |
def base_init(new_args):
global args
args = new_args
if (sys.version_info < (3, 0)):
sys.stderr = codecs.getwriter('UTF-8')(sys.stderr)
sys.stdout = codecs.getwriter('UTF-8')(sys.stdout)
sys.stdin = codecs.getreader('UTF-8')(sys.stdin)
logging.warn('Library is tested with P... |
def add_predictor(decoder):
p = DummyPredictor(vocab_size=20)
decoder.add_predictor('dummy', p)
|
def create_decoder():
try:
decoder = decoding.DECODER_REGISTRY[args.decoder](args)
except Exception as e:
logging.fatal(('An %s has occurred while initializing the decoder: %s Stack trace: %s' % (sys.exc_info()[0], e, traceback.format_exc())))
sys.exit('Could not initialize decoder.')
... |
def _generate_dummy_hypo():
return decoding.core.Hypothesis([utils.UNK_ID], 0.0, [0.0])
|
def create_src_sentences(num_sentences=10, str_length=5):
return [randomString(str_length) for i in range(num_sentences)]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.