opennmt.utils.misc module

Various utility functions to use throughout the project.

opennmt.utils.misc.print_bytes(str_as_bytes, stream=None)[source]

Prints a string viewed as bytes.

  • str_as_bytes – The bytes to print.
  • stream – The stream to print to (sys.stdout if not set).
opennmt.utils.misc.format_translation_output(sentence, score=None, token_level_scores=None, attention=None, alignment_type=None)[source]

Formats a translation output with possibly scores, alignments, etc., e.g:

1.123214 ||| Hello world ||| 0.30907777 0.030488174 ||| 0-0 1-1

  • sentence – The translation to output.
  • score – If set, attach the score.
  • token_level_scores – If set, attach the token level scores.
  • attention – The attention vector.
  • alignment_type – The type of alignments to format (can be: “hard”).

Returns x as a tuple or its single element.

opennmt.utils.misc.classes_in_module(module, public_only=False)[source]

Returns a generator over the classes defined in module.


Returns the name of fun arguments.


Returns a path to the third_party directory.


Returns the number of lines of the file filename.


Returns the total number of trainable parameters.


Return list of dims, statically where possible.

opennmt.utils.misc.extract_prefixed_keys(dictionary, prefix)[source]

Returns a dictionary with all keys from dictionary that are prefixed with prefix.

opennmt.utils.misc.extract_suffixed_keys(dictionary, suffix)[source]

Returns a dictionary with all keys from dictionary that are suffixed with suffix.


Returns a generator to iterate on each batch of a Numpy array or dict of Numpy arrays.

opennmt.utils.misc.merge_dict(dict1, dict2)[source]

Merges dict2 into dict1.

  • dict1 – The base dictionary.
  • dict2 – The dictionary to merge.

The merged dictionary dict1.

class opennmt.utils.misc.OrderRestorer(index_fn, callback_fn)[source]

Bases: object

Helper class to restore out-of-order elements in order.

__init__(index_fn, callback_fn)[source]

Initializes this object.

  • index_fn – A callable mapping an element to a unique index.
  • callback_fn – A callable taking an element that will be called in order.

Push event x.

opennmt.utils.misc.add_dict_to_collection(collection_name, dict_)[source]

Adds a dictionary to a graph collection.

  • collection_name – The name of the collection to add the dictionary to
  • dict – A dictionary of string keys to tensor values

Gets a dictionary from a graph collection.

Parameters:collection_name – A collection name to read a dictionary from
Returns:A dictionary with string keys and tensor values