code
stringlengths
17
6.64M
def sort_by_size(file_list, transcription_list, size_list): zipped = list(zip(file_list, transcription_list, size_list)) sorted_lists = sorted(zipped, key=(lambda x: (x[2][1], x[2][0]))) return ([x[0] for x in sorted_lists], [x[1] for x in sorted_lists], [x[2] for x in sorted_lists])
def convert(file_list_path, char_list_path, selections, out_file_names, pad_whitespace, dataset_prefix, base_path, compress): charlist = load_char_list(char_list_path) (file_list, transcription_list, size_list, n_labels) = load_file_list_and_transcriptions_and_sizes_and_n_labels(file_list_path, char_list_path...
def get_image_list(train_list_path): with open(train_list_path) as f: imgs = f.readlines() imgs = [img.replace('\n', '') for img in imgs] return imgs
def get_train_and_train_valid_lists(train_list_path, blacklist, train_fraction=0.9): with open(train_list_path) as f: imgs = f.readlines() imgs = [img.replace('\n', '') for img in imgs] n_train = int(round((train_fraction * len(imgs)))) train_imgs = imgs[:n_train] train_valid_imgs = imgs[n...
def convert_IAM_lines_demo(base_path_imgs, tag, blacklist=[]): base_path_out = (('features/' + tag) + '/') mkdir_p(base_path_out) file_list_path = 'lines.txt' char_list_path = 'chars.txt' selection_list_path = 'split/demo.txt' out_file_name_demo = (base_path_out + 'demo.h5') print('convert...
def convert_IAM_lines_train(base_path_imgs, tag, blacklist=[]): base_path_out = (('features/' + tag) + '/') mkdir_p(base_path_out) file_list_path = 'lines.txt' char_list_path = 'chars.txt' selection_list_path = 'split/train.txt' out_file_name_train1 = (base_path_out + 'train.1.h5') out_fil...
def convert_IAM_lines_valid_test(base_path_imgs, tag): base_path_out = (('features/' + tag) + '/') mkdir_p(base_path_out) char_list_path = 'chars.txt' selection_list_path_valid = 'split/valid.txt' selection_list_path_test = 'split/eval.txt' out_file_name_valid = (base_path_out + 'valid.h5') ...
def main(): base_path_imgs = 'IAM_lines' tag = 'raw' if (base_path_imgs[(- 1)] != '/'): base_path_imgs += '/' convert_IAM_lines_demo(base_path_imgs, tag)
def hdf5_strings(handle, name, data): try: S = max([len(d) for d in data]) dset = handle.create_dataset(name, (len(data),), dtype=('S' + str(S))) dset[...] = data except Exception: dt = h5py.special_dtype(vlen=unicode) del handle[name] dset = handle.create_datas...
def write_to_hdf(img_list, transcription_list, charlist, out_file_name, dataset_prefix='train'): with h5py.File(out_file_name, 'w') as f: f.attrs['inputPattSize'] = 1 f.attrs['numDims'] = 1 f.attrs['numSeqs'] = len(img_list) classes = charlist inputs = [] sizes = []...
def main(): char_list = ['a', 'b', 'c', 'd'] img_list = [numpy.zeros((14, 14), dtype='float32'), numpy.zeros((12, 12), dtype='float32')] transcription_list = [[0, 1, 2], [2, 0, 1]] out_file_name = 'test.h5' write_to_hdf(img_list, transcription_list, char_list, out_file_name)
def hdf5_strings(handle, name, data): try: S = max([len(d) for d in data]) dset = handle.create_dataset(name, (len(data),), dtype=('S' + str(S))) dset[...] = data except Exception: dt = h5py.special_dtype(vlen=unicode) del handle[name] dset = handle.create_datas...
def write_to_hdf(img_list, transcription_list, charlist, out_file_name, dataset_prefix='train'): with h5py.File(out_file_name, 'w') as f: f.attrs['inputPattSize'] = 3 f.attrs['numDims'] = 1 f.attrs['numSeqs'] = len(img_list) classes = charlist inputs = [] sizes = []...
def main(): char_list = ['a', 'b', 'c', 'd'] img_list = [numpy.zeros((14, 14, 3), dtype='float32'), numpy.zeros((12, 12, 3), dtype='float32')] transcription_list = [[0, 1, 2], [2, 0, 1]] out_file_name = 'test.h5' write_to_hdf(img_list, transcription_list, char_list, out_file_name)
def linkcode_resolve(domain, info): def find_source(): obj = sys.modules[info['module']] for part in info['fullname'].split('.'): obj = getattr(obj, part) import inspect import os fn = inspect.getsourcefile(obj) fn = os.path.relpath(fn, start='returnn')...
def generate(): updater._init_optimizer_classes_dict() optimizer_dict = updater._OptimizerClassesDict rst_file = open('optimizer.rst', 'w') rst_file.write(header_text) for (optimizer_name, optimizer_class) in sorted(optimizer_dict.items()): if (not optimizer_name.endswith('optimizer')): ...
def generate(): RecLayer._create_rnn_cells_dict() layer_names = sorted(list(RecLayer._rnn_cells_dict.keys())) rst_file = open('layer_reference/units.rst', 'w') rst_file.write(header_text) for layer_name in layer_names: unit_class = RecLayer.get_rnn_cell_class(layer_name) if (issubc...
def generate(): if (not os.path.exists('api')): os.mkdir('api') def makeapi(modname): '\n :param str modname:\n ' fn = ('api/%s.rst' % (modname[len('returnn.'):] or '___base')) if os.path.exists(fn): return f = open(fn, 'w') target_pyt...
def init_config(config_filename=None, command_line_options=(), default_config=None, extra_updates=None): '\n :param str|None config_filename:\n :param list[str]|tuple[str] command_line_options: e.g. ``sys.argv[1:]``\n :param dict[str]|None default_config:\n :param dict[str]|None extra_updates:\n\n ...
def init_log(): '\n Initializes the global :class:`Log`.\n ' log.init_by_config(config)
def get_cache_byte_sizes(): '\n :rtype: (int,int,int)\n :returns cache size in bytes for (train,dev,eval)\n ' cache_sizes_user = config.list('cache_size', [('%iG' % util.default_cache_size_in_gbytes())]) num_datasets = ((1 + config.has('dev')) + config.has('eval')) cache_factor = 1.0 if (...
def load_data(config, cache_byte_size, files_config_key, **kwargs): '\n :param Config config:\n :param int cache_byte_size:\n :param str files_config_key: such as "train" or "dev"\n :param kwargs: passed on to init_dataset() or init_dataset_via_str()\n :rtype: (Dataset,int)\n :returns the datase...
def init_data(): '\n Initializes the globals train,dev,eval of type Dataset.\n ' cache_byte_sizes = get_cache_byte_sizes() global train_data, dev_data, eval_data (dev_data, extra_cache_bytes_dev) = load_data(config, cache_byte_sizes[1], 'dev', **Dataset.get_default_kwargs_eval(config=config)) ...
def print_task_properties(): '\n print information about used data\n ' if train_data: print('Train data:', file=log.v2) print(' input:', train_data.num_inputs, 'x', train_data.window, file=log.v2) print(' output:', train_data.num_outputs, file=log.v2) print(' ', (train_...
def init_engine(): '\n Initializes global ``engine``, for example :class:`returnn.tf.engine.Engine`.\n ' global engine if BackendEngine.is_tensorflow_selected(): from returnn.tf.engine import Engine engine = Engine(config=config) elif BackendEngine.is_torch_selected(): fr...
def returnn_greeting(config_filename=None, command_line_options=None): '\n Prints some RETURNN greeting to the log.\n\n :param str|None config_filename:\n :param list[str]|None command_line_options:\n ' print(('RETURNN starting up, version %s, date/time %s, pid %i, cwd %s, Python %s' % (util.descr...
def init_backend_engine(): '\n Selects the backend engine (TensorFlow, PyTorch, Theano, or whatever)\n and does corresponding initialization and preparation.\n\n This does not initialize the global ``engine`` object yet.\n See :func:`init_engine` for that.\n ' if config.value('PYTORCH_CUDA_ALLO...
def init(config_filename=None, command_line_options=(), config_updates=None, extra_greeting=None): '\n :param str|None config_filename:\n :param tuple[str]|list[str]|None command_line_options: e.g. sys.argv[1:]\n :param dict[str]|None config_updates: see :func:`init_config`\n :param str|None extra_gre...
def finalize(error_occurred=False): '\n Cleanup at the end.\n\n :param bool error_occurred:\n ' print('Quitting', file=getattr(log, 'v4', sys.stderr)) global quit_returnn quit_returnn = True sys.exited = True if engine: if BackendEngine.is_tensorflow_selected(): en...
def need_data(): '\n :return: whether we need to init the data (call :func:`init_data`) for the current task (:func:`execute_main_task`)\n :rtype: bool\n ' if (config.has('need_data') and (not config.bool('need_data', True))): return False task = config.value('task', 'train') if (task...
def execute_main_task(): '\n Executes the main task (via config ``task`` option).\n ' from returnn.util.basic import hms_fraction start_time = time.time() task = config.value('task', 'train') if config.is_true('dry_run'): print('Dry run, will not save anything.', file=log.v1) if ...
def analyze_data(config): '\n :param Config config:\n ' dss = config.value('analyze_dataset', 'train') ds = {'train': train_data, 'dev': dev_data, 'eval': eval_data}[dss] epoch = config.int('epoch', 1) print('Analyze dataset', dss, 'epoch', epoch, file=log.v1) ds.init_seq_order(epoch=epo...
def main(argv=None): '\n Main entry point of RETURNN.\n\n :param list[str]|None argv: ``sys.argv`` by default\n ' if (argv is None): argv = sys.argv return_code = 0 try: assert (len(argv) >= 2), ('usage: %s <config>' % argv[0]) init(command_line_options=argv[1:]) ...
def setup(package_name=__package__, modules=None): '\n This does the setup, such that all the modules become available in the `returnn` package.\n It does not import all the modules now, but instead provides them lazily.\n\n :param str package_name: "returnn" by default\n :param dict[str,types.ModuleT...
class _LazyLoader(types.ModuleType): '\n Lazily import a module, mainly to avoid pulling in large dependencies.\n Code borrowed from TensorFlow, and simplified, and extended.\n ' def __init__(self, full_mod_name, **kwargs): '\n :param str full_mod_name:\n ' super(_LazyL...
def debug_print_file(fn): '\n :param str fn:\n ' print(('%s:' % fn)) if (not os.path.exists(fn)): print('<does not exist>') return if os.path.isdir(fn): print('<dir:>') pprint(sorted(os.listdir(fn))) return print(open(fn).read())
def parse_pkg_info(fn): '\n :param str fn:\n :return: dict with info written by distutils. e.g. ``res["Version"]`` is the version.\n :rtype: dict[str,str]\n ' res = {} for ln in open(fn).read().splitlines(): if ((not ln) or (not ln[:1].strip())): continue (key, valu...
def git_head_version(git_dir=_root_dir, long=False): '\n :param str git_dir:\n :param bool long: see :func:`get_version_str`\n :rtype: str\n ' from returnn.util.basic import git_commit_date, git_commit_rev, git_is_dirty commit_date = git_commit_date(git_dir=git_dir) version = ('1.%s' % com...
def get_version_str(verbose=False, verbose_error=False, fallback=None, long=False): '\n :param bool verbose: print exactly how we end up with some version\n :param bool verbose_error: print only any potential errors\n :param str|None fallback:\n :param bool long:\n False: Always distutils.version...
class Config(): '\n Reads in some config file, and provides access to the key/value items.\n We support some simple text-line-based config, JSON, and Python format.\n ' def __init__(self, items=None): '\n :param dict[str]|None items: optional initial typed_dict\n ' self...
@contextlib.contextmanager def global_config_ctx(config: Config): '\n sets the config as global config in this context,\n and recovers the original global config afterwards\n ' global _global_config prev_global_config = _global_config try: set_global_config(config) (yield) ...
def set_global_config(config): '\n Will define the global config, returned by :func:`get_global_config`\n\n :param Config config:\n ' _get_or_set_config_via_tf_default_graph(config) global _global_config _global_config = config
def get_global_config(*, raise_exception: bool=True, auto_create: bool=False, return_empty_if_none: bool=False): '\n :param raise_exception: if no global config is found, raise an exception, otherwise return None\n :param auto_create: if no global config is found, it creates one, registers it as global, and...
def _get_or_set_config_via_tf_default_graph(config=None): '\n This is done in a safe way, and might just be a no-op.\n When TF is not imported yet, it will just return.\n\n :param Config|None config: if set, will set it\n :rtype: Config|None\n ' if ('tensorflow' not in sys.modules): ret...
def network_json_from_config(config): '\n :param Config config:\n :rtype: dict[str]\n ' if (config.has('network') and config.is_typed('network')): json_content = config.typed_value('network') assert isinstance(json_content, dict) assert json_content return json_content...
def tf_should_use_gpu(config): '\n :param Config config:\n :rtype: bool\n ' cfg_dev = config.value('device', None) if (cfg_dev == 'gpu'): return True if (cfg_dev == 'cpu'): return False if (not cfg_dev): from returnn.log import log from returnn.tf.util.basi...
def _global_config_as_py_module_proxy_setup(): if (_PyModuleName in sys.modules): return sys.modules[_PyModuleName] = _GlobalConfigAsPyModuleProxy(_PyModuleName)
class _GlobalConfigAsPyModuleProxy(_types.ModuleType): '\n Takes :func:`get_global_config`, and makes its ``typed_dict`` available as module attributes.\n ' @staticmethod def _get_config() -> Optional[Config]: '\n :return: config or None if not available anymore\n ' re...
class OggZipDataset(CachedDataset2): "\n Generic dataset which reads a Zip file containing Ogg files for each sequence and a text document.\n The feature extraction settings are determined by the ``audio`` option,\n which is passed to :class:`ExtractAudioFeatures`.\n Does also support Wav files, and m...
class Dataset(object): '\n Base class for any dataset. This defines the dataset API.\n ' @staticmethod def kwargs_update_from_config(config, kwargs): '\n :type config: returnn.config.Config\n :type kwargs: dict[str]\n ' def set_or_remove(key, value): ...
class DatasetSeq(): '\n Encapsulates all data for one sequence.\n ' def __init__(self, seq_idx, features, targets=None, seq_tag=None): '\n :param int seq_idx: sorted seq idx in the Dataset\n :param numpy.ndarray|dict[str,numpy.ndarray] features: format 2d (time,feature) (float)\n ...
def get_dataset_class(name: Union[(str, Type[Dataset])]) -> Optional[Type[Dataset]]: '\n :param str|type name:\n ' if isinstance(name, type): assert issubclass(name, Dataset) return name if _dataset_classes: return _dataset_classes.get(name, None) from importlib import im...
def init_dataset(kwargs, extra_kwargs=None, default_kwargs=None): '\n :param dict[str]|str|(()->dict[str])|Dataset kwargs:\n :param dict[str]|None extra_kwargs:\n :param dict[str]|None default_kwargs:\n :rtype: Dataset\n ' assert kwargs if isinstance(kwargs, Dataset): data = kwargs ...
def init_dataset_via_str(config_str, config=None, cache_byte_size=None, **kwargs): '\n :param str config_str: hdf-files, or "LmDataset:..." or so\n :param returnn.config.Config|None config: optional, only for "sprint:..."\n :param int|None cache_byte_size: optional, only for HDFDataset\n :rtype: Datas...
def convert_data_dims(data_dims, leave_dict_as_is=False): '\n This converts what we called num_outputs originally,\n from the various formats which were allowed in the past\n (just an int, or dict[str,int]) into the format which we currently expect.\n In all cases, the output will be a new copy of the...
def shapes_for_batches(batches: Sequence[Batch], *, data_keys: Sequence[str], dataset: Optional[Dataset]=None, extern_data: Optional[TensorDict], enforce_min_len1: bool=False) -> Optional[Dict[(str, List[int])]]: '\n :param batches:\n :param data_keys:\n :param dataset:\n :param extern_data: detailed ...
def set_config_extern_data_from_dataset(config, dataset): '\n :param returnn.config.Config config:\n :param Dataset dataset:\n ' from returnn.tf.network import _data_kwargs_from_dataset_key config.set('extern_data', {key: _data_kwargs_from_dataset_key(dataset=dataset, key=key) for key in dataset....
class BundleFile(object): 'Holds paths to HDF dataset files.' def __init__(self, filePath): 'Reads paths to HDF dataset files from a bundle file.\n Example of contents of a bundle file:\n\n /work/asr2/ryndin/crnnRegressionSpeechEnhancemenent/data/data_tr05_real_1_100.hdf\n /work/...
class CachedDataset(Dataset): '\n Base class for datasets with caching. This is only used for the :class:`HDFDataset`.\n Also see :class:`CachedDataset2`.\n ' def __init__(self, cache_byte_size=0, **kwargs): '\n :param int cache_byte_size:\n ' super(CachedDataset, self)...
class CachedDataset2(Dataset): '\n Somewhat like CachedDataset, but different.\n Simpler in some sense. And more generic. Caching might be worse.\n\n If you derive from this class:\n - you must override `_collect_single_seq`\n - you must set `num_inputs` (dense-dim of "data" key) and `num_outputs` ...
class SingleStreamPipeDataset(CachedDataset2): '\n Producer: Gets data from somewhere / an external source, running in some thread.\n Consumer: The thread / code which calls load_seqs and get_data here.\n ' def __init__(self, dim, ndim, sparse=False, dtype='float32'): '\n :param int d...
class LmDataset(CachedDataset2): '\n Dataset useful for language modeling.\n It creates index sequences for either words, characters or other orthographics symbols based on a vocabulary.\n Can also perform internal word to phoneme conversion with a lexicon file.\n Reads simple txt files or bliss xml f...
def _is_bliss(filename): '\n :param str filename:\n :rtype: bool\n ' try: corpus_file = open(filename, 'rb') if filename.endswith('.gz'): corpus_file = gzip.GzipFile(fileobj=corpus_file) context = iter(ElementTree.iterparse(corpus_file, events=('start', 'end'))) ...
def _iter_bliss(filename, callback): '\n :param str filename:\n :param (str)->None callback:\n ' corpus_file = open(filename, 'rb') if filename.endswith('.gz'): corpus_file = gzip.GzipFile(fileobj=corpus_file) def getelements(tag): '\n Yield *tag* elements from *filena...
def _iter_txt(filename, callback, skip_empty_lines=True): '\n :param str filename:\n :param (str)->None callback:\n :param bool skip_empty_lines:\n ' f = open(filename, 'rb') if filename.endswith('.gz'): f = gzip.GzipFile(fileobj=f) for line in f: try: line = li...
def iter_corpus(filename, callback, skip_empty_lines=True): '\n :param str filename:\n :param ((str)->None) callback:\n :param bool skip_empty_lines:\n ' if _is_bliss(filename): _iter_bliss(filename=filename, callback=callback) else: _iter_txt(filename=filename, callback=callba...
def read_corpus(filename, skip_empty_lines=True): '\n :param str filename: either Bliss XML or line-based text\n :param bool skip_empty_lines: in case of line-based text, skip empty lines\n :return: list of orthographies\n :rtype: list[str]\n ' out_list = [] iter_corpus(filename=filename, c...
class AllophoneState(): '\n Represents one allophone (phone with context) state (number, boundary).\n In Sprint, see AllophoneStateAlphabet::index().\n ' id = None context_history = () context_future = () boundary = 0 state = None _attrs = ['id', 'context_history', 'context_future...
class Lexicon(): '\n Lexicon. Map of words to phoneme sequences (can have multiple pronunciations).\n ' def __init__(self, filename): '\n :param str filename:\n ' print('Loading lexicon', filename, file=log.v4) lex_file = open(filename, 'rb') if filename.en...
class StateTying(): '\n Clustering of (allophone) states into classes.\n ' def __init__(self, state_tying_file): '\n :param str state_tying_file:\n ' self.allo_map = {} self.class_map = {} lines = open(state_tying_file).read().splitlines() for line ...
class PhoneSeqGenerator(): '\n Generates phone sequences.\n ' def __init__(self, lexicon_file, allo_num_states=3, allo_context_len=1, state_tying_file=None, add_silence_beginning=0.1, add_silence_between_words=0.1, add_silence_end=0.1, repetition=0.9, silence_repetition=0.95): '\n :param...
class TranslationDataset(CachedDataset2): '\n Based on the conventions by our team for translation datasets.\n It gets a directory and expects these files:\n\n - source.dev(.gz)\n - source.train(.gz)\n - source.vocab.pkl\n - target.dev(.gz)\n - target.train(.gz)\n -...
class TranslationFactorsDataset(TranslationDataset): '\n Extends TranslationDataset with support for translation factors,\n see https://workshop2016.iwslt.org/downloads/IWSLT_2016_paper_2.pdf, https://arxiv.org/abs/1910.03912.\n\n Each word in the source and/or target corpus is represented by a tuple of ...
class ConfusionNetworkDataset(TranslationDataset): '\n This dataset allows for multiple (weighted) options for each word in the source sequence.\n In particular, it can be\n used to represent confusion networks.\n Two matrices (of dimension source length x max_density) will be provided as\n input t...
def expand_abbreviations(text): '\n :param str text:\n :rtype: str\n ' for (regex, replacement) in _abbreviations: text = re.sub(regex, replacement, text) return text
def lowercase(text): '\n :param str text:\n :rtype: str\n ' return text.lower()
def lowercase_keep_special(text): '\n :param str text:\n :rtype: str\n ' return re.sub('(\\s|^)(?!(\\[\\S*])|(<\\S*>))\\S+(?=\\s|$)', (lambda m: m.group(0).lower()), text)
def collapse_whitespace(text): '\n :param str text:\n :rtype: str\n ' text = re.sub(_whitespace_re, ' ', text) text = text.strip() return text
def convert_to_ascii(text): '\n :param str text:\n :rtype: str\n ' from unidecode import unidecode return unidecode(text)
def basic_cleaners(text): '\n Basic pipeline that lowercases and collapses whitespace without transliteration.\n\n :param str text:\n :rtype: str\n ' text = lowercase(text) text = collapse_whitespace(text) return text
def transliteration_cleaners(text): '\n Pipeline for non-English text that transliterates to ASCII.\n\n :param str text:\n :rtype: str\n ' text = convert_to_ascii(text) text = lowercase(text) text = collapse_whitespace(text) return text
def english_cleaners(text): '\n Pipeline for English text, including number and abbreviation expansion.\n :param str text:\n :rtype: str\n ' text = convert_to_ascii(text) text = lowercase(text) text = normalize_numbers(text, with_spacing=True) text = expand_abbreviations(text) text...
def english_cleaners_keep_special(text): '\n Pipeline for English text, including number and abbreviation expansion.\n :param str text:\n :rtype: str\n ' text = convert_to_ascii(text) text = lowercase_keep_special(text) text = normalize_numbers(text, with_spacing=True) text = expand_ab...
def get_remove_chars(chars): '\n :param str|list[str] chars:\n :rtype: (str)->str\n ' def remove_chars(text): '\n :param str text:\n :rtype: str\n ' for c in chars: text = text.replace(c, ' ') text = collapse_whitespace(text) return te...
def get_replace(old, new): '\n :param str old:\n :param str new:\n :rtype: (str)->str\n ' def replace(text): '\n :param str text:\n :rtype: str\n ' text = text.replace(old, new) return text return replace
def _get_inflect(): global _inflect if _inflect: return _inflect import inflect _inflect = inflect.engine() return _inflect
def _remove_commas(m): '\n :param typing.Match m:\n :rtype: str\n ' return m.group(1).replace(',', '')
def _expand_decimal_point(m): '\n :param typing.Match m:\n :rtype: str\n ' return m.group(1).replace('.', ' point ')
def _expand_dollars(m): '\n :param typing.Match m:\n :rtype: str\n ' match = m.group(1) parts = match.split('.') if (len(parts) > 2): return (match + ' dollars') dollars = (int(parts[0]) if parts[0] else 0) cents = (int(parts[1]) if ((len(parts) > 1) and parts[1]) else 0) ...
def _expand_ordinal(m): '\n :param typing.Match m:\n :rtype: str\n ' return _get_inflect().number_to_words(m.group(0))
def _expand_number(m): '\n :param typing.Match m:\n :rtype: str\n ' num_s = m.group(0) num_s = num_s.strip() if ('.' in num_s): return _get_inflect().number_to_words(num_s, andword='') num = int(num_s) if (num_s.startswith('0') or (num in {747})): digits = {'0': 'zero'...
def _expand_number_with_spacing(m): '\n :param typing.Match m:\n :rtype: str\n ' return (' %s ' % _expand_number(m))
def normalize_numbers(text, with_spacing=False): '\n :param str text:\n :param bool with_spacing:\n :rtype: str\n ' text = re.sub(_comma_number_re, _remove_commas, text) text = re.sub(_pounds_re, '\\1 pounds', text) text = re.sub(_dollars_re, _expand_dollars, text) text = re.sub(_decim...
def _dummy_identity_pp(text): '\n :param str text:\n :rtype: str\n ' return text
def get_post_processor_function(opts): '\n You might want to use :mod:`inflect` or :mod:`unidecode`\n for some normalization / cleanup.\n This function can be used to get such functions.\n\n :param str|list[str] opts: e.g. "english_cleaners", or "get_remove_chars(\',/\')"\n :return: function\n :...
def _main(): from returnn.util import better_exchook better_exchook.install() from argparse import ArgumentParser arg_parser = ArgumentParser() arg_parser.add_argument('lm_dataset', help=('Python eval string, should eval to dict' + ', or otherwise filename, and will just dump')) arg_parser.add...
class MapDatasetBase(object): '\n This dataset can be used as template to implement user-side Datasets,\n where the data can be access in arbitrary order.\n For global sorting, the length information needs to be known beforehand, see get_seq_len.\n ' def __init__(self, data_types=None): "...
class MapDatasetWrapper(CachedDataset2): '\n Takes a MapDataset and turns it into a returnn.datasets.Dataset by providing the required class methods.\n ' def __init__(self, map_dataset, **kwargs): '\n :param MapDatasetBase|function map_dataset: the MapDataset to be wrapped\n ' ...
class FromListDataset(MapDatasetBase): '\n Simple implementation of a MapDataset where all data is given in a list.\n ' def __init__(self, data_list, sort_data_key=None, **kwargs): '\n :param list[dict[str,numpy.ndarray]] data_list: sequence data as a dict data_key -> data for all sequen...
def _get_num_outputs_entry(name: str, opts: Dict[(str, Any)]) -> Tuple[(int, int)]: '\n :param opts: data opts from data_types in MapDatasetBase\n :return: num_outputs entry: (num-classes, len(shape))\n\n This is maybe optional at some point when we remove num_outputs in Dataset.\n ' from returnn....