id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,200
readbeyond/aeneas
aeneas/tree.py
Tree.leaves_not_empty
def leaves_not_empty(self): """ Return the list of leaves not empty in the tree rooted at this node, in DFS order. :rtype: list of :class:`~aeneas.tree.Tree` """ return [n for n in self.dfs if ((n.is_leaf) and (not n.is_empty))]
python
def leaves_not_empty(self): """ Return the list of leaves not empty in the tree rooted at this node, in DFS order. :rtype: list of :class:`~aeneas.tree.Tree` """ return [n for n in self.dfs if ((n.is_leaf) and (not n.is_empty))]
[ "def", "leaves_not_empty", "(", "self", ")", ":", "return", "[", "n", "for", "n", "in", "self", ".", "dfs", "if", "(", "(", "n", ".", "is_leaf", ")", "and", "(", "not", "n", ".", "is_empty", ")", ")", "]" ]
Return the list of leaves not empty in the tree rooted at this node, in DFS order. :rtype: list of :class:`~aeneas.tree.Tree`
[ "Return", "the", "list", "of", "leaves", "not", "empty", "in", "the", "tree", "rooted", "at", "this", "node", "in", "DFS", "order", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L335-L343
232,201
readbeyond/aeneas
aeneas/tree.py
Tree.height
def height(self): """ Return the height of the tree rooted at this node, that is, the difference between the level of a deepest leaf and the level of this node. Return ``1`` for a single-node tree, ``2`` for a two-levels tree, etc. :rtype: int """ return max([n.level for n in self.subtree]) - self.level + 1
python
def height(self): """ Return the height of the tree rooted at this node, that is, the difference between the level of a deepest leaf and the level of this node. Return ``1`` for a single-node tree, ``2`` for a two-levels tree, etc. :rtype: int """ return max([n.level for n in self.subtree]) - self.level + 1
[ "def", "height", "(", "self", ")", ":", "return", "max", "(", "[", "n", ".", "level", "for", "n", "in", "self", ".", "subtree", "]", ")", "-", "self", ".", "level", "+", "1" ]
Return the height of the tree rooted at this node, that is, the difference between the level of a deepest leaf and the level of this node. Return ``1`` for a single-node tree, ``2`` for a two-levels tree, etc. :rtype: int
[ "Return", "the", "height", "of", "the", "tree", "rooted", "at", "this", "node", "that", "is", "the", "difference", "between", "the", "level", "of", "a", "deepest", "leaf", "and", "the", "level", "of", "this", "node", ".", "Return", "1", "for", "a", "single", "-", "node", "tree", "2", "for", "a", "two", "-", "levels", "tree", "etc", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L357-L368
232,202
readbeyond/aeneas
aeneas/tree.py
Tree.levels
def levels(self): """ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` """ ret = [[] for i in range(self.height)] for node in self.subtree: ret[node.level - self.level].append(node) return ret
python
def levels(self): """ Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree` """ ret = [[] for i in range(self.height)] for node in self.subtree: ret[node.level - self.level].append(node) return ret
[ "def", "levels", "(", "self", ")", ":", "ret", "=", "[", "[", "]", "for", "i", "in", "range", "(", "self", ".", "height", ")", "]", "for", "node", "in", "self", ".", "subtree", ":", "ret", "[", "node", ".", "level", "-", "self", ".", "level", "]", ".", "append", "(", "node", ")", "return", "ret" ]
Return a list of lists of nodes. The outer list is indexed by the level. Each inner list contains the nodes at that level, in DFS order. :rtype: list of lists of :class:`~aeneas.tree.Tree`
[ "Return", "a", "list", "of", "lists", "of", "nodes", ".", "The", "outer", "list", "is", "indexed", "by", "the", "level", ".", "Each", "inner", "list", "contains", "the", "nodes", "at", "that", "level", "in", "DFS", "order", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L397-L409
232,203
readbeyond/aeneas
aeneas/tree.py
Tree.level_at_index
def level_at_index(self, index): """ Return the list of nodes at level ``index``, in DFS order. :param int index: the index :rtype: list of :class:`~aeneas.tree.Tree` :raises: ValueError if the given ``index`` is not valid """ if not isinstance(index, int): self.log_exc(u"Index is not an integer", None, True, TypeError) levels = self.levels if (index < 0) or (index >= len(levels)): self.log_exc(u"The given level index '%d' is not valid" % (index), None, True, ValueError) return self.levels[index]
python
def level_at_index(self, index): """ Return the list of nodes at level ``index``, in DFS order. :param int index: the index :rtype: list of :class:`~aeneas.tree.Tree` :raises: ValueError if the given ``index`` is not valid """ if not isinstance(index, int): self.log_exc(u"Index is not an integer", None, True, TypeError) levels = self.levels if (index < 0) or (index >= len(levels)): self.log_exc(u"The given level index '%d' is not valid" % (index), None, True, ValueError) return self.levels[index]
[ "def", "level_at_index", "(", "self", ",", "index", ")", ":", "if", "not", "isinstance", "(", "index", ",", "int", ")", ":", "self", ".", "log_exc", "(", "u\"Index is not an integer\"", ",", "None", ",", "True", ",", "TypeError", ")", "levels", "=", "self", ".", "levels", "if", "(", "index", "<", "0", ")", "or", "(", "index", ">=", "len", "(", "levels", ")", ")", ":", "self", ".", "log_exc", "(", "u\"The given level index '%d' is not valid\"", "%", "(", "index", ")", ",", "None", ",", "True", ",", "ValueError", ")", "return", "self", ".", "levels", "[", "index", "]" ]
Return the list of nodes at level ``index``, in DFS order. :param int index: the index :rtype: list of :class:`~aeneas.tree.Tree` :raises: ValueError if the given ``index`` is not valid
[ "Return", "the", "list", "of", "nodes", "at", "level", "index", "in", "DFS", "order", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L425-L440
232,204
readbeyond/aeneas
aeneas/tree.py
Tree.ancestor
def ancestor(self, index): """ Return the ``index``-th ancestor. The 0-th ancestor is the node itself, the 1-th ancestor is its parent node, etc. :param int index: the number of levels to go up :rtype: :class:`~aeneas.tree.Tree` :raises: TypeError if ``index`` is not an int :raises: ValueError if ``index`` is negative """ if not isinstance(index, int): self.log_exc(u"index is not an integer", None, True, TypeError) if index < 0: self.log_exc(u"index cannot be negative", None, True, ValueError) parent_node = self for i in range(index): if parent_node is None: break parent_node = parent_node.parent return parent_node
python
def ancestor(self, index): """ Return the ``index``-th ancestor. The 0-th ancestor is the node itself, the 1-th ancestor is its parent node, etc. :param int index: the number of levels to go up :rtype: :class:`~aeneas.tree.Tree` :raises: TypeError if ``index`` is not an int :raises: ValueError if ``index`` is negative """ if not isinstance(index, int): self.log_exc(u"index is not an integer", None, True, TypeError) if index < 0: self.log_exc(u"index cannot be negative", None, True, ValueError) parent_node = self for i in range(index): if parent_node is None: break parent_node = parent_node.parent return parent_node
[ "def", "ancestor", "(", "self", ",", "index", ")", ":", "if", "not", "isinstance", "(", "index", ",", "int", ")", ":", "self", ".", "log_exc", "(", "u\"index is not an integer\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "index", "<", "0", ":", "self", ".", "log_exc", "(", "u\"index cannot be negative\"", ",", "None", ",", "True", ",", "ValueError", ")", "parent_node", "=", "self", "for", "i", "in", "range", "(", "index", ")", ":", "if", "parent_node", "is", "None", ":", "break", "parent_node", "=", "parent_node", ".", "parent", "return", "parent_node" ]
Return the ``index``-th ancestor. The 0-th ancestor is the node itself, the 1-th ancestor is its parent node, etc. :param int index: the number of levels to go up :rtype: :class:`~aeneas.tree.Tree` :raises: TypeError if ``index`` is not an int :raises: ValueError if ``index`` is negative
[ "Return", "the", "index", "-", "th", "ancestor", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L454-L476
232,205
readbeyond/aeneas
aeneas/tree.py
Tree.keep_levels
def keep_levels(self, level_indices): """ Rearrange the tree rooted at this node to keep only the given levels. The returned Tree will still be rooted at the current node, i.e. this function implicitly adds ``0`` to ``level_indices``. If ``level_indices`` is an empty list, only this node will be returned, with no children. Elements of ``level_indices`` that do not represent valid level indices (e.g., negative, or too large) will be ignored and no error will be raised. Important: this function modifies the original tree in place! :param list level_indices: the list of int, representing the levels to keep :raises: TypeError if ``level_indices`` is not a list or if it contains an element which is not an int """ if not isinstance(level_indices, list): self.log_exc(u"level_indices is not an instance of list", None, True, TypeError) for l in level_indices: if not isinstance(l, int): self.log_exc(u"level_indices contains an element not int", None, True, TypeError) prev_levels = self.levels level_indices = set(level_indices) if 0 not in level_indices: level_indices.add(0) level_indices = level_indices & set(range(self.height)) level_indices = sorted(level_indices)[::-1] # first, remove children for l in level_indices: for node in prev_levels[l]: node.remove_children(reset_parent=False) # then, connect to the right new parent for i in range(len(level_indices) - 1): l = level_indices[i] for node in prev_levels[l]: parent_node = node.ancestor(l - level_indices[i + 1]) parent_node.add_child(node)
python
def keep_levels(self, level_indices): """ Rearrange the tree rooted at this node to keep only the given levels. The returned Tree will still be rooted at the current node, i.e. this function implicitly adds ``0`` to ``level_indices``. If ``level_indices`` is an empty list, only this node will be returned, with no children. Elements of ``level_indices`` that do not represent valid level indices (e.g., negative, or too large) will be ignored and no error will be raised. Important: this function modifies the original tree in place! :param list level_indices: the list of int, representing the levels to keep :raises: TypeError if ``level_indices`` is not a list or if it contains an element which is not an int """ if not isinstance(level_indices, list): self.log_exc(u"level_indices is not an instance of list", None, True, TypeError) for l in level_indices: if not isinstance(l, int): self.log_exc(u"level_indices contains an element not int", None, True, TypeError) prev_levels = self.levels level_indices = set(level_indices) if 0 not in level_indices: level_indices.add(0) level_indices = level_indices & set(range(self.height)) level_indices = sorted(level_indices)[::-1] # first, remove children for l in level_indices: for node in prev_levels[l]: node.remove_children(reset_parent=False) # then, connect to the right new parent for i in range(len(level_indices) - 1): l = level_indices[i] for node in prev_levels[l]: parent_node = node.ancestor(l - level_indices[i + 1]) parent_node.add_child(node)
[ "def", "keep_levels", "(", "self", ",", "level_indices", ")", ":", "if", "not", "isinstance", "(", "level_indices", ",", "list", ")", ":", "self", ".", "log_exc", "(", "u\"level_indices is not an instance of list\"", ",", "None", ",", "True", ",", "TypeError", ")", "for", "l", "in", "level_indices", ":", "if", "not", "isinstance", "(", "l", ",", "int", ")", ":", "self", ".", "log_exc", "(", "u\"level_indices contains an element not int\"", ",", "None", ",", "True", ",", "TypeError", ")", "prev_levels", "=", "self", ".", "levels", "level_indices", "=", "set", "(", "level_indices", ")", "if", "0", "not", "in", "level_indices", ":", "level_indices", ".", "add", "(", "0", ")", "level_indices", "=", "level_indices", "&", "set", "(", "range", "(", "self", ".", "height", ")", ")", "level_indices", "=", "sorted", "(", "level_indices", ")", "[", ":", ":", "-", "1", "]", "# first, remove children", "for", "l", "in", "level_indices", ":", "for", "node", "in", "prev_levels", "[", "l", "]", ":", "node", ".", "remove_children", "(", "reset_parent", "=", "False", ")", "# then, connect to the right new parent", "for", "i", "in", "range", "(", "len", "(", "level_indices", ")", "-", "1", ")", ":", "l", "=", "level_indices", "[", "i", "]", "for", "node", "in", "prev_levels", "[", "l", "]", ":", "parent_node", "=", "node", ".", "ancestor", "(", "l", "-", "level_indices", "[", "i", "+", "1", "]", ")", "parent_node", ".", "add_child", "(", "node", ")" ]
Rearrange the tree rooted at this node to keep only the given levels. The returned Tree will still be rooted at the current node, i.e. this function implicitly adds ``0`` to ``level_indices``. If ``level_indices`` is an empty list, only this node will be returned, with no children. Elements of ``level_indices`` that do not represent valid level indices (e.g., negative, or too large) will be ignored and no error will be raised. Important: this function modifies the original tree in place! :param list level_indices: the list of int, representing the levels to keep :raises: TypeError if ``level_indices`` is not a list or if it contains an element which is not an int
[ "Rearrange", "the", "tree", "rooted", "at", "this", "node", "to", "keep", "only", "the", "given", "levels", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L478-L521
232,206
readbeyond/aeneas
thirdparty/mfcc.py
s2dctmat
def s2dctmat(nfilt,ncep,freqstep): """Return the 'legacy' not-quite-DCT matrix used by Sphinx""" melcos = numpy.empty((ncep, nfilt), 'double') for i in range(0,ncep): freq = numpy.pi * float(i) / nfilt melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double')) melcos[:,0] = melcos[:,0] * 0.5 return melcos
python
def s2dctmat(nfilt,ncep,freqstep): """Return the 'legacy' not-quite-DCT matrix used by Sphinx""" melcos = numpy.empty((ncep, nfilt), 'double') for i in range(0,ncep): freq = numpy.pi * float(i) / nfilt melcos[i] = numpy.cos(freq * numpy.arange(0.5, float(nfilt)+0.5, 1.0, 'double')) melcos[:,0] = melcos[:,0] * 0.5 return melcos
[ "def", "s2dctmat", "(", "nfilt", ",", "ncep", ",", "freqstep", ")", ":", "melcos", "=", "numpy", ".", "empty", "(", "(", "ncep", ",", "nfilt", ")", ",", "'double'", ")", "for", "i", "in", "range", "(", "0", ",", "ncep", ")", ":", "freq", "=", "numpy", ".", "pi", "*", "float", "(", "i", ")", "/", "nfilt", "melcos", "[", "i", "]", "=", "numpy", ".", "cos", "(", "freq", "*", "numpy", ".", "arange", "(", "0.5", ",", "float", "(", "nfilt", ")", "+", "0.5", ",", "1.0", ",", "'double'", ")", ")", "melcos", "[", ":", ",", "0", "]", "=", "melcos", "[", ":", ",", "0", "]", "*", "0.5", "return", "melcos" ]
Return the 'legacy' not-quite-DCT matrix used by Sphinx
[ "Return", "the", "legacy", "not", "-", "quite", "-", "DCT", "matrix", "used", "by", "Sphinx" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L146-L153
232,207
readbeyond/aeneas
thirdparty/mfcc.py
logspec2s2mfc
def logspec2s2mfc(logspec, ncep=13): """Convert log-power-spectrum bins to MFCC using the 'legacy' Sphinx transform""" nframes, nfilt = logspec.shape melcos = s2dctmat(nfilt, ncep, 1./nfilt) return numpy.dot(logspec, melcos.T) / nfilt
python
def logspec2s2mfc(logspec, ncep=13): """Convert log-power-spectrum bins to MFCC using the 'legacy' Sphinx transform""" nframes, nfilt = logspec.shape melcos = s2dctmat(nfilt, ncep, 1./nfilt) return numpy.dot(logspec, melcos.T) / nfilt
[ "def", "logspec2s2mfc", "(", "logspec", ",", "ncep", "=", "13", ")", ":", "nframes", ",", "nfilt", "=", "logspec", ".", "shape", "melcos", "=", "s2dctmat", "(", "nfilt", ",", "ncep", ",", "1.", "/", "nfilt", ")", "return", "numpy", ".", "dot", "(", "logspec", ",", "melcos", ".", "T", ")", "/", "nfilt" ]
Convert log-power-spectrum bins to MFCC using the 'legacy' Sphinx transform
[ "Convert", "log", "-", "power", "-", "spectrum", "bins", "to", "MFCC", "using", "the", "legacy", "Sphinx", "transform" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L155-L160
232,208
readbeyond/aeneas
thirdparty/mfcc.py
dct
def dct(input, K=13): """Convert log-power-spectrum to MFCC using the orthogonal DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep) return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N)
python
def dct(input, K=13): """Convert log-power-spectrum to MFCC using the orthogonal DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep) return numpy.dot(input, cosmat) * numpy.sqrt(2.0 / N)
[ "def", "dct", "(", "input", ",", "K", "=", "13", ")", ":", "nframes", ",", "N", "=", "input", ".", "shape", "freqstep", "=", "numpy", ".", "pi", "/", "N", "cosmat", "=", "dctmat", "(", "N", ",", "K", ",", "freqstep", ")", "return", "numpy", ".", "dot", "(", "input", ",", "cosmat", ")", "*", "numpy", ".", "sqrt", "(", "2.0", "/", "N", ")" ]
Convert log-power-spectrum to MFCC using the orthogonal DCT-II
[ "Convert", "log", "-", "power", "-", "spectrum", "to", "MFCC", "using", "the", "orthogonal", "DCT", "-", "II" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L174-L179
232,209
readbeyond/aeneas
thirdparty/mfcc.py
dct2
def dct2(input, K=13): """Convert log-power-spectrum to MFCC using the normalized DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep,False) return numpy.dot(input, cosmat) * (2.0 / N)
python
def dct2(input, K=13): """Convert log-power-spectrum to MFCC using the normalized DCT-II""" nframes, N = input.shape freqstep = numpy.pi / N cosmat = dctmat(N,K,freqstep,False) return numpy.dot(input, cosmat) * (2.0 / N)
[ "def", "dct2", "(", "input", ",", "K", "=", "13", ")", ":", "nframes", ",", "N", "=", "input", ".", "shape", "freqstep", "=", "numpy", ".", "pi", "/", "N", "cosmat", "=", "dctmat", "(", "N", ",", "K", ",", "freqstep", ",", "False", ")", "return", "numpy", ".", "dot", "(", "input", ",", "cosmat", ")", "*", "(", "2.0", "/", "N", ")" ]
Convert log-power-spectrum to MFCC using the normalized DCT-II
[ "Convert", "log", "-", "power", "-", "spectrum", "to", "MFCC", "using", "the", "normalized", "DCT", "-", "II" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/thirdparty/mfcc.py#L181-L186
232,210
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.read_properties
def read_properties(self): """ Populate this object by reading the audio properties of the file at the given path. Currently this function uses :class:`~aeneas.ffprobewrapper.FFPROBEWrapper` to get the audio file properties. :raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read """ self.log(u"Reading properties...") # check the file can be read if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) # get the file size self.log([u"Getting file size for '%s'", self.file_path]) self.file_size = gf.file_size(self.file_path) self.log([u"File size for '%s' is '%d'", self.file_path, self.file_size]) # get the audio properties using FFPROBEWrapper try: self.log(u"Reading properties with FFPROBEWrapper...") properties = FFPROBEWrapper( rconf=self.rconf, logger=self.logger ).read_properties(self.file_path) self.log(u"Reading properties with FFPROBEWrapper... done") except FFPROBEPathError: self.log_exc(u"Unable to call ffprobe executable", None, True, AudioFileProbeError) except (FFPROBEUnsupportedFormatError, FFPROBEParsingError): self.log_exc(u"Audio file format not supported by ffprobe", None, True, AudioFileUnsupportedFormatError) # save relevant properties in results inside the audiofile object self.audio_length = TimeValue(properties[FFPROBEWrapper.STDOUT_DURATION]) self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME] self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE]) self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS]) self.log([u"Stored audio_length: '%s'", self.audio_length]) self.log([u"Stored audio_format: '%s'", self.audio_format]) self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate]) self.log([u"Stored audio_channels: '%s'", self.audio_channels]) self.log(u"Reading properties... done")
python
def read_properties(self): """ Populate this object by reading the audio properties of the file at the given path. Currently this function uses :class:`~aeneas.ffprobewrapper.FFPROBEWrapper` to get the audio file properties. :raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read """ self.log(u"Reading properties...") # check the file can be read if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) # get the file size self.log([u"Getting file size for '%s'", self.file_path]) self.file_size = gf.file_size(self.file_path) self.log([u"File size for '%s' is '%d'", self.file_path, self.file_size]) # get the audio properties using FFPROBEWrapper try: self.log(u"Reading properties with FFPROBEWrapper...") properties = FFPROBEWrapper( rconf=self.rconf, logger=self.logger ).read_properties(self.file_path) self.log(u"Reading properties with FFPROBEWrapper... done") except FFPROBEPathError: self.log_exc(u"Unable to call ffprobe executable", None, True, AudioFileProbeError) except (FFPROBEUnsupportedFormatError, FFPROBEParsingError): self.log_exc(u"Audio file format not supported by ffprobe", None, True, AudioFileUnsupportedFormatError) # save relevant properties in results inside the audiofile object self.audio_length = TimeValue(properties[FFPROBEWrapper.STDOUT_DURATION]) self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME] self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE]) self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS]) self.log([u"Stored audio_length: '%s'", self.audio_length]) self.log([u"Stored audio_format: '%s'", self.audio_format]) self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate]) self.log([u"Stored audio_channels: '%s'", self.audio_channels]) self.log(u"Reading properties... done")
[ "def", "read_properties", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Reading properties...\"", ")", "# check the file can be read", "if", "not", "gf", ".", "file_can_be_read", "(", "self", ".", "file_path", ")", ":", "self", ".", "log_exc", "(", "u\"File '%s' cannot be read\"", "%", "(", "self", ".", "file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "# get the file size", "self", ".", "log", "(", "[", "u\"Getting file size for '%s'\"", ",", "self", ".", "file_path", "]", ")", "self", ".", "file_size", "=", "gf", ".", "file_size", "(", "self", ".", "file_path", ")", "self", ".", "log", "(", "[", "u\"File size for '%s' is '%d'\"", ",", "self", ".", "file_path", ",", "self", ".", "file_size", "]", ")", "# get the audio properties using FFPROBEWrapper", "try", ":", "self", ".", "log", "(", "u\"Reading properties with FFPROBEWrapper...\"", ")", "properties", "=", "FFPROBEWrapper", "(", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", ".", "read_properties", "(", "self", ".", "file_path", ")", "self", ".", "log", "(", "u\"Reading properties with FFPROBEWrapper... done\"", ")", "except", "FFPROBEPathError", ":", "self", ".", "log_exc", "(", "u\"Unable to call ffprobe executable\"", ",", "None", ",", "True", ",", "AudioFileProbeError", ")", "except", "(", "FFPROBEUnsupportedFormatError", ",", "FFPROBEParsingError", ")", ":", "self", ".", "log_exc", "(", "u\"Audio file format not supported by ffprobe\"", ",", "None", ",", "True", ",", "AudioFileUnsupportedFormatError", ")", "# save relevant properties in results inside the audiofile object", "self", ".", "audio_length", "=", "TimeValue", "(", "properties", "[", "FFPROBEWrapper", ".", "STDOUT_DURATION", "]", ")", "self", ".", "audio_format", "=", "properties", "[", "FFPROBEWrapper", ".", "STDOUT_CODEC_NAME", "]", "self", ".", "audio_sample_rate", "=", "gf", ".", "safe_int", "(", "properties", "[", "FFPROBEWrapper", ".", "STDOUT_SAMPLE_RATE", "]", ")", "self", ".", "audio_channels", "=", "gf", ".", "safe_int", "(", "properties", "[", "FFPROBEWrapper", ".", "STDOUT_CHANNELS", "]", ")", "self", ".", "log", "(", "[", "u\"Stored audio_length: '%s'\"", ",", "self", ".", "audio_length", "]", ")", "self", ".", "log", "(", "[", "u\"Stored audio_format: '%s'\"", ",", "self", ".", "audio_format", "]", ")", "self", ".", "log", "(", "[", "u\"Stored audio_sample_rate: '%s'\"", ",", "self", ".", "audio_sample_rate", "]", ")", "self", ".", "log", "(", "[", "u\"Stored audio_channels: '%s'\"", ",", "self", ".", "audio_channels", "]", ")", "self", ".", "log", "(", "u\"Reading properties... done\"", ")" ]
Populate this object by reading the audio properties of the file at the given path. Currently this function uses :class:`~aeneas.ffprobewrapper.FFPROBEWrapper` to get the audio file properties. :raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read
[ "Populate", "this", "object", "by", "reading", "the", "audio", "properties", "of", "the", "file", "at", "the", "given", "path", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L330-L376
232,211
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.read_samples_from_file
def read_samples_from_file(self): """ Load the audio samples from file into memory. If ``self.file_format`` is ``None`` or it is not ``("pcm_s16le", 1, self.rconf.sample_rate)``, the file will be first converted to a temporary PCM16 mono WAVE file. Audio data will be read from this temporary file, which will be then deleted from disk immediately. Otherwise, the audio data will be read directly from the given file, which will not be deleted from disk. :raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read """ self.log(u"Loading audio data...") # check the file can be read if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) # determine if we need to convert the audio file convert_audio_file = ( (self.file_format is None) or ( (self.rconf.safety_checks) and (self.file_format != ("pcm_s16le", 1, self.rconf.sample_rate)) ) ) # convert the audio file if needed if convert_audio_file: # convert file to PCM16 mono WAVE with correct sample rate self.log(u"self.file_format is None or not good => converting self.file_path") tmp_handler, tmp_file_path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH]) self.log([u"Temporary PCM16 mono WAVE file: '%s'", tmp_file_path]) try: self.log(u"Converting audio file to mono...") converter = FFMPEGWrapper(rconf=self.rconf, logger=self.logger) converter.convert(self.file_path, tmp_file_path) self.file_format = ("pcm_s16le", 1, self.rconf.sample_rate) self.log(u"Converting audio file to mono... done") except FFMPEGPathError: gf.delete_file(tmp_handler, tmp_file_path) self.log_exc(u"Unable to call ffmpeg executable", None, True, AudioFileConverterError) except OSError: gf.delete_file(tmp_handler, tmp_file_path) self.log_exc(u"Audio file format not supported by ffmpeg", None, True, AudioFileUnsupportedFormatError) else: # read the file directly if self.rconf.safety_checks: self.log(u"self.file_format is good => reading self.file_path directly") else: self.log_warn(u"Safety checks disabled => reading self.file_path directly") tmp_handler = None tmp_file_path = self.file_path # TODO allow calling C extension cwave to read samples faster try: self.audio_format = "pcm16" self.audio_channels = 1 self.audio_sample_rate, self.__samples = scipywavread(tmp_file_path) # scipy reads a sample as an int16_t, that is, a number in [-32768, 32767] # so we convert it to a float64 in [-1, 1] self.__samples = self.__samples.astype("float64") / 32768 self.__samples_capacity = len(self.__samples) self.__samples_length = self.__samples_capacity self._update_length() except ValueError: self.log_exc(u"Audio format not supported by scipywavread", None, True, AudioFileUnsupportedFormatError) # if we converted the audio file, delete the temporary converted audio file if convert_audio_file: gf.delete_file(tmp_handler, tmp_file_path) self.log([u"Deleted temporary audio file: '%s'", tmp_file_path]) self._update_length() self.log([u"Sample length: %.3f", self.audio_length]) self.log([u"Sample rate: %d", self.audio_sample_rate]) self.log([u"Audio format: %s", self.audio_format]) self.log([u"Audio channels: %d", self.audio_channels]) self.log(u"Loading audio data... done")
python
def read_samples_from_file(self): """ Load the audio samples from file into memory. If ``self.file_format`` is ``None`` or it is not ``("pcm_s16le", 1, self.rconf.sample_rate)``, the file will be first converted to a temporary PCM16 mono WAVE file. Audio data will be read from this temporary file, which will be then deleted from disk immediately. Otherwise, the audio data will be read directly from the given file, which will not be deleted from disk. :raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read """ self.log(u"Loading audio data...") # check the file can be read if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) # determine if we need to convert the audio file convert_audio_file = ( (self.file_format is None) or ( (self.rconf.safety_checks) and (self.file_format != ("pcm_s16le", 1, self.rconf.sample_rate)) ) ) # convert the audio file if needed if convert_audio_file: # convert file to PCM16 mono WAVE with correct sample rate self.log(u"self.file_format is None or not good => converting self.file_path") tmp_handler, tmp_file_path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH]) self.log([u"Temporary PCM16 mono WAVE file: '%s'", tmp_file_path]) try: self.log(u"Converting audio file to mono...") converter = FFMPEGWrapper(rconf=self.rconf, logger=self.logger) converter.convert(self.file_path, tmp_file_path) self.file_format = ("pcm_s16le", 1, self.rconf.sample_rate) self.log(u"Converting audio file to mono... done") except FFMPEGPathError: gf.delete_file(tmp_handler, tmp_file_path) self.log_exc(u"Unable to call ffmpeg executable", None, True, AudioFileConverterError) except OSError: gf.delete_file(tmp_handler, tmp_file_path) self.log_exc(u"Audio file format not supported by ffmpeg", None, True, AudioFileUnsupportedFormatError) else: # read the file directly if self.rconf.safety_checks: self.log(u"self.file_format is good => reading self.file_path directly") else: self.log_warn(u"Safety checks disabled => reading self.file_path directly") tmp_handler = None tmp_file_path = self.file_path # TODO allow calling C extension cwave to read samples faster try: self.audio_format = "pcm16" self.audio_channels = 1 self.audio_sample_rate, self.__samples = scipywavread(tmp_file_path) # scipy reads a sample as an int16_t, that is, a number in [-32768, 32767] # so we convert it to a float64 in [-1, 1] self.__samples = self.__samples.astype("float64") / 32768 self.__samples_capacity = len(self.__samples) self.__samples_length = self.__samples_capacity self._update_length() except ValueError: self.log_exc(u"Audio format not supported by scipywavread", None, True, AudioFileUnsupportedFormatError) # if we converted the audio file, delete the temporary converted audio file if convert_audio_file: gf.delete_file(tmp_handler, tmp_file_path) self.log([u"Deleted temporary audio file: '%s'", tmp_file_path]) self._update_length() self.log([u"Sample length: %.3f", self.audio_length]) self.log([u"Sample rate: %d", self.audio_sample_rate]) self.log([u"Audio format: %s", self.audio_format]) self.log([u"Audio channels: %d", self.audio_channels]) self.log(u"Loading audio data... done")
[ "def", "read_samples_from_file", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Loading audio data...\"", ")", "# check the file can be read", "if", "not", "gf", ".", "file_can_be_read", "(", "self", ".", "file_path", ")", ":", "self", ".", "log_exc", "(", "u\"File '%s' cannot be read\"", "%", "(", "self", ".", "file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "# determine if we need to convert the audio file", "convert_audio_file", "=", "(", "(", "self", ".", "file_format", "is", "None", ")", "or", "(", "(", "self", ".", "rconf", ".", "safety_checks", ")", "and", "(", "self", ".", "file_format", "!=", "(", "\"pcm_s16le\"", ",", "1", ",", "self", ".", "rconf", ".", "sample_rate", ")", ")", ")", ")", "# convert the audio file if needed", "if", "convert_audio_file", ":", "# convert file to PCM16 mono WAVE with correct sample rate", "self", ".", "log", "(", "u\"self.file_format is None or not good => converting self.file_path\"", ")", "tmp_handler", ",", "tmp_file_path", "=", "gf", ".", "tmp_file", "(", "suffix", "=", "u\".wav\"", ",", "root", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "TMP_PATH", "]", ")", "self", ".", "log", "(", "[", "u\"Temporary PCM16 mono WAVE file: '%s'\"", ",", "tmp_file_path", "]", ")", "try", ":", "self", ".", "log", "(", "u\"Converting audio file to mono...\"", ")", "converter", "=", "FFMPEGWrapper", "(", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", "converter", ".", "convert", "(", "self", ".", "file_path", ",", "tmp_file_path", ")", "self", ".", "file_format", "=", "(", "\"pcm_s16le\"", ",", "1", ",", "self", ".", "rconf", ".", "sample_rate", ")", "self", ".", "log", "(", "u\"Converting audio file to mono... done\"", ")", "except", "FFMPEGPathError", ":", "gf", ".", "delete_file", "(", "tmp_handler", ",", "tmp_file_path", ")", "self", ".", "log_exc", "(", "u\"Unable to call ffmpeg executable\"", ",", "None", ",", "True", ",", "AudioFileConverterError", ")", "except", "OSError", ":", "gf", ".", "delete_file", "(", "tmp_handler", ",", "tmp_file_path", ")", "self", ".", "log_exc", "(", "u\"Audio file format not supported by ffmpeg\"", ",", "None", ",", "True", ",", "AudioFileUnsupportedFormatError", ")", "else", ":", "# read the file directly", "if", "self", ".", "rconf", ".", "safety_checks", ":", "self", ".", "log", "(", "u\"self.file_format is good => reading self.file_path directly\"", ")", "else", ":", "self", ".", "log_warn", "(", "u\"Safety checks disabled => reading self.file_path directly\"", ")", "tmp_handler", "=", "None", "tmp_file_path", "=", "self", ".", "file_path", "# TODO allow calling C extension cwave to read samples faster", "try", ":", "self", ".", "audio_format", "=", "\"pcm16\"", "self", ".", "audio_channels", "=", "1", "self", ".", "audio_sample_rate", ",", "self", ".", "__samples", "=", "scipywavread", "(", "tmp_file_path", ")", "# scipy reads a sample as an int16_t, that is, a number in [-32768, 32767]", "# so we convert it to a float64 in [-1, 1]", "self", ".", "__samples", "=", "self", ".", "__samples", ".", "astype", "(", "\"float64\"", ")", "/", "32768", "self", ".", "__samples_capacity", "=", "len", "(", "self", ".", "__samples", ")", "self", ".", "__samples_length", "=", "self", ".", "__samples_capacity", "self", ".", "_update_length", "(", ")", "except", "ValueError", ":", "self", ".", "log_exc", "(", "u\"Audio format not supported by scipywavread\"", ",", "None", ",", "True", ",", "AudioFileUnsupportedFormatError", ")", "# if we converted the audio file, delete the temporary converted audio file", "if", "convert_audio_file", ":", "gf", ".", "delete_file", "(", "tmp_handler", ",", "tmp_file_path", ")", "self", ".", "log", "(", "[", "u\"Deleted temporary audio file: '%s'\"", ",", "tmp_file_path", "]", ")", "self", ".", "_update_length", "(", ")", "self", ".", "log", "(", "[", "u\"Sample length: %.3f\"", ",", "self", ".", "audio_length", "]", ")", "self", ".", "log", "(", "[", "u\"Sample rate: %d\"", ",", "self", ".", "audio_sample_rate", "]", ")", "self", ".", "log", "(", "[", "u\"Audio format: %s\"", ",", "self", ".", "audio_format", "]", ")", "self", ".", "log", "(", "[", "u\"Audio channels: %d\"", ",", "self", ".", "audio_channels", "]", ")", "self", ".", "log", "(", "u\"Loading audio data... done\"", ")" ]
Load the audio samples from file into memory. If ``self.file_format`` is ``None`` or it is not ``("pcm_s16le", 1, self.rconf.sample_rate)``, the file will be first converted to a temporary PCM16 mono WAVE file. Audio data will be read from this temporary file, which will be then deleted from disk immediately. Otherwise, the audio data will be read directly from the given file, which will not be deleted from disk. :raises: :class:`~aeneas.audiofile.AudioFileConverterError`: if the path to the ``ffmpeg`` executable cannot be called :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported :raises: OSError: if the audio file cannot be read
[ "Load", "the", "audio", "samples", "from", "file", "into", "memory", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L378-L464
232,212
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.preallocate_memory
def preallocate_memory(self, capacity): """ Preallocate memory to store audio samples, to avoid repeated new allocations and copies while performing several consecutive append operations. If ``self.__samples`` is not initialized, it will become an array of ``capacity`` zeros. If ``capacity`` is larger than the current capacity, the current ``self.__samples`` will be extended with zeros. If ``capacity`` is smaller than the current capacity, the first ``capacity`` values of ``self.__samples`` will be retained. :param int capacity: the new capacity, in number of samples :raises: ValueError: if ``capacity`` is negative .. versionadded:: 1.5.0 """ if capacity < 0: raise ValueError(u"The capacity value cannot be negative") if self.__samples is None: self.log(u"Not initialized") self.__samples = numpy.zeros(capacity) self.__samples_length = 0 else: self.log([u"Previous sample length was (samples): %d", self.__samples_length]) self.log([u"Previous sample capacity was (samples): %d", self.__samples_capacity]) self.__samples = numpy.resize(self.__samples, capacity) self.__samples_length = min(self.__samples_length, capacity) self.__samples_capacity = capacity self.log([u"Current sample capacity is (samples): %d", self.__samples_capacity])
python
def preallocate_memory(self, capacity): """ Preallocate memory to store audio samples, to avoid repeated new allocations and copies while performing several consecutive append operations. If ``self.__samples`` is not initialized, it will become an array of ``capacity`` zeros. If ``capacity`` is larger than the current capacity, the current ``self.__samples`` will be extended with zeros. If ``capacity`` is smaller than the current capacity, the first ``capacity`` values of ``self.__samples`` will be retained. :param int capacity: the new capacity, in number of samples :raises: ValueError: if ``capacity`` is negative .. versionadded:: 1.5.0 """ if capacity < 0: raise ValueError(u"The capacity value cannot be negative") if self.__samples is None: self.log(u"Not initialized") self.__samples = numpy.zeros(capacity) self.__samples_length = 0 else: self.log([u"Previous sample length was (samples): %d", self.__samples_length]) self.log([u"Previous sample capacity was (samples): %d", self.__samples_capacity]) self.__samples = numpy.resize(self.__samples, capacity) self.__samples_length = min(self.__samples_length, capacity) self.__samples_capacity = capacity self.log([u"Current sample capacity is (samples): %d", self.__samples_capacity])
[ "def", "preallocate_memory", "(", "self", ",", "capacity", ")", ":", "if", "capacity", "<", "0", ":", "raise", "ValueError", "(", "u\"The capacity value cannot be negative\"", ")", "if", "self", ".", "__samples", "is", "None", ":", "self", ".", "log", "(", "u\"Not initialized\"", ")", "self", ".", "__samples", "=", "numpy", ".", "zeros", "(", "capacity", ")", "self", ".", "__samples_length", "=", "0", "else", ":", "self", ".", "log", "(", "[", "u\"Previous sample length was (samples): %d\"", ",", "self", ".", "__samples_length", "]", ")", "self", ".", "log", "(", "[", "u\"Previous sample capacity was (samples): %d\"", ",", "self", ".", "__samples_capacity", "]", ")", "self", ".", "__samples", "=", "numpy", ".", "resize", "(", "self", ".", "__samples", ",", "capacity", ")", "self", ".", "__samples_length", "=", "min", "(", "self", ".", "__samples_length", ",", "capacity", ")", "self", ".", "__samples_capacity", "=", "capacity", "self", ".", "log", "(", "[", "u\"Current sample capacity is (samples): %d\"", ",", "self", ".", "__samples_capacity", "]", ")" ]
Preallocate memory to store audio samples, to avoid repeated new allocations and copies while performing several consecutive append operations. If ``self.__samples`` is not initialized, it will become an array of ``capacity`` zeros. If ``capacity`` is larger than the current capacity, the current ``self.__samples`` will be extended with zeros. If ``capacity`` is smaller than the current capacity, the first ``capacity`` values of ``self.__samples`` will be retained. :param int capacity: the new capacity, in number of samples :raises: ValueError: if ``capacity`` is negative .. versionadded:: 1.5.0
[ "Preallocate", "memory", "to", "store", "audio", "samples", "to", "avoid", "repeated", "new", "allocations", "and", "copies", "while", "performing", "several", "consecutive", "append", "operations", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L466-L499
232,213
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.minimize_memory
def minimize_memory(self): """ Reduce the allocated memory to the minimum required to store the current audio samples. This function is meant to be called when building a wave incrementally, after the last append operation. .. versionadded:: 1.5.0 """ if self.__samples is None: self.log(u"Not initialized, returning") else: self.log(u"Initialized, minimizing memory...") self.preallocate_memory(self.__samples_length) self.log(u"Initialized, minimizing memory... done")
python
def minimize_memory(self): """ Reduce the allocated memory to the minimum required to store the current audio samples. This function is meant to be called when building a wave incrementally, after the last append operation. .. versionadded:: 1.5.0 """ if self.__samples is None: self.log(u"Not initialized, returning") else: self.log(u"Initialized, minimizing memory...") self.preallocate_memory(self.__samples_length) self.log(u"Initialized, minimizing memory... done")
[ "def", "minimize_memory", "(", "self", ")", ":", "if", "self", ".", "__samples", "is", "None", ":", "self", ".", "log", "(", "u\"Not initialized, returning\"", ")", "else", ":", "self", ".", "log", "(", "u\"Initialized, minimizing memory...\"", ")", "self", ".", "preallocate_memory", "(", "self", ".", "__samples_length", ")", "self", ".", "log", "(", "u\"Initialized, minimizing memory... done\"", ")" ]
Reduce the allocated memory to the minimum required to store the current audio samples. This function is meant to be called when building a wave incrementally, after the last append operation. .. versionadded:: 1.5.0
[ "Reduce", "the", "allocated", "memory", "to", "the", "minimum", "required", "to", "store", "the", "current", "audio", "samples", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L501-L517
232,214
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.add_samples
def add_samples(self, samples, reverse=False): """ Concatenate the given new samples to the current audio data. This function initializes the memory if no audio data is present already. If ``reverse`` is ``True``, the new samples will be reversed and then concatenated. :param samples: the new samples to be concatenated :type samples: :class:`numpy.ndarray` (1D) :param bool reverse: if ``True``, concatenate new samples after reversing them .. versionadded:: 1.2.1 """ self.log(u"Adding samples...") samples_length = len(samples) current_length = self.__samples_length future_length = current_length + samples_length if (self.__samples is None) or (self.__samples_capacity < future_length): self.preallocate_memory(2 * future_length) if reverse: self.__samples[current_length:future_length] = samples[::-1] else: self.__samples[current_length:future_length] = samples[:] self.__samples_length = future_length self._update_length() self.log(u"Adding samples... done")
python
def add_samples(self, samples, reverse=False): """ Concatenate the given new samples to the current audio data. This function initializes the memory if no audio data is present already. If ``reverse`` is ``True``, the new samples will be reversed and then concatenated. :param samples: the new samples to be concatenated :type samples: :class:`numpy.ndarray` (1D) :param bool reverse: if ``True``, concatenate new samples after reversing them .. versionadded:: 1.2.1 """ self.log(u"Adding samples...") samples_length = len(samples) current_length = self.__samples_length future_length = current_length + samples_length if (self.__samples is None) or (self.__samples_capacity < future_length): self.preallocate_memory(2 * future_length) if reverse: self.__samples[current_length:future_length] = samples[::-1] else: self.__samples[current_length:future_length] = samples[:] self.__samples_length = future_length self._update_length() self.log(u"Adding samples... done")
[ "def", "add_samples", "(", "self", ",", "samples", ",", "reverse", "=", "False", ")", ":", "self", ".", "log", "(", "u\"Adding samples...\"", ")", "samples_length", "=", "len", "(", "samples", ")", "current_length", "=", "self", ".", "__samples_length", "future_length", "=", "current_length", "+", "samples_length", "if", "(", "self", ".", "__samples", "is", "None", ")", "or", "(", "self", ".", "__samples_capacity", "<", "future_length", ")", ":", "self", ".", "preallocate_memory", "(", "2", "*", "future_length", ")", "if", "reverse", ":", "self", ".", "__samples", "[", "current_length", ":", "future_length", "]", "=", "samples", "[", ":", ":", "-", "1", "]", "else", ":", "self", ".", "__samples", "[", "current_length", ":", "future_length", "]", "=", "samples", "[", ":", "]", "self", ".", "__samples_length", "=", "future_length", "self", ".", "_update_length", "(", ")", "self", ".", "log", "(", "u\"Adding samples... done\"", ")" ]
Concatenate the given new samples to the current audio data. This function initializes the memory if no audio data is present already. If ``reverse`` is ``True``, the new samples will be reversed and then concatenated. :param samples: the new samples to be concatenated :type samples: :class:`numpy.ndarray` (1D) :param bool reverse: if ``True``, concatenate new samples after reversing them .. versionadded:: 1.2.1
[ "Concatenate", "the", "given", "new", "samples", "to", "the", "current", "audio", "data", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L519-L547
232,215
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.reverse
def reverse(self): """ Reverse the audio data. :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0 """ if self.__samples is None: if self.file_path is None: self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError) else: self.read_samples_from_file() self.log(u"Reversing...") self.__samples[0:self.__samples_length] = numpy.flipud(self.__samples[0:self.__samples_length]) self.log(u"Reversing... done")
python
def reverse(self): """ Reverse the audio data. :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0 """ if self.__samples is None: if self.file_path is None: self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError) else: self.read_samples_from_file() self.log(u"Reversing...") self.__samples[0:self.__samples_length] = numpy.flipud(self.__samples[0:self.__samples_length]) self.log(u"Reversing... done")
[ "def", "reverse", "(", "self", ")", ":", "if", "self", ".", "__samples", "is", "None", ":", "if", "self", ".", "file_path", "is", "None", ":", "self", ".", "log_exc", "(", "u\"AudioFile object not initialized\"", ",", "None", ",", "True", ",", "AudioFileNotInitializedError", ")", "else", ":", "self", ".", "read_samples_from_file", "(", ")", "self", ".", "log", "(", "u\"Reversing...\"", ")", "self", ".", "__samples", "[", "0", ":", "self", ".", "__samples_length", "]", "=", "numpy", ".", "flipud", "(", "self", ".", "__samples", "[", "0", ":", "self", ".", "__samples_length", "]", ")", "self", ".", "log", "(", "u\"Reversing... done\"", ")" ]
Reverse the audio data. :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0
[ "Reverse", "the", "audio", "data", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L549-L564
232,216
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.trim
def trim(self, begin=None, length=None): """ Get a slice of the audio data of ``length`` seconds, starting from ``begin`` seconds. If audio data is not loaded, load it and then slice it. :param begin: the start position, in seconds :type begin: :class:`~aeneas.exacttiming.TimeValue` :param length: the position, in seconds :type length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` .. versionadded:: 1.2.0 """ for variable, name in [(begin, "begin"), (length, "length")]: if (variable is not None) and (not isinstance(variable, TimeValue)): raise TypeError(u"%s is not None or TimeValue" % name) self.log(u"Trimming...") if (begin is None) and (length is None): self.log(u"begin and length are both None: nothing to do") else: if begin is None: begin = TimeValue("0.000") self.log([u"begin was None, now set to %.3f", begin]) begin = min(max(TimeValue("0.000"), begin), self.audio_length) self.log([u"begin is %.3f", begin]) if length is None: length = self.audio_length - begin self.log([u"length was None, now set to %.3f", length]) length = min(max(TimeValue("0.000"), length), self.audio_length - begin) self.log([u"length is %.3f", length]) begin_index = int(begin * self.audio_sample_rate) end_index = int((begin + length) * self.audio_sample_rate) new_idx = end_index - begin_index self.__samples[0:new_idx] = self.__samples[begin_index:end_index] self.__samples_length = new_idx self._update_length() self.log(u"Trimming... done")
python
def trim(self, begin=None, length=None): """ Get a slice of the audio data of ``length`` seconds, starting from ``begin`` seconds. If audio data is not loaded, load it and then slice it. :param begin: the start position, in seconds :type begin: :class:`~aeneas.exacttiming.TimeValue` :param length: the position, in seconds :type length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` .. versionadded:: 1.2.0 """ for variable, name in [(begin, "begin"), (length, "length")]: if (variable is not None) and (not isinstance(variable, TimeValue)): raise TypeError(u"%s is not None or TimeValue" % name) self.log(u"Trimming...") if (begin is None) and (length is None): self.log(u"begin and length are both None: nothing to do") else: if begin is None: begin = TimeValue("0.000") self.log([u"begin was None, now set to %.3f", begin]) begin = min(max(TimeValue("0.000"), begin), self.audio_length) self.log([u"begin is %.3f", begin]) if length is None: length = self.audio_length - begin self.log([u"length was None, now set to %.3f", length]) length = min(max(TimeValue("0.000"), length), self.audio_length - begin) self.log([u"length is %.3f", length]) begin_index = int(begin * self.audio_sample_rate) end_index = int((begin + length) * self.audio_sample_rate) new_idx = end_index - begin_index self.__samples[0:new_idx] = self.__samples[begin_index:end_index] self.__samples_length = new_idx self._update_length() self.log(u"Trimming... done")
[ "def", "trim", "(", "self", ",", "begin", "=", "None", ",", "length", "=", "None", ")", ":", "for", "variable", ",", "name", "in", "[", "(", "begin", ",", "\"begin\"", ")", ",", "(", "length", ",", "\"length\"", ")", "]", ":", "if", "(", "variable", "is", "not", "None", ")", "and", "(", "not", "isinstance", "(", "variable", ",", "TimeValue", ")", ")", ":", "raise", "TypeError", "(", "u\"%s is not None or TimeValue\"", "%", "name", ")", "self", ".", "log", "(", "u\"Trimming...\"", ")", "if", "(", "begin", "is", "None", ")", "and", "(", "length", "is", "None", ")", ":", "self", ".", "log", "(", "u\"begin and length are both None: nothing to do\"", ")", "else", ":", "if", "begin", "is", "None", ":", "begin", "=", "TimeValue", "(", "\"0.000\"", ")", "self", ".", "log", "(", "[", "u\"begin was None, now set to %.3f\"", ",", "begin", "]", ")", "begin", "=", "min", "(", "max", "(", "TimeValue", "(", "\"0.000\"", ")", ",", "begin", ")", ",", "self", ".", "audio_length", ")", "self", ".", "log", "(", "[", "u\"begin is %.3f\"", ",", "begin", "]", ")", "if", "length", "is", "None", ":", "length", "=", "self", ".", "audio_length", "-", "begin", "self", ".", "log", "(", "[", "u\"length was None, now set to %.3f\"", ",", "length", "]", ")", "length", "=", "min", "(", "max", "(", "TimeValue", "(", "\"0.000\"", ")", ",", "length", ")", ",", "self", ".", "audio_length", "-", "begin", ")", "self", ".", "log", "(", "[", "u\"length is %.3f\"", ",", "length", "]", ")", "begin_index", "=", "int", "(", "begin", "*", "self", ".", "audio_sample_rate", ")", "end_index", "=", "int", "(", "(", "begin", "+", "length", ")", "*", "self", ".", "audio_sample_rate", ")", "new_idx", "=", "end_index", "-", "begin_index", "self", ".", "__samples", "[", "0", ":", "new_idx", "]", "=", "self", ".", "__samples", "[", "begin_index", ":", "end_index", "]", "self", ".", "__samples_length", "=", "new_idx", "self", ".", "_update_length", "(", ")", "self", ".", "log", "(", "u\"Trimming... done\"", ")" ]
Get a slice of the audio data of ``length`` seconds, starting from ``begin`` seconds. If audio data is not loaded, load it and then slice it. :param begin: the start position, in seconds :type begin: :class:`~aeneas.exacttiming.TimeValue` :param length: the position, in seconds :type length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` .. versionadded:: 1.2.0
[ "Get", "a", "slice", "of", "the", "audio", "data", "of", "length", "seconds", "starting", "from", "begin", "seconds", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L566-L605
232,217
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.write
def write(self, file_path): """ Write the audio data to file. Return ``True`` on success, or ``False`` otherwise. :param string file_path: the path of the output file to be written :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0 """ if self.__samples is None: if self.file_path is None: self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError) else: self.read_samples_from_file() self.log([u"Writing audio file '%s'...", file_path]) try: # our value is a float64 in [-1, 1] # scipy writes the sample as an int16_t, that is, a number in [-32768, 32767] data = (self.audio_samples * 32768).astype("int16") scipywavwrite(file_path, self.audio_sample_rate, data) except Exception as exc: self.log_exc(u"Error writing audio file to '%s'" % (file_path), exc, True, OSError) self.log([u"Writing audio file '%s'... done", file_path])
python
def write(self, file_path): """ Write the audio data to file. Return ``True`` on success, or ``False`` otherwise. :param string file_path: the path of the output file to be written :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0 """ if self.__samples is None: if self.file_path is None: self.log_exc(u"AudioFile object not initialized", None, True, AudioFileNotInitializedError) else: self.read_samples_from_file() self.log([u"Writing audio file '%s'...", file_path]) try: # our value is a float64 in [-1, 1] # scipy writes the sample as an int16_t, that is, a number in [-32768, 32767] data = (self.audio_samples * 32768).astype("int16") scipywavwrite(file_path, self.audio_sample_rate, data) except Exception as exc: self.log_exc(u"Error writing audio file to '%s'" % (file_path), exc, True, OSError) self.log([u"Writing audio file '%s'... done", file_path])
[ "def", "write", "(", "self", ",", "file_path", ")", ":", "if", "self", ".", "__samples", "is", "None", ":", "if", "self", ".", "file_path", "is", "None", ":", "self", ".", "log_exc", "(", "u\"AudioFile object not initialized\"", ",", "None", ",", "True", ",", "AudioFileNotInitializedError", ")", "else", ":", "self", ".", "read_samples_from_file", "(", ")", "self", ".", "log", "(", "[", "u\"Writing audio file '%s'...\"", ",", "file_path", "]", ")", "try", ":", "# our value is a float64 in [-1, 1]", "# scipy writes the sample as an int16_t, that is, a number in [-32768, 32767]", "data", "=", "(", "self", ".", "audio_samples", "*", "32768", ")", ".", "astype", "(", "\"int16\"", ")", "scipywavwrite", "(", "file_path", ",", "self", ".", "audio_sample_rate", ",", "data", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"Error writing audio file to '%s'\"", "%", "(", "file_path", ")", ",", "exc", ",", "True", ",", "OSError", ")", "self", ".", "log", "(", "[", "u\"Writing audio file '%s'... done\"", ",", "file_path", "]", ")" ]
Write the audio data to file. Return ``True`` on success, or ``False`` otherwise. :param string file_path: the path of the output file to be written :raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet .. versionadded:: 1.2.0
[ "Write", "the", "audio", "data", "to", "file", ".", "Return", "True", "on", "success", "or", "False", "otherwise", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L607-L630
232,218
readbeyond/aeneas
aeneas/audiofile.py
AudioFile.clear_data
def clear_data(self): """ Clear the audio data, freeing memory. """ self.log(u"Clear audio_data") self.__samples_capacity = 0 self.__samples_length = 0 self.__samples = None
python
def clear_data(self): """ Clear the audio data, freeing memory. """ self.log(u"Clear audio_data") self.__samples_capacity = 0 self.__samples_length = 0 self.__samples = None
[ "def", "clear_data", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Clear audio_data\"", ")", "self", ".", "__samples_capacity", "=", "0", "self", ".", "__samples_length", "=", "0", "self", ".", "__samples", "=", "None" ]
Clear the audio data, freeing memory.
[ "Clear", "the", "audio", "data", "freeing", "memory", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L632-L639
232,219
readbeyond/aeneas
aeneas/audiofile.py
AudioFile._update_length
def _update_length(self): """ Update the audio length property, according to the length of the current audio data and audio sample rate. This function fails silently if one of the two is ``None``. """ if (self.audio_sample_rate is not None) and (self.__samples is not None): # NOTE computing TimeValue (... / ...) yields wrong results, # see issue #168 # self.audio_length = TimeValue(self.__samples_length / self.audio_sample_rate) self.audio_length = TimeValue(self.__samples_length) / TimeValue(self.audio_sample_rate)
python
def _update_length(self): """ Update the audio length property, according to the length of the current audio data and audio sample rate. This function fails silently if one of the two is ``None``. """ if (self.audio_sample_rate is not None) and (self.__samples is not None): # NOTE computing TimeValue (... / ...) yields wrong results, # see issue #168 # self.audio_length = TimeValue(self.__samples_length / self.audio_sample_rate) self.audio_length = TimeValue(self.__samples_length) / TimeValue(self.audio_sample_rate)
[ "def", "_update_length", "(", "self", ")", ":", "if", "(", "self", ".", "audio_sample_rate", "is", "not", "None", ")", "and", "(", "self", ".", "__samples", "is", "not", "None", ")", ":", "# NOTE computing TimeValue (... / ...) yields wrong results,", "# see issue #168", "# self.audio_length = TimeValue(self.__samples_length / self.audio_sample_rate)", "self", ".", "audio_length", "=", "TimeValue", "(", "self", ".", "__samples_length", ")", "/", "TimeValue", "(", "self", ".", "audio_sample_rate", ")" ]
Update the audio length property, according to the length of the current audio data and audio sample rate. This function fails silently if one of the two is ``None``.
[ "Update", "the", "audio", "length", "property", "according", "to", "the", "length", "of", "the", "current", "audio", "data", "and", "audio", "sample", "rate", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofile.py#L641-L653
232,220
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.masked_middle_mfcc
def masked_middle_mfcc(self): """ Return the MFCC speech frames in the MIDDLE portion of the wave. :rtype: :class:`numpy.ndarray` (2D) """ begin, end = self._masked_middle_begin_end() return (self.masked_mfcc)[:, begin:end]
python
def masked_middle_mfcc(self): """ Return the MFCC speech frames in the MIDDLE portion of the wave. :rtype: :class:`numpy.ndarray` (2D) """ begin, end = self._masked_middle_begin_end() return (self.masked_mfcc)[:, begin:end]
[ "def", "masked_middle_mfcc", "(", "self", ")", ":", "begin", ",", "end", "=", "self", ".", "_masked_middle_begin_end", "(", ")", "return", "(", "self", ".", "masked_mfcc", ")", "[", ":", ",", "begin", ":", "end", "]" ]
Return the MFCC speech frames in the MIDDLE portion of the wave. :rtype: :class:`numpy.ndarray` (2D)
[ "Return", "the", "MFCC", "speech", "frames", "in", "the", "MIDDLE", "portion", "of", "the", "wave", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L327-L335
232,221
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.masked_middle_map
def masked_middle_map(self): """ Return the map from the MFCC speech frame indices in the MIDDLE portion of the wave to the MFCC FULL frame indices. :rtype: :class:`numpy.ndarray` (1D) """ begin, end = self._masked_middle_begin_end() return self.__mfcc_mask_map[begin:end]
python
def masked_middle_map(self): """ Return the map from the MFCC speech frame indices in the MIDDLE portion of the wave to the MFCC FULL frame indices. :rtype: :class:`numpy.ndarray` (1D) """ begin, end = self._masked_middle_begin_end() return self.__mfcc_mask_map[begin:end]
[ "def", "masked_middle_map", "(", "self", ")", ":", "begin", ",", "end", "=", "self", ".", "_masked_middle_begin_end", "(", ")", "return", "self", ".", "__mfcc_mask_map", "[", "begin", ":", "end", "]" ]
Return the map from the MFCC speech frame indices in the MIDDLE portion of the wave to the MFCC FULL frame indices. :rtype: :class:`numpy.ndarray` (1D)
[ "Return", "the", "map", "from", "the", "MFCC", "speech", "frame", "indices", "in", "the", "MIDDLE", "portion", "of", "the", "wave", "to", "the", "MFCC", "FULL", "frame", "indices", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L349-L359
232,222
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC._binary_search_intervals
def _binary_search_intervals(cls, intervals, index): """ Binary search for the interval containing index, assuming there is such an interval. This function should never return ``None``. """ start = 0 end = len(intervals) - 1 while start <= end: middle_index = start + ((end - start) // 2) middle = intervals[middle_index] if (middle[0] <= index) and (index < middle[1]): return middle elif middle[0] > index: end = middle_index - 1 else: start = middle_index + 1 return None
python
def _binary_search_intervals(cls, intervals, index): """ Binary search for the interval containing index, assuming there is such an interval. This function should never return ``None``. """ start = 0 end = len(intervals) - 1 while start <= end: middle_index = start + ((end - start) // 2) middle = intervals[middle_index] if (middle[0] <= index) and (index < middle[1]): return middle elif middle[0] > index: end = middle_index - 1 else: start = middle_index + 1 return None
[ "def", "_binary_search_intervals", "(", "cls", ",", "intervals", ",", "index", ")", ":", "start", "=", "0", "end", "=", "len", "(", "intervals", ")", "-", "1", "while", "start", "<=", "end", ":", "middle_index", "=", "start", "+", "(", "(", "end", "-", "start", ")", "//", "2", ")", "middle", "=", "intervals", "[", "middle_index", "]", "if", "(", "middle", "[", "0", "]", "<=", "index", ")", "and", "(", "index", "<", "middle", "[", "1", "]", ")", ":", "return", "middle", "elif", "middle", "[", "0", "]", ">", "index", ":", "end", "=", "middle_index", "-", "1", "else", ":", "start", "=", "middle_index", "+", "1", "return", "None" ]
Binary search for the interval containing index, assuming there is such an interval. This function should never return ``None``.
[ "Binary", "search", "for", "the", "interval", "containing", "index", "assuming", "there", "is", "such", "an", "interval", ".", "This", "function", "should", "never", "return", "None", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L423-L440
232,223
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.middle_begin
def middle_begin(self, index): """ Set the index where MIDDLE starts. :param int index: the new index for MIDDLE begin """ if (index < 0) or (index > self.all_length): raise ValueError(u"The given index is not valid") self.__middle_begin = index
python
def middle_begin(self, index): """ Set the index where MIDDLE starts. :param int index: the new index for MIDDLE begin """ if (index < 0) or (index > self.all_length): raise ValueError(u"The given index is not valid") self.__middle_begin = index
[ "def", "middle_begin", "(", "self", ",", "index", ")", ":", "if", "(", "index", "<", "0", ")", "or", "(", "index", ">", "self", ".", "all_length", ")", ":", "raise", "ValueError", "(", "u\"The given index is not valid\"", ")", "self", ".", "__middle_begin", "=", "index" ]
Set the index where MIDDLE starts. :param int index: the new index for MIDDLE begin
[ "Set", "the", "index", "where", "MIDDLE", "starts", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L452-L460
232,224
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC._compute_mfcc_c_extension
def _compute_mfcc_c_extension(self): """ Compute MFCCs using the Python C extension cmfcc. """ self.log(u"Computing MFCCs using C extension...") try: self.log(u"Importing cmfcc...") import aeneas.cmfcc.cmfcc self.log(u"Importing cmfcc... done") self.__mfcc = (aeneas.cmfcc.cmfcc.compute_from_data( self.audio_file.audio_samples, self.audio_file.audio_sample_rate, self.rconf[RuntimeConfiguration.MFCC_FILTERS], self.rconf[RuntimeConfiguration.MFCC_SIZE], self.rconf[RuntimeConfiguration.MFCC_FFT_ORDER], self.rconf[RuntimeConfiguration.MFCC_LOWER_FREQUENCY], self.rconf[RuntimeConfiguration.MFCC_UPPER_FREQUENCY], self.rconf[RuntimeConfiguration.MFCC_EMPHASIS_FACTOR], self.rconf[RuntimeConfiguration.MFCC_WINDOW_LENGTH], self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT] )[0]).transpose() self.log(u"Computing MFCCs using C extension... done") return (True, None) except Exception as exc: self.log_exc(u"An unexpected error occurred while running cmfcc", exc, False, None) return (False, None)
python
def _compute_mfcc_c_extension(self): """ Compute MFCCs using the Python C extension cmfcc. """ self.log(u"Computing MFCCs using C extension...") try: self.log(u"Importing cmfcc...") import aeneas.cmfcc.cmfcc self.log(u"Importing cmfcc... done") self.__mfcc = (aeneas.cmfcc.cmfcc.compute_from_data( self.audio_file.audio_samples, self.audio_file.audio_sample_rate, self.rconf[RuntimeConfiguration.MFCC_FILTERS], self.rconf[RuntimeConfiguration.MFCC_SIZE], self.rconf[RuntimeConfiguration.MFCC_FFT_ORDER], self.rconf[RuntimeConfiguration.MFCC_LOWER_FREQUENCY], self.rconf[RuntimeConfiguration.MFCC_UPPER_FREQUENCY], self.rconf[RuntimeConfiguration.MFCC_EMPHASIS_FACTOR], self.rconf[RuntimeConfiguration.MFCC_WINDOW_LENGTH], self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT] )[0]).transpose() self.log(u"Computing MFCCs using C extension... done") return (True, None) except Exception as exc: self.log_exc(u"An unexpected error occurred while running cmfcc", exc, False, None) return (False, None)
[ "def", "_compute_mfcc_c_extension", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Computing MFCCs using C extension...\"", ")", "try", ":", "self", ".", "log", "(", "u\"Importing cmfcc...\"", ")", "import", "aeneas", ".", "cmfcc", ".", "cmfcc", "self", ".", "log", "(", "u\"Importing cmfcc... done\"", ")", "self", ".", "__mfcc", "=", "(", "aeneas", ".", "cmfcc", ".", "cmfcc", ".", "compute_from_data", "(", "self", ".", "audio_file", ".", "audio_samples", ",", "self", ".", "audio_file", ".", "audio_sample_rate", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_FILTERS", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_SIZE", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_FFT_ORDER", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_LOWER_FREQUENCY", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_UPPER_FREQUENCY", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_EMPHASIS_FACTOR", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_WINDOW_LENGTH", "]", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "MFCC_WINDOW_SHIFT", "]", ")", "[", "0", "]", ")", ".", "transpose", "(", ")", "self", ".", "log", "(", "u\"Computing MFCCs using C extension... done\"", ")", "return", "(", "True", ",", "None", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"An unexpected error occurred while running cmfcc\"", ",", "exc", ",", "False", ",", "None", ")", "return", "(", "False", ",", "None", ")" ]
Compute MFCCs using the Python C extension cmfcc.
[ "Compute", "MFCCs", "using", "the", "Python", "C", "extension", "cmfcc", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L509-L534
232,225
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC._compute_mfcc_pure_python
def _compute_mfcc_pure_python(self): """ Compute MFCCs using the pure Python code. """ self.log(u"Computing MFCCs using pure Python code...") try: self.__mfcc = MFCC( rconf=self.rconf, logger=self.logger ).compute_from_data( self.audio_file.audio_samples, self.audio_file.audio_sample_rate ).transpose() self.log(u"Computing MFCCs using pure Python code... done") return (True, None) except Exception as exc: self.log_exc(u"An unexpected error occurred while running pure Python code", exc, False, None) return (False, None)
python
def _compute_mfcc_pure_python(self): """ Compute MFCCs using the pure Python code. """ self.log(u"Computing MFCCs using pure Python code...") try: self.__mfcc = MFCC( rconf=self.rconf, logger=self.logger ).compute_from_data( self.audio_file.audio_samples, self.audio_file.audio_sample_rate ).transpose() self.log(u"Computing MFCCs using pure Python code... done") return (True, None) except Exception as exc: self.log_exc(u"An unexpected error occurred while running pure Python code", exc, False, None) return (False, None)
[ "def", "_compute_mfcc_pure_python", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Computing MFCCs using pure Python code...\"", ")", "try", ":", "self", ".", "__mfcc", "=", "MFCC", "(", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", ".", "compute_from_data", "(", "self", ".", "audio_file", ".", "audio_samples", ",", "self", ".", "audio_file", ".", "audio_sample_rate", ")", ".", "transpose", "(", ")", "self", ".", "log", "(", "u\"Computing MFCCs using pure Python code... done\"", ")", "return", "(", "True", ",", "None", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"An unexpected error occurred while running pure Python code\"", ",", "exc", ",", "False", ",", "None", ")", "return", "(", "False", ",", "None", ")" ]
Compute MFCCs using the pure Python code.
[ "Compute", "MFCCs", "using", "the", "pure", "Python", "code", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L536-L553
232,226
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.reverse
def reverse(self): """ Reverse the audio file. The reversing is done efficiently using NumPy views inplace instead of swapping values. Only speech and nonspeech intervals are actually recomputed as Python lists. """ self.log(u"Reversing...") all_length = self.all_length self.__mfcc = self.__mfcc[:, ::-1] tmp = self.__middle_end self.__middle_end = all_length - self.__middle_begin self.__middle_begin = all_length - tmp if self.__mfcc_mask is not None: self.__mfcc_mask = self.__mfcc_mask[::-1] # equivalent to # self.__mfcc_mask_map = ((all_length - 1) - self.__mfcc_mask_map)[::-1] # but done in place using NumPy view self.__mfcc_mask_map *= -1 self.__mfcc_mask_map += all_length - 1 self.__mfcc_mask_map = self.__mfcc_mask_map[::-1] self.__speech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__speech_intervals[::-1]] self.__nonspeech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__nonspeech_intervals[::-1]] self.is_reversed = not self.is_reversed self.log(u"Reversing...done")
python
def reverse(self): """ Reverse the audio file. The reversing is done efficiently using NumPy views inplace instead of swapping values. Only speech and nonspeech intervals are actually recomputed as Python lists. """ self.log(u"Reversing...") all_length = self.all_length self.__mfcc = self.__mfcc[:, ::-1] tmp = self.__middle_end self.__middle_end = all_length - self.__middle_begin self.__middle_begin = all_length - tmp if self.__mfcc_mask is not None: self.__mfcc_mask = self.__mfcc_mask[::-1] # equivalent to # self.__mfcc_mask_map = ((all_length - 1) - self.__mfcc_mask_map)[::-1] # but done in place using NumPy view self.__mfcc_mask_map *= -1 self.__mfcc_mask_map += all_length - 1 self.__mfcc_mask_map = self.__mfcc_mask_map[::-1] self.__speech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__speech_intervals[::-1]] self.__nonspeech_intervals = [(all_length - i[1], all_length - i[0]) for i in self.__nonspeech_intervals[::-1]] self.is_reversed = not self.is_reversed self.log(u"Reversing...done")
[ "def", "reverse", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Reversing...\"", ")", "all_length", "=", "self", ".", "all_length", "self", ".", "__mfcc", "=", "self", ".", "__mfcc", "[", ":", ",", ":", ":", "-", "1", "]", "tmp", "=", "self", ".", "__middle_end", "self", ".", "__middle_end", "=", "all_length", "-", "self", ".", "__middle_begin", "self", ".", "__middle_begin", "=", "all_length", "-", "tmp", "if", "self", ".", "__mfcc_mask", "is", "not", "None", ":", "self", ".", "__mfcc_mask", "=", "self", ".", "__mfcc_mask", "[", ":", ":", "-", "1", "]", "# equivalent to", "# self.__mfcc_mask_map = ((all_length - 1) - self.__mfcc_mask_map)[::-1]", "# but done in place using NumPy view", "self", ".", "__mfcc_mask_map", "*=", "-", "1", "self", ".", "__mfcc_mask_map", "+=", "all_length", "-", "1", "self", ".", "__mfcc_mask_map", "=", "self", ".", "__mfcc_mask_map", "[", ":", ":", "-", "1", "]", "self", ".", "__speech_intervals", "=", "[", "(", "all_length", "-", "i", "[", "1", "]", ",", "all_length", "-", "i", "[", "0", "]", ")", "for", "i", "in", "self", ".", "__speech_intervals", "[", ":", ":", "-", "1", "]", "]", "self", ".", "__nonspeech_intervals", "=", "[", "(", "all_length", "-", "i", "[", "1", "]", ",", "all_length", "-", "i", "[", "0", "]", ")", "for", "i", "in", "self", ".", "__nonspeech_intervals", "[", ":", ":", "-", "1", "]", "]", "self", ".", "is_reversed", "=", "not", "self", ".", "is_reversed", "self", ".", "log", "(", "u\"Reversing...done\"", ")" ]
Reverse the audio file. The reversing is done efficiently using NumPy views inplace instead of swapping values. Only speech and nonspeech intervals are actually recomputed as Python lists.
[ "Reverse", "the", "audio", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L555-L582
232,227
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.run_vad
def run_vad( self, log_energy_threshold=None, min_nonspeech_length=None, extend_before=None, extend_after=None ): """ Determine which frames contain speech and nonspeech, and store the resulting boolean mask internally. The four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after) """ def _compute_runs(array): """ Compute runs as a list of arrays, each containing the indices of a contiguous run. :param array: the data array :type array: :class:`numpy.ndarray` (1D) :rtype: list of :class:`numpy.ndarray` (1D) """ if len(array) < 1: return [] return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) self.log(u"Creating VAD object") vad = VAD(rconf=self.rconf, logger=self.logger) self.log(u"Running VAD...") self.__mfcc_mask = vad.run_vad( wave_energy=self.__mfcc[0], log_energy_threshold=log_energy_threshold, min_nonspeech_length=min_nonspeech_length, extend_before=extend_before, extend_after=extend_after ) self.__mfcc_mask_map = (numpy.where(self.__mfcc_mask))[0] self.log(u"Running VAD... done") self.log(u"Storing speech and nonspeech intervals...") # where( == True) already computed, reusing # COMMENTED runs = _compute_runs((numpy.where(self.__mfcc_mask))[0]) runs = _compute_runs(self.__mfcc_mask_map) self.__speech_intervals = [(r[0], r[-1]) for r in runs] # where( == False) not already computed, computing now runs = _compute_runs((numpy.where(~self.__mfcc_mask))[0]) self.__nonspeech_intervals = [(r[0], r[-1]) for r in runs] self.log(u"Storing speech and nonspeech intervals... done")
python
def run_vad( self, log_energy_threshold=None, min_nonspeech_length=None, extend_before=None, extend_after=None ): """ Determine which frames contain speech and nonspeech, and store the resulting boolean mask internally. The four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after) """ def _compute_runs(array): """ Compute runs as a list of arrays, each containing the indices of a contiguous run. :param array: the data array :type array: :class:`numpy.ndarray` (1D) :rtype: list of :class:`numpy.ndarray` (1D) """ if len(array) < 1: return [] return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) self.log(u"Creating VAD object") vad = VAD(rconf=self.rconf, logger=self.logger) self.log(u"Running VAD...") self.__mfcc_mask = vad.run_vad( wave_energy=self.__mfcc[0], log_energy_threshold=log_energy_threshold, min_nonspeech_length=min_nonspeech_length, extend_before=extend_before, extend_after=extend_after ) self.__mfcc_mask_map = (numpy.where(self.__mfcc_mask))[0] self.log(u"Running VAD... done") self.log(u"Storing speech and nonspeech intervals...") # where( == True) already computed, reusing # COMMENTED runs = _compute_runs((numpy.where(self.__mfcc_mask))[0]) runs = _compute_runs(self.__mfcc_mask_map) self.__speech_intervals = [(r[0], r[-1]) for r in runs] # where( == False) not already computed, computing now runs = _compute_runs((numpy.where(~self.__mfcc_mask))[0]) self.__nonspeech_intervals = [(r[0], r[-1]) for r in runs] self.log(u"Storing speech and nonspeech intervals... done")
[ "def", "run_vad", "(", "self", ",", "log_energy_threshold", "=", "None", ",", "min_nonspeech_length", "=", "None", ",", "extend_before", "=", "None", ",", "extend_after", "=", "None", ")", ":", "def", "_compute_runs", "(", "array", ")", ":", "\"\"\"\n Compute runs as a list of arrays,\n each containing the indices of a contiguous run.\n\n :param array: the data array\n :type array: :class:`numpy.ndarray` (1D)\n :rtype: list of :class:`numpy.ndarray` (1D)\n \"\"\"", "if", "len", "(", "array", ")", "<", "1", ":", "return", "[", "]", "return", "numpy", ".", "split", "(", "array", ",", "numpy", ".", "where", "(", "numpy", ".", "diff", "(", "array", ")", "!=", "1", ")", "[", "0", "]", "+", "1", ")", "self", ".", "log", "(", "u\"Creating VAD object\"", ")", "vad", "=", "VAD", "(", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", "self", ".", "log", "(", "u\"Running VAD...\"", ")", "self", ".", "__mfcc_mask", "=", "vad", ".", "run_vad", "(", "wave_energy", "=", "self", ".", "__mfcc", "[", "0", "]", ",", "log_energy_threshold", "=", "log_energy_threshold", ",", "min_nonspeech_length", "=", "min_nonspeech_length", ",", "extend_before", "=", "extend_before", ",", "extend_after", "=", "extend_after", ")", "self", ".", "__mfcc_mask_map", "=", "(", "numpy", ".", "where", "(", "self", ".", "__mfcc_mask", ")", ")", "[", "0", "]", "self", ".", "log", "(", "u\"Running VAD... done\"", ")", "self", ".", "log", "(", "u\"Storing speech and nonspeech intervals...\"", ")", "# where( == True) already computed, reusing", "# COMMENTED runs = _compute_runs((numpy.where(self.__mfcc_mask))[0])", "runs", "=", "_compute_runs", "(", "self", ".", "__mfcc_mask_map", ")", "self", ".", "__speech_intervals", "=", "[", "(", "r", "[", "0", "]", ",", "r", "[", "-", "1", "]", ")", "for", "r", "in", "runs", "]", "# where( == False) not already computed, computing now", "runs", "=", "_compute_runs", "(", "(", "numpy", ".", "where", "(", "~", "self", ".", "__mfcc_mask", ")", ")", "[", "0", "]", ")", "self", ".", "__nonspeech_intervals", "=", "[", "(", "r", "[", "0", "]", ",", "r", "[", "-", "1", "]", ")", "for", "r", "in", "runs", "]", "self", ".", "log", "(", "u\"Storing speech and nonspeech intervals... done\"", ")" ]
Determine which frames contain speech and nonspeech, and store the resulting boolean mask internally. The four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after)
[ "Determine", "which", "frames", "contain", "speech", "and", "nonspeech", "and", "store", "the", "resulting", "boolean", "mask", "internally", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L584-L636
232,228
readbeyond/aeneas
aeneas/audiofilemfcc.py
AudioFileMFCC.set_head_middle_tail
def set_head_middle_tail(self, head_length=None, middle_length=None, tail_length=None): """ Set the HEAD, MIDDLE, TAIL explicitly. If a parameter is ``None``, it will be ignored. If both ``middle_length`` and ``tail_length`` are specified, only ``middle_length`` will be applied. :param head_length: the length of HEAD, in seconds :type head_length: :class:`~aeneas.exacttiming.TimeValue` :param middle_length: the length of MIDDLE, in seconds :type middle_length: :class:`~aeneas.exacttiming.TimeValue` :param tail_length: the length of TAIL, in seconds :type tail_length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` :raises: ValueError: if one of the arguments is greater than the length of the audio file """ for variable, name in [ (head_length, "head_length"), (middle_length, "middle_length"), (tail_length, "tail_length") ]: if (variable is not None) and (not isinstance(variable, TimeValue)): raise TypeError(u"%s is not None or TimeValue" % name) if (variable is not None) and (variable > self.audio_length): raise ValueError(u"%s is greater than the length of the audio file" % name) self.log(u"Setting head middle tail...") mws = self.rconf.mws self.log([u"Before: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length]) if head_length is not None: self.middle_begin = int(head_length / mws) if middle_length is not None: self.middle_end = self.middle_begin + int(middle_length / mws) elif tail_length is not None: self.middle_end = self.all_length - int(tail_length / mws) self.log([u"After: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length]) self.log(u"Setting head middle tail... done")
python
def set_head_middle_tail(self, head_length=None, middle_length=None, tail_length=None): """ Set the HEAD, MIDDLE, TAIL explicitly. If a parameter is ``None``, it will be ignored. If both ``middle_length`` and ``tail_length`` are specified, only ``middle_length`` will be applied. :param head_length: the length of HEAD, in seconds :type head_length: :class:`~aeneas.exacttiming.TimeValue` :param middle_length: the length of MIDDLE, in seconds :type middle_length: :class:`~aeneas.exacttiming.TimeValue` :param tail_length: the length of TAIL, in seconds :type tail_length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` :raises: ValueError: if one of the arguments is greater than the length of the audio file """ for variable, name in [ (head_length, "head_length"), (middle_length, "middle_length"), (tail_length, "tail_length") ]: if (variable is not None) and (not isinstance(variable, TimeValue)): raise TypeError(u"%s is not None or TimeValue" % name) if (variable is not None) and (variable > self.audio_length): raise ValueError(u"%s is greater than the length of the audio file" % name) self.log(u"Setting head middle tail...") mws = self.rconf.mws self.log([u"Before: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length]) if head_length is not None: self.middle_begin = int(head_length / mws) if middle_length is not None: self.middle_end = self.middle_begin + int(middle_length / mws) elif tail_length is not None: self.middle_end = self.all_length - int(tail_length / mws) self.log([u"After: 0 %d %d %d", self.middle_begin, self.middle_end, self.all_length]) self.log(u"Setting head middle tail... done")
[ "def", "set_head_middle_tail", "(", "self", ",", "head_length", "=", "None", ",", "middle_length", "=", "None", ",", "tail_length", "=", "None", ")", ":", "for", "variable", ",", "name", "in", "[", "(", "head_length", ",", "\"head_length\"", ")", ",", "(", "middle_length", ",", "\"middle_length\"", ")", ",", "(", "tail_length", ",", "\"tail_length\"", ")", "]", ":", "if", "(", "variable", "is", "not", "None", ")", "and", "(", "not", "isinstance", "(", "variable", ",", "TimeValue", ")", ")", ":", "raise", "TypeError", "(", "u\"%s is not None or TimeValue\"", "%", "name", ")", "if", "(", "variable", "is", "not", "None", ")", "and", "(", "variable", ">", "self", ".", "audio_length", ")", ":", "raise", "ValueError", "(", "u\"%s is greater than the length of the audio file\"", "%", "name", ")", "self", ".", "log", "(", "u\"Setting head middle tail...\"", ")", "mws", "=", "self", ".", "rconf", ".", "mws", "self", ".", "log", "(", "[", "u\"Before: 0 %d %d %d\"", ",", "self", ".", "middle_begin", ",", "self", ".", "middle_end", ",", "self", ".", "all_length", "]", ")", "if", "head_length", "is", "not", "None", ":", "self", ".", "middle_begin", "=", "int", "(", "head_length", "/", "mws", ")", "if", "middle_length", "is", "not", "None", ":", "self", ".", "middle_end", "=", "self", ".", "middle_begin", "+", "int", "(", "middle_length", "/", "mws", ")", "elif", "tail_length", "is", "not", "None", ":", "self", ".", "middle_end", "=", "self", ".", "all_length", "-", "int", "(", "tail_length", "/", "mws", ")", "self", ".", "log", "(", "[", "u\"After: 0 %d %d %d\"", ",", "self", ".", "middle_begin", ",", "self", ".", "middle_end", ",", "self", ".", "all_length", "]", ")", "self", ".", "log", "(", "u\"Setting head middle tail... done\"", ")" ]
Set the HEAD, MIDDLE, TAIL explicitly. If a parameter is ``None``, it will be ignored. If both ``middle_length`` and ``tail_length`` are specified, only ``middle_length`` will be applied. :param head_length: the length of HEAD, in seconds :type head_length: :class:`~aeneas.exacttiming.TimeValue` :param middle_length: the length of MIDDLE, in seconds :type middle_length: :class:`~aeneas.exacttiming.TimeValue` :param tail_length: the length of TAIL, in seconds :type tail_length: :class:`~aeneas.exacttiming.TimeValue` :raises: TypeError: if one of the arguments is not ``None`` or :class:`~aeneas.exacttiming.TimeValue` :raises: ValueError: if one of the arguments is greater than the length of the audio file
[ "Set", "the", "HEAD", "MIDDLE", "TAIL", "explicitly", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/audiofilemfcc.py#L638-L676
232,229
readbeyond/aeneas
aeneas/textfile.py
TextFragment.chars
def chars(self): """ Return the number of characters of the text fragment, not including the line separators. :rtype: int """ if self.lines is None: return 0 return sum([len(line) for line in self.lines])
python
def chars(self): """ Return the number of characters of the text fragment, not including the line separators. :rtype: int """ if self.lines is None: return 0 return sum([len(line) for line in self.lines])
[ "def", "chars", "(", "self", ")", ":", "if", "self", ".", "lines", "is", "None", ":", "return", "0", "return", "sum", "(", "[", "len", "(", "line", ")", "for", "line", "in", "self", ".", "lines", "]", ")" ]
Return the number of characters of the text fragment, not including the line separators. :rtype: int
[ "Return", "the", "number", "of", "characters", "of", "the", "text", "fragment", "not", "including", "the", "line", "separators", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L355-L364
232,230
readbeyond/aeneas
aeneas/textfile.py
TextFile.children_not_empty
def children_not_empty(self): """ Return the direct not empty children of the root of the fragments tree, as ``TextFile`` objects. :rtype: list of :class:`~aeneas.textfile.TextFile` """ children = [] for child_node in self.fragments_tree.children_not_empty: child_text_file = self.get_subtree(child_node) child_text_file.set_language(child_node.value.language) children.append(child_text_file) return children
python
def children_not_empty(self): """ Return the direct not empty children of the root of the fragments tree, as ``TextFile`` objects. :rtype: list of :class:`~aeneas.textfile.TextFile` """ children = [] for child_node in self.fragments_tree.children_not_empty: child_text_file = self.get_subtree(child_node) child_text_file.set_language(child_node.value.language) children.append(child_text_file) return children
[ "def", "children_not_empty", "(", "self", ")", ":", "children", "=", "[", "]", "for", "child_node", "in", "self", ".", "fragments_tree", ".", "children_not_empty", ":", "child_text_file", "=", "self", ".", "get_subtree", "(", "child_node", ")", "child_text_file", ".", "set_language", "(", "child_node", ".", "value", ".", "language", ")", "children", ".", "append", "(", "child_text_file", ")", "return", "children" ]
Return the direct not empty children of the root of the fragments tree, as ``TextFile`` objects. :rtype: list of :class:`~aeneas.textfile.TextFile`
[ "Return", "the", "direct", "not", "empty", "children", "of", "the", "root", "of", "the", "fragments", "tree", "as", "TextFile", "objects", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L455-L467
232,231
readbeyond/aeneas
aeneas/textfile.py
TextFile.characters
def characters(self): """ The number of characters in this text file. :rtype: int """ chars = 0 for fragment in self.fragments: chars += fragment.characters return chars
python
def characters(self): """ The number of characters in this text file. :rtype: int """ chars = 0 for fragment in self.fragments: chars += fragment.characters return chars
[ "def", "characters", "(", "self", ")", ":", "chars", "=", "0", "for", "fragment", "in", "self", ".", "fragments", ":", "chars", "+=", "fragment", ".", "characters", "return", "chars" ]
The number of characters in this text file. :rtype: int
[ "The", "number", "of", "characters", "in", "this", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L525-L534
232,232
readbeyond/aeneas
aeneas/textfile.py
TextFile.add_fragment
def add_fragment(self, fragment, as_last=True): """ Add the given text fragment as the first or last child of the root node of the text file tree. :param fragment: the text fragment to be added :type fragment: :class:`~aeneas.textfile.TextFragment` :param bool as_last: if ``True`` append fragment, otherwise prepend it """ if not isinstance(fragment, TextFragment): self.log_exc(u"fragment is not an instance of TextFragment", None, True, TypeError) self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last)
python
def add_fragment(self, fragment, as_last=True): """ Add the given text fragment as the first or last child of the root node of the text file tree. :param fragment: the text fragment to be added :type fragment: :class:`~aeneas.textfile.TextFragment` :param bool as_last: if ``True`` append fragment, otherwise prepend it """ if not isinstance(fragment, TextFragment): self.log_exc(u"fragment is not an instance of TextFragment", None, True, TypeError) self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last)
[ "def", "add_fragment", "(", "self", ",", "fragment", ",", "as_last", "=", "True", ")", ":", "if", "not", "isinstance", "(", "fragment", ",", "TextFragment", ")", ":", "self", ".", "log_exc", "(", "u\"fragment is not an instance of TextFragment\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "fragments_tree", ".", "add_child", "(", "Tree", "(", "value", "=", "fragment", ")", ",", "as_last", "=", "as_last", ")" ]
Add the given text fragment as the first or last child of the root node of the text file tree. :param fragment: the text fragment to be added :type fragment: :class:`~aeneas.textfile.TextFragment` :param bool as_last: if ``True`` append fragment, otherwise prepend it
[ "Add", "the", "given", "text", "fragment", "as", "the", "first", "or", "last", "child", "of", "the", "root", "node", "of", "the", "text", "file", "tree", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L547-L558
232,233
readbeyond/aeneas
aeneas/textfile.py
TextFile.set_language
def set_language(self, language): """ Set the given language for all the text fragments. :param language: the language of the text fragments :type language: :class:`~aeneas.language.Language` """ self.log([u"Setting language: '%s'", language]) for fragment in self.fragments: fragment.language = language
python
def set_language(self, language): """ Set the given language for all the text fragments. :param language: the language of the text fragments :type language: :class:`~aeneas.language.Language` """ self.log([u"Setting language: '%s'", language]) for fragment in self.fragments: fragment.language = language
[ "def", "set_language", "(", "self", ",", "language", ")", ":", "self", ".", "log", "(", "[", "u\"Setting language: '%s'\"", ",", "language", "]", ")", "for", "fragment", "in", "self", ".", "fragments", ":", "fragment", ".", "language", "=", "language" ]
Set the given language for all the text fragments. :param language: the language of the text fragments :type language: :class:`~aeneas.language.Language`
[ "Set", "the", "given", "language", "for", "all", "the", "text", "fragments", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L598-L607
232,234
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_from_file
def _read_from_file(self): """ Read text fragments from file. """ # test if we can read the given file if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) if self.file_format not in TextFileFormat.ALLOWED_VALUES: self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError) # read the contents of the file self.log([u"Reading contents of file '%s'", self.file_path]) with io.open(self.file_path, "r", encoding="utf-8") as text_file: lines = text_file.readlines() # clear text fragments self.clear() # parse the contents map_read_function = { TextFileFormat.MPLAIN: self._read_mplain, TextFileFormat.MUNPARSED: self._read_munparsed, TextFileFormat.PARSED: self._read_parsed, TextFileFormat.PLAIN: self._read_plain, TextFileFormat.SUBTITLES: self._read_subtitles, TextFileFormat.UNPARSED: self._read_unparsed } map_read_function[self.file_format](lines) # log the number of fragments self.log([u"Parsed %d fragments", len(self.fragments)])
python
def _read_from_file(self): """ Read text fragments from file. """ # test if we can read the given file if not gf.file_can_be_read(self.file_path): self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError) if self.file_format not in TextFileFormat.ALLOWED_VALUES: self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError) # read the contents of the file self.log([u"Reading contents of file '%s'", self.file_path]) with io.open(self.file_path, "r", encoding="utf-8") as text_file: lines = text_file.readlines() # clear text fragments self.clear() # parse the contents map_read_function = { TextFileFormat.MPLAIN: self._read_mplain, TextFileFormat.MUNPARSED: self._read_munparsed, TextFileFormat.PARSED: self._read_parsed, TextFileFormat.PLAIN: self._read_plain, TextFileFormat.SUBTITLES: self._read_subtitles, TextFileFormat.UNPARSED: self._read_unparsed } map_read_function[self.file_format](lines) # log the number of fragments self.log([u"Parsed %d fragments", len(self.fragments)])
[ "def", "_read_from_file", "(", "self", ")", ":", "# test if we can read the given file", "if", "not", "gf", ".", "file_can_be_read", "(", "self", ".", "file_path", ")", ":", "self", ".", "log_exc", "(", "u\"File '%s' cannot be read\"", "%", "(", "self", ".", "file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "if", "self", ".", "file_format", "not", "in", "TextFileFormat", ".", "ALLOWED_VALUES", ":", "self", ".", "log_exc", "(", "u\"Text file format '%s' is not supported.\"", "%", "(", "self", ".", "file_format", ")", ",", "None", ",", "True", ",", "ValueError", ")", "# read the contents of the file", "self", ".", "log", "(", "[", "u\"Reading contents of file '%s'\"", ",", "self", ".", "file_path", "]", ")", "with", "io", ".", "open", "(", "self", ".", "file_path", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "text_file", ":", "lines", "=", "text_file", ".", "readlines", "(", ")", "# clear text fragments", "self", ".", "clear", "(", ")", "# parse the contents", "map_read_function", "=", "{", "TextFileFormat", ".", "MPLAIN", ":", "self", ".", "_read_mplain", ",", "TextFileFormat", ".", "MUNPARSED", ":", "self", ".", "_read_munparsed", ",", "TextFileFormat", ".", "PARSED", ":", "self", ".", "_read_parsed", ",", "TextFileFormat", ".", "PLAIN", ":", "self", ".", "_read_plain", ",", "TextFileFormat", ".", "SUBTITLES", ":", "self", ".", "_read_subtitles", ",", "TextFileFormat", ".", "UNPARSED", ":", "self", ".", "_read_unparsed", "}", "map_read_function", "[", "self", ".", "file_format", "]", "(", "lines", ")", "# log the number of fragments", "self", ".", "log", "(", "[", "u\"Parsed %d fragments\"", ",", "len", "(", "self", ".", "fragments", ")", "]", ")" ]
Read text fragments from file.
[ "Read", "text", "fragments", "from", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L638-L669
232,235
readbeyond/aeneas
aeneas/textfile.py
TextFile._mplain_word_separator
def _mplain_word_separator(self): """ Get the word separator to split words in mplain format. :rtype: string """ word_separator = gf.safe_get(self.parameters, gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR, u" ") if (word_separator is None) or (word_separator == "space"): return u" " elif word_separator == "equal": return u"=" elif word_separator == "pipe": return u"|" elif word_separator == "tab": return u"\u0009" return word_separator
python
def _mplain_word_separator(self): """ Get the word separator to split words in mplain format. :rtype: string """ word_separator = gf.safe_get(self.parameters, gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR, u" ") if (word_separator is None) or (word_separator == "space"): return u" " elif word_separator == "equal": return u"=" elif word_separator == "pipe": return u"|" elif word_separator == "tab": return u"\u0009" return word_separator
[ "def", "_mplain_word_separator", "(", "self", ")", ":", "word_separator", "=", "gf", ".", "safe_get", "(", "self", ".", "parameters", ",", "gc", ".", "PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR", ",", "u\" \"", ")", "if", "(", "word_separator", "is", "None", ")", "or", "(", "word_separator", "==", "\"space\"", ")", ":", "return", "u\" \"", "elif", "word_separator", "==", "\"equal\"", ":", "return", "u\"=\"", "elif", "word_separator", "==", "\"pipe\"", ":", "return", "u\"|\"", "elif", "word_separator", "==", "\"tab\"", ":", "return", "u\"\\u0009\"", "return", "word_separator" ]
Get the word separator to split words in mplain format. :rtype: string
[ "Get", "the", "word", "separator", "to", "split", "words", "in", "mplain", "format", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L671-L686
232,236
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_mplain
def _read_mplain(self, lines): """ Read text fragments from a multilevel format text file. :param list lines: the lines of the subtitles text file """ self.log(u"Parsing fragments from subtitles text format") word_separator = self._mplain_word_separator() self.log([u"Word separator is: '%s'", word_separator]) lines = [line.strip() for line in lines] pairs = [] i = 1 current = 0 tree = Tree() while current < len(lines): line_text = lines[current] if len(line_text) > 0: sentences = [line_text] following = current + 1 while (following < len(lines)) and (len(lines[following]) > 0): sentences.append(lines[following]) following += 1 # here sentences holds the sentences for this paragraph # create paragraph node paragraph_identifier = u"p%06d" % i paragraph_lines = [u" ".join(sentences)] paragraph_fragment = TextFragment( identifier=paragraph_identifier, lines=paragraph_lines, filtered_lines=paragraph_lines ) paragraph_node = Tree(value=paragraph_fragment) tree.add_child(paragraph_node) self.log([u"Paragraph %s", paragraph_identifier]) # create sentences nodes j = 1 for s in sentences: sentence_identifier = paragraph_identifier + u"s%06d" % j sentence_lines = [s] sentence_fragment = TextFragment( identifier=sentence_identifier, lines=sentence_lines, filtered_lines=sentence_lines ) sentence_node = Tree(value=sentence_fragment) paragraph_node.add_child(sentence_node) j += 1 self.log([u" Sentence %s", sentence_identifier]) # create words nodes k = 1 for w in [w for w in s.split(word_separator) if len(w) > 0]: word_identifier = sentence_identifier + u"w%06d" % k word_lines = [w] word_fragment = TextFragment( identifier=word_identifier, lines=word_lines, filtered_lines=word_lines ) word_node = Tree(value=word_fragment) sentence_node.add_child(word_node) k += 1 self.log([u" Word %s", word_identifier]) # keep iterating current = following i += 1 current += 1 self.log(u"Storing tree") self.fragments_tree = tree
python
def _read_mplain(self, lines): """ Read text fragments from a multilevel format text file. :param list lines: the lines of the subtitles text file """ self.log(u"Parsing fragments from subtitles text format") word_separator = self._mplain_word_separator() self.log([u"Word separator is: '%s'", word_separator]) lines = [line.strip() for line in lines] pairs = [] i = 1 current = 0 tree = Tree() while current < len(lines): line_text = lines[current] if len(line_text) > 0: sentences = [line_text] following = current + 1 while (following < len(lines)) and (len(lines[following]) > 0): sentences.append(lines[following]) following += 1 # here sentences holds the sentences for this paragraph # create paragraph node paragraph_identifier = u"p%06d" % i paragraph_lines = [u" ".join(sentences)] paragraph_fragment = TextFragment( identifier=paragraph_identifier, lines=paragraph_lines, filtered_lines=paragraph_lines ) paragraph_node = Tree(value=paragraph_fragment) tree.add_child(paragraph_node) self.log([u"Paragraph %s", paragraph_identifier]) # create sentences nodes j = 1 for s in sentences: sentence_identifier = paragraph_identifier + u"s%06d" % j sentence_lines = [s] sentence_fragment = TextFragment( identifier=sentence_identifier, lines=sentence_lines, filtered_lines=sentence_lines ) sentence_node = Tree(value=sentence_fragment) paragraph_node.add_child(sentence_node) j += 1 self.log([u" Sentence %s", sentence_identifier]) # create words nodes k = 1 for w in [w for w in s.split(word_separator) if len(w) > 0]: word_identifier = sentence_identifier + u"w%06d" % k word_lines = [w] word_fragment = TextFragment( identifier=word_identifier, lines=word_lines, filtered_lines=word_lines ) word_node = Tree(value=word_fragment) sentence_node.add_child(word_node) k += 1 self.log([u" Word %s", word_identifier]) # keep iterating current = following i += 1 current += 1 self.log(u"Storing tree") self.fragments_tree = tree
[ "def", "_read_mplain", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from subtitles text format\"", ")", "word_separator", "=", "self", ".", "_mplain_word_separator", "(", ")", "self", ".", "log", "(", "[", "u\"Word separator is: '%s'\"", ",", "word_separator", "]", ")", "lines", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "lines", "]", "pairs", "=", "[", "]", "i", "=", "1", "current", "=", "0", "tree", "=", "Tree", "(", ")", "while", "current", "<", "len", "(", "lines", ")", ":", "line_text", "=", "lines", "[", "current", "]", "if", "len", "(", "line_text", ")", ">", "0", ":", "sentences", "=", "[", "line_text", "]", "following", "=", "current", "+", "1", "while", "(", "following", "<", "len", "(", "lines", ")", ")", "and", "(", "len", "(", "lines", "[", "following", "]", ")", ">", "0", ")", ":", "sentences", ".", "append", "(", "lines", "[", "following", "]", ")", "following", "+=", "1", "# here sentences holds the sentences for this paragraph", "# create paragraph node", "paragraph_identifier", "=", "u\"p%06d\"", "%", "i", "paragraph_lines", "=", "[", "u\" \"", ".", "join", "(", "sentences", ")", "]", "paragraph_fragment", "=", "TextFragment", "(", "identifier", "=", "paragraph_identifier", ",", "lines", "=", "paragraph_lines", ",", "filtered_lines", "=", "paragraph_lines", ")", "paragraph_node", "=", "Tree", "(", "value", "=", "paragraph_fragment", ")", "tree", ".", "add_child", "(", "paragraph_node", ")", "self", ".", "log", "(", "[", "u\"Paragraph %s\"", ",", "paragraph_identifier", "]", ")", "# create sentences nodes", "j", "=", "1", "for", "s", "in", "sentences", ":", "sentence_identifier", "=", "paragraph_identifier", "+", "u\"s%06d\"", "%", "j", "sentence_lines", "=", "[", "s", "]", "sentence_fragment", "=", "TextFragment", "(", "identifier", "=", "sentence_identifier", ",", "lines", "=", "sentence_lines", ",", "filtered_lines", "=", "sentence_lines", ")", "sentence_node", "=", "Tree", "(", "value", "=", "sentence_fragment", ")", "paragraph_node", ".", "add_child", "(", "sentence_node", ")", "j", "+=", "1", "self", ".", "log", "(", "[", "u\" Sentence %s\"", ",", "sentence_identifier", "]", ")", "# create words nodes", "k", "=", "1", "for", "w", "in", "[", "w", "for", "w", "in", "s", ".", "split", "(", "word_separator", ")", "if", "len", "(", "w", ")", ">", "0", "]", ":", "word_identifier", "=", "sentence_identifier", "+", "u\"w%06d\"", "%", "k", "word_lines", "=", "[", "w", "]", "word_fragment", "=", "TextFragment", "(", "identifier", "=", "word_identifier", ",", "lines", "=", "word_lines", ",", "filtered_lines", "=", "word_lines", ")", "word_node", "=", "Tree", "(", "value", "=", "word_fragment", ")", "sentence_node", ".", "add_child", "(", "word_node", ")", "k", "+=", "1", "self", ".", "log", "(", "[", "u\" Word %s\"", ",", "word_identifier", "]", ")", "# keep iterating", "current", "=", "following", "i", "+=", "1", "current", "+=", "1", "self", ".", "log", "(", "u\"Storing tree\"", ")", "self", ".", "fragments_tree", "=", "tree" ]
Read text fragments from a multilevel format text file. :param list lines: the lines of the subtitles text file
[ "Read", "text", "fragments", "from", "a", "multilevel", "format", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L688-L760
232,237
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_subtitles
def _read_subtitles(self, lines): """ Read text fragments from a subtitles format text file. :param list lines: the lines of the subtitles text file :raises: ValueError: if the id regex is not valid """ self.log(u"Parsing fragments from subtitles text format") id_format = self._get_id_format() lines = [line.strip() for line in lines] pairs = [] i = 1 current = 0 while current < len(lines): line_text = lines[current] if len(line_text) > 0: fragment_lines = [line_text] following = current + 1 while (following < len(lines)) and (len(lines[following]) > 0): fragment_lines.append(lines[following]) following += 1 identifier = id_format % i pairs.append((identifier, fragment_lines)) current = following i += 1 current += 1 self._create_text_fragments(pairs)
python
def _read_subtitles(self, lines): """ Read text fragments from a subtitles format text file. :param list lines: the lines of the subtitles text file :raises: ValueError: if the id regex is not valid """ self.log(u"Parsing fragments from subtitles text format") id_format = self._get_id_format() lines = [line.strip() for line in lines] pairs = [] i = 1 current = 0 while current < len(lines): line_text = lines[current] if len(line_text) > 0: fragment_lines = [line_text] following = current + 1 while (following < len(lines)) and (len(lines[following]) > 0): fragment_lines.append(lines[following]) following += 1 identifier = id_format % i pairs.append((identifier, fragment_lines)) current = following i += 1 current += 1 self._create_text_fragments(pairs)
[ "def", "_read_subtitles", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from subtitles text format\"", ")", "id_format", "=", "self", ".", "_get_id_format", "(", ")", "lines", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "lines", "]", "pairs", "=", "[", "]", "i", "=", "1", "current", "=", "0", "while", "current", "<", "len", "(", "lines", ")", ":", "line_text", "=", "lines", "[", "current", "]", "if", "len", "(", "line_text", ")", ">", "0", ":", "fragment_lines", "=", "[", "line_text", "]", "following", "=", "current", "+", "1", "while", "(", "following", "<", "len", "(", "lines", ")", ")", "and", "(", "len", "(", "lines", "[", "following", "]", ")", ">", "0", ")", ":", "fragment_lines", ".", "append", "(", "lines", "[", "following", "]", ")", "following", "+=", "1", "identifier", "=", "id_format", "%", "i", "pairs", ".", "append", "(", "(", "identifier", ",", "fragment_lines", ")", ")", "current", "=", "following", "i", "+=", "1", "current", "+=", "1", "self", ".", "_create_text_fragments", "(", "pairs", ")" ]
Read text fragments from a subtitles format text file. :param list lines: the lines of the subtitles text file :raises: ValueError: if the id regex is not valid
[ "Read", "text", "fragments", "from", "a", "subtitles", "format", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L851-L877
232,238
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_parsed
def _read_parsed(self, lines): """ Read text fragments from a parsed format text file. :param list lines: the lines of the parsed text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) """ self.log(u"Parsing fragments from parsed text format") pairs = [] for line in lines: pieces = line.split(gc.PARSED_TEXT_SEPARATOR) if len(pieces) == 2: identifier = pieces[0].strip() text = pieces[1].strip() if len(identifier) > 0: pairs.append((identifier, [text])) self._create_text_fragments(pairs)
python
def _read_parsed(self, lines): """ Read text fragments from a parsed format text file. :param list lines: the lines of the parsed text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) """ self.log(u"Parsing fragments from parsed text format") pairs = [] for line in lines: pieces = line.split(gc.PARSED_TEXT_SEPARATOR) if len(pieces) == 2: identifier = pieces[0].strip() text = pieces[1].strip() if len(identifier) > 0: pairs.append((identifier, [text])) self._create_text_fragments(pairs)
[ "def", "_read_parsed", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from parsed text format\"", ")", "pairs", "=", "[", "]", "for", "line", "in", "lines", ":", "pieces", "=", "line", ".", "split", "(", "gc", ".", "PARSED_TEXT_SEPARATOR", ")", "if", "len", "(", "pieces", ")", "==", "2", ":", "identifier", "=", "pieces", "[", "0", "]", ".", "strip", "(", ")", "text", "=", "pieces", "[", "1", "]", ".", "strip", "(", ")", "if", "len", "(", "identifier", ")", ">", "0", ":", "pairs", ".", "append", "(", "(", "identifier", ",", "[", "text", "]", ")", ")", "self", ".", "_create_text_fragments", "(", "pairs", ")" ]
Read text fragments from a parsed format text file. :param list lines: the lines of the parsed text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings)
[ "Read", "text", "fragments", "from", "a", "parsed", "format", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L879-L896
232,239
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_plain
def _read_plain(self, lines): """ Read text fragments from a plain format text file. :param list lines: the lines of the plain text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) :raises: ValueError: if the id regex is not valid """ self.log(u"Parsing fragments from plain text format") id_format = self._get_id_format() lines = [line.strip() for line in lines] pairs = [] i = 1 for line in lines: identifier = id_format % i text = line.strip() pairs.append((identifier, [text])) i += 1 self._create_text_fragments(pairs)
python
def _read_plain(self, lines): """ Read text fragments from a plain format text file. :param list lines: the lines of the plain text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) :raises: ValueError: if the id regex is not valid """ self.log(u"Parsing fragments from plain text format") id_format = self._get_id_format() lines = [line.strip() for line in lines] pairs = [] i = 1 for line in lines: identifier = id_format % i text = line.strip() pairs.append((identifier, [text])) i += 1 self._create_text_fragments(pairs)
[ "def", "_read_plain", "(", "self", ",", "lines", ")", ":", "self", ".", "log", "(", "u\"Parsing fragments from plain text format\"", ")", "id_format", "=", "self", ".", "_get_id_format", "(", ")", "lines", "=", "[", "line", ".", "strip", "(", ")", "for", "line", "in", "lines", "]", "pairs", "=", "[", "]", "i", "=", "1", "for", "line", "in", "lines", ":", "identifier", "=", "id_format", "%", "i", "text", "=", "line", ".", "strip", "(", ")", "pairs", ".", "append", "(", "(", "identifier", ",", "[", "text", "]", ")", ")", "i", "+=", "1", "self", ".", "_create_text_fragments", "(", "pairs", ")" ]
Read text fragments from a plain format text file. :param list lines: the lines of the plain text file :param dict parameters: additional parameters for parsing (e.g., class/id regex strings) :raises: ValueError: if the id regex is not valid
[ "Read", "text", "fragments", "from", "a", "plain", "format", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L898-L917
232,240
readbeyond/aeneas
aeneas/textfile.py
TextFile._read_unparsed
def _read_unparsed(self, lines): """ Read text fragments from an unparsed format text file. :param list lines: the lines of the unparsed text file """ from bs4 import BeautifulSoup def filter_attributes(): """ Return a dict with the bs4 filter parameters """ attributes = {} for attribute_name, filter_name in [ ("class", gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX), ("id", gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX) ]: if filter_name in self.parameters: regex_string = self.parameters[filter_name] if regex_string is not None: self.log([u"Regex for %s: '%s'", attribute_name, regex_string]) regex = re.compile(r".*\b" + regex_string + r"\b.*") attributes[attribute_name] = regex return attributes # # TODO better and/or parametric parsing, # for example, removing tags but keeping text, etc. # self.log(u"Parsing fragments from unparsed text format") # transform text in a soup object self.log(u"Creating soup") soup = BeautifulSoup("\n".join(lines), "lxml") # extract according to class_regex and id_regex text_from_id = {} ids = [] filter_attributes = filter_attributes() self.log([u"Finding elements matching attributes '%s'", filter_attributes]) nodes = soup.findAll(attrs=filter_attributes) for node in nodes: try: f_id = gf.safe_unicode(node["id"]) f_text = gf.safe_unicode(node.text) text_from_id[f_id] = f_text ids.append(f_id) except KeyError: self.log_warn(u"KeyError while parsing a node") # sort by ID as requested id_sort = gf.safe_get( dictionary=self.parameters, key=gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT, default_value=IDSortingAlgorithm.UNSORTED, can_return_none=False ) self.log([u"Sorting text fragments using '%s'", id_sort]) sorted_ids = IDSortingAlgorithm(id_sort).sort(ids) # append to fragments self.log(u"Appending fragments") self._create_text_fragments([(key, [text_from_id[key]]) for key in sorted_ids])
python
def _read_unparsed(self, lines): """ Read text fragments from an unparsed format text file. :param list lines: the lines of the unparsed text file """ from bs4 import BeautifulSoup def filter_attributes(): """ Return a dict with the bs4 filter parameters """ attributes = {} for attribute_name, filter_name in [ ("class", gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX), ("id", gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX) ]: if filter_name in self.parameters: regex_string = self.parameters[filter_name] if regex_string is not None: self.log([u"Regex for %s: '%s'", attribute_name, regex_string]) regex = re.compile(r".*\b" + regex_string + r"\b.*") attributes[attribute_name] = regex return attributes # # TODO better and/or parametric parsing, # for example, removing tags but keeping text, etc. # self.log(u"Parsing fragments from unparsed text format") # transform text in a soup object self.log(u"Creating soup") soup = BeautifulSoup("\n".join(lines), "lxml") # extract according to class_regex and id_regex text_from_id = {} ids = [] filter_attributes = filter_attributes() self.log([u"Finding elements matching attributes '%s'", filter_attributes]) nodes = soup.findAll(attrs=filter_attributes) for node in nodes: try: f_id = gf.safe_unicode(node["id"]) f_text = gf.safe_unicode(node.text) text_from_id[f_id] = f_text ids.append(f_id) except KeyError: self.log_warn(u"KeyError while parsing a node") # sort by ID as requested id_sort = gf.safe_get( dictionary=self.parameters, key=gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT, default_value=IDSortingAlgorithm.UNSORTED, can_return_none=False ) self.log([u"Sorting text fragments using '%s'", id_sort]) sorted_ids = IDSortingAlgorithm(id_sort).sort(ids) # append to fragments self.log(u"Appending fragments") self._create_text_fragments([(key, [text_from_id[key]]) for key in sorted_ids])
[ "def", "_read_unparsed", "(", "self", ",", "lines", ")", ":", "from", "bs4", "import", "BeautifulSoup", "def", "filter_attributes", "(", ")", ":", "\"\"\" Return a dict with the bs4 filter parameters \"\"\"", "attributes", "=", "{", "}", "for", "attribute_name", ",", "filter_name", "in", "[", "(", "\"class\"", ",", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX", ")", ",", "(", "\"id\"", ",", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX", ")", "]", ":", "if", "filter_name", "in", "self", ".", "parameters", ":", "regex_string", "=", "self", ".", "parameters", "[", "filter_name", "]", "if", "regex_string", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"Regex for %s: '%s'\"", ",", "attribute_name", ",", "regex_string", "]", ")", "regex", "=", "re", ".", "compile", "(", "r\".*\\b\"", "+", "regex_string", "+", "r\"\\b.*\"", ")", "attributes", "[", "attribute_name", "]", "=", "regex", "return", "attributes", "#", "# TODO better and/or parametric parsing,", "# for example, removing tags but keeping text, etc.", "#", "self", ".", "log", "(", "u\"Parsing fragments from unparsed text format\"", ")", "# transform text in a soup object", "self", ".", "log", "(", "u\"Creating soup\"", ")", "soup", "=", "BeautifulSoup", "(", "\"\\n\"", ".", "join", "(", "lines", ")", ",", "\"lxml\"", ")", "# extract according to class_regex and id_regex", "text_from_id", "=", "{", "}", "ids", "=", "[", "]", "filter_attributes", "=", "filter_attributes", "(", ")", "self", ".", "log", "(", "[", "u\"Finding elements matching attributes '%s'\"", ",", "filter_attributes", "]", ")", "nodes", "=", "soup", ".", "findAll", "(", "attrs", "=", "filter_attributes", ")", "for", "node", "in", "nodes", ":", "try", ":", "f_id", "=", "gf", ".", "safe_unicode", "(", "node", "[", "\"id\"", "]", ")", "f_text", "=", "gf", ".", "safe_unicode", "(", "node", ".", "text", ")", "text_from_id", "[", "f_id", "]", "=", "f_text", "ids", ".", "append", "(", "f_id", ")", "except", "KeyError", ":", "self", ".", "log_warn", "(", "u\"KeyError while parsing a node\"", ")", "# sort by ID as requested", "id_sort", "=", "gf", ".", "safe_get", "(", "dictionary", "=", "self", ".", "parameters", ",", "key", "=", "gc", ".", "PPN_TASK_IS_TEXT_UNPARSED_ID_SORT", ",", "default_value", "=", "IDSortingAlgorithm", ".", "UNSORTED", ",", "can_return_none", "=", "False", ")", "self", ".", "log", "(", "[", "u\"Sorting text fragments using '%s'\"", ",", "id_sort", "]", ")", "sorted_ids", "=", "IDSortingAlgorithm", "(", "id_sort", ")", ".", "sort", "(", "ids", ")", "# append to fragments", "self", ".", "log", "(", "u\"Appending fragments\"", ")", "self", ".", "_create_text_fragments", "(", "[", "(", "key", ",", "[", "text_from_id", "[", "key", "]", "]", ")", "for", "key", "in", "sorted_ids", "]", ")" ]
Read text fragments from an unparsed format text file. :param list lines: the lines of the unparsed text file
[ "Read", "text", "fragments", "from", "an", "unparsed", "format", "text", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L919-L978
232,241
readbeyond/aeneas
aeneas/textfile.py
TextFile._get_id_format
def _get_id_format(self): """ Return the id regex from the parameters""" id_format = gf.safe_get( self.parameters, gc.PPN_TASK_OS_FILE_ID_REGEX, self.DEFAULT_ID_FORMAT, can_return_none=False ) try: identifier = id_format % 1 except (TypeError, ValueError) as exc: self.log_exc(u"String '%s' is not a valid id format" % (id_format), exc, True, ValueError) return id_format
python
def _get_id_format(self): """ Return the id regex from the parameters""" id_format = gf.safe_get( self.parameters, gc.PPN_TASK_OS_FILE_ID_REGEX, self.DEFAULT_ID_FORMAT, can_return_none=False ) try: identifier = id_format % 1 except (TypeError, ValueError) as exc: self.log_exc(u"String '%s' is not a valid id format" % (id_format), exc, True, ValueError) return id_format
[ "def", "_get_id_format", "(", "self", ")", ":", "id_format", "=", "gf", ".", "safe_get", "(", "self", ".", "parameters", ",", "gc", ".", "PPN_TASK_OS_FILE_ID_REGEX", ",", "self", ".", "DEFAULT_ID_FORMAT", ",", "can_return_none", "=", "False", ")", "try", ":", "identifier", "=", "id_format", "%", "1", "except", "(", "TypeError", ",", "ValueError", ")", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"String '%s' is not a valid id format\"", "%", "(", "id_format", ")", ",", "exc", ",", "True", ",", "ValueError", ")", "return", "id_format" ]
Return the id regex from the parameters
[ "Return", "the", "id", "regex", "from", "the", "parameters" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L980-L992
232,242
readbeyond/aeneas
aeneas/textfile.py
TextFile._create_text_fragments
def _create_text_fragments(self, pairs): """ Create text fragment objects and append them to this list. :param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n]) """ self.log(u"Creating TextFragment objects") text_filter = self._build_text_filter() for pair in pairs: self.add_fragment( TextFragment( identifier=pair[0], lines=pair[1], filtered_lines=text_filter.apply_filter(pair[1]) ) )
python
def _create_text_fragments(self, pairs): """ Create text fragment objects and append them to this list. :param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n]) """ self.log(u"Creating TextFragment objects") text_filter = self._build_text_filter() for pair in pairs: self.add_fragment( TextFragment( identifier=pair[0], lines=pair[1], filtered_lines=text_filter.apply_filter(pair[1]) ) )
[ "def", "_create_text_fragments", "(", "self", ",", "pairs", ")", ":", "self", ".", "log", "(", "u\"Creating TextFragment objects\"", ")", "text_filter", "=", "self", ".", "_build_text_filter", "(", ")", "for", "pair", "in", "pairs", ":", "self", ".", "add_fragment", "(", "TextFragment", "(", "identifier", "=", "pair", "[", "0", "]", ",", "lines", "=", "pair", "[", "1", "]", ",", "filtered_lines", "=", "text_filter", ".", "apply_filter", "(", "pair", "[", "1", "]", ")", ")", ")" ]
Create text fragment objects and append them to this list. :param list pairs: a list of pairs, each pair being (id, [line_1, ..., line_n])
[ "Create", "text", "fragment", "objects", "and", "append", "them", "to", "this", "list", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L994-L1009
232,243
readbeyond/aeneas
aeneas/textfile.py
TextFile._build_text_filter
def _build_text_filter(self): """ Build a suitable TextFilter object. """ text_filter = TextFilter(logger=self.logger) self.log(u"Created TextFilter object") for key, cls, param_name in [ ( gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX, TextFilterIgnoreRegex, "regex" ), ( gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP, TextFilterTransliterate, "map_file_path" ) ]: cls_name = cls.__name__ param_value = gf.safe_get(self.parameters, key, None) if param_value is not None: self.log([u"Creating %s object...", cls_name]) params = { param_name: param_value, "logger": self.logger } try: inner_filter = cls(**params) text_filter.add_filter(inner_filter) self.log([u"Creating %s object... done", cls_name]) except ValueError as exc: self.log_exc(u"Creating %s object failed" % (cls_name), exc, False, None) return text_filter
python
def _build_text_filter(self): """ Build a suitable TextFilter object. """ text_filter = TextFilter(logger=self.logger) self.log(u"Created TextFilter object") for key, cls, param_name in [ ( gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX, TextFilterIgnoreRegex, "regex" ), ( gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP, TextFilterTransliterate, "map_file_path" ) ]: cls_name = cls.__name__ param_value = gf.safe_get(self.parameters, key, None) if param_value is not None: self.log([u"Creating %s object...", cls_name]) params = { param_name: param_value, "logger": self.logger } try: inner_filter = cls(**params) text_filter.add_filter(inner_filter) self.log([u"Creating %s object... done", cls_name]) except ValueError as exc: self.log_exc(u"Creating %s object failed" % (cls_name), exc, False, None) return text_filter
[ "def", "_build_text_filter", "(", "self", ")", ":", "text_filter", "=", "TextFilter", "(", "logger", "=", "self", ".", "logger", ")", "self", ".", "log", "(", "u\"Created TextFilter object\"", ")", "for", "key", ",", "cls", ",", "param_name", "in", "[", "(", "gc", ".", "PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX", ",", "TextFilterIgnoreRegex", ",", "\"regex\"", ")", ",", "(", "gc", ".", "PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP", ",", "TextFilterTransliterate", ",", "\"map_file_path\"", ")", "]", ":", "cls_name", "=", "cls", ".", "__name__", "param_value", "=", "gf", ".", "safe_get", "(", "self", ".", "parameters", ",", "key", ",", "None", ")", "if", "param_value", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"Creating %s object...\"", ",", "cls_name", "]", ")", "params", "=", "{", "param_name", ":", "param_value", ",", "\"logger\"", ":", "self", ".", "logger", "}", "try", ":", "inner_filter", "=", "cls", "(", "*", "*", "params", ")", "text_filter", ".", "add_filter", "(", "inner_filter", ")", "self", ".", "log", "(", "[", "u\"Creating %s object... done\"", ",", "cls_name", "]", ")", "except", "ValueError", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"Creating %s object failed\"", "%", "(", "cls_name", ")", ",", "exc", ",", "False", ",", "None", ")", "return", "text_filter" ]
Build a suitable TextFilter object.
[ "Build", "a", "suitable", "TextFilter", "object", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1011-L1043
232,244
readbeyond/aeneas
aeneas/textfile.py
TextFilter.add_filter
def add_filter(self, new_filter, as_last=True): """ Compose this filter with the given ``new_filter`` filter. :param new_filter: the filter to be composed :type new_filter: :class:`~aeneas.textfile.TextFilter` :param bool as_last: if ``True``, compose to the right, otherwise to the left """ if as_last: self.filters.append(new_filter) else: self.filters = [new_filter] + self.filters
python
def add_filter(self, new_filter, as_last=True): """ Compose this filter with the given ``new_filter`` filter. :param new_filter: the filter to be composed :type new_filter: :class:`~aeneas.textfile.TextFilter` :param bool as_last: if ``True``, compose to the right, otherwise to the left """ if as_last: self.filters.append(new_filter) else: self.filters = [new_filter] + self.filters
[ "def", "add_filter", "(", "self", ",", "new_filter", ",", "as_last", "=", "True", ")", ":", "if", "as_last", ":", "self", ".", "filters", ".", "append", "(", "new_filter", ")", "else", ":", "self", ".", "filters", "=", "[", "new_filter", "]", "+", "self", ".", "filters" ]
Compose this filter with the given ``new_filter`` filter. :param new_filter: the filter to be composed :type new_filter: :class:`~aeneas.textfile.TextFilter` :param bool as_last: if ``True``, compose to the right, otherwise to the left
[ "Compose", "this", "filter", "with", "the", "given", "new_filter", "filter", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1071-L1082
232,245
readbeyond/aeneas
aeneas/textfile.py
TextFilter.apply_filter
def apply_filter(self, strings): """ Apply the text filter filter to the given list of strings. :param list strings: the list of input strings """ result = strings for filt in self.filters: result = filt.apply_filter(result) self.log([u"Applying regex: '%s' => '%s'", strings, result]) return result
python
def apply_filter(self, strings): """ Apply the text filter filter to the given list of strings. :param list strings: the list of input strings """ result = strings for filt in self.filters: result = filt.apply_filter(result) self.log([u"Applying regex: '%s' => '%s'", strings, result]) return result
[ "def", "apply_filter", "(", "self", ",", "strings", ")", ":", "result", "=", "strings", "for", "filt", "in", "self", ".", "filters", ":", "result", "=", "filt", ".", "apply_filter", "(", "result", ")", "self", ".", "log", "(", "[", "u\"Applying regex: '%s' => '%s'\"", ",", "strings", ",", "result", "]", ")", "return", "result" ]
Apply the text filter filter to the given list of strings. :param list strings: the list of input strings
[ "Apply", "the", "text", "filter", "filter", "to", "the", "given", "list", "of", "strings", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1084-L1094
232,246
readbeyond/aeneas
aeneas/textfile.py
TransliterationMap._build_map
def _build_map(self): """ Read the map file at path. """ if gf.is_py2_narrow_build(): self.log_warn(u"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.") self.trans_map = {} with io.open(self.file_path, "r", encoding="utf-8") as file_obj: contents = file_obj.read().replace(u"\t", u" ") for line in contents.splitlines(): # ignore lines starting with "#" or blank (after stripping) if not line.startswith(u"#"): line = line.strip() if len(line) > 0: self._process_map_rule(line)
python
def _build_map(self): """ Read the map file at path. """ if gf.is_py2_narrow_build(): self.log_warn(u"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.") self.trans_map = {} with io.open(self.file_path, "r", encoding="utf-8") as file_obj: contents = file_obj.read().replace(u"\t", u" ") for line in contents.splitlines(): # ignore lines starting with "#" or blank (after stripping) if not line.startswith(u"#"): line = line.strip() if len(line) > 0: self._process_map_rule(line)
[ "def", "_build_map", "(", "self", ")", ":", "if", "gf", ".", "is_py2_narrow_build", "(", ")", ":", "self", ".", "log_warn", "(", "u\"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.\"", ")", "self", ".", "trans_map", "=", "{", "}", "with", "io", ".", "open", "(", "self", ".", "file_path", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", ".", "replace", "(", "u\"\\t\"", ",", "u\" \"", ")", "for", "line", "in", "contents", ".", "splitlines", "(", ")", ":", "# ignore lines starting with \"#\" or blank (after stripping)", "if", "not", "line", ".", "startswith", "(", "u\"#\"", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "len", "(", "line", ")", ">", "0", ":", "self", ".", "_process_map_rule", "(", "line", ")" ]
Read the map file at path.
[ "Read", "the", "map", "file", "at", "path", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1241-L1255
232,247
readbeyond/aeneas
aeneas/textfile.py
TransliterationMap._process_map_rule
def _process_map_rule(self, line): """ Process the line string containing a map rule. """ result = self.REPLACE_REGEX.match(line) if result is not None: what = self._process_first_group(result.group(1)) replacement = self._process_second_group(result.group(2)) for char in what: self.trans_map[char] = replacement self.log([u"Adding rule: replace '%s' with '%s'", char, replacement]) else: result = self.DELETE_REGEX.match(line) if result is not None: what = self._process_first_group(result.group(1)) for char in what: self.trans_map[char] = "" self.log([u"Adding rule: delete '%s'", char])
python
def _process_map_rule(self, line): """ Process the line string containing a map rule. """ result = self.REPLACE_REGEX.match(line) if result is not None: what = self._process_first_group(result.group(1)) replacement = self._process_second_group(result.group(2)) for char in what: self.trans_map[char] = replacement self.log([u"Adding rule: replace '%s' with '%s'", char, replacement]) else: result = self.DELETE_REGEX.match(line) if result is not None: what = self._process_first_group(result.group(1)) for char in what: self.trans_map[char] = "" self.log([u"Adding rule: delete '%s'", char])
[ "def", "_process_map_rule", "(", "self", ",", "line", ")", ":", "result", "=", "self", ".", "REPLACE_REGEX", ".", "match", "(", "line", ")", "if", "result", "is", "not", "None", ":", "what", "=", "self", ".", "_process_first_group", "(", "result", ".", "group", "(", "1", ")", ")", "replacement", "=", "self", ".", "_process_second_group", "(", "result", ".", "group", "(", "2", ")", ")", "for", "char", "in", "what", ":", "self", ".", "trans_map", "[", "char", "]", "=", "replacement", "self", ".", "log", "(", "[", "u\"Adding rule: replace '%s' with '%s'\"", ",", "char", ",", "replacement", "]", ")", "else", ":", "result", "=", "self", ".", "DELETE_REGEX", ".", "match", "(", "line", ")", "if", "result", "is", "not", "None", ":", "what", "=", "self", ".", "_process_first_group", "(", "result", ".", "group", "(", "1", ")", ")", "for", "char", "in", "what", ":", "self", ".", "trans_map", "[", "char", "]", "=", "\"\"", "self", ".", "log", "(", "[", "u\"Adding rule: delete '%s'\"", ",", "char", "]", ")" ]
Process the line string containing a map rule.
[ "Process", "the", "line", "string", "containing", "a", "map", "rule", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1257-L1274
232,248
readbeyond/aeneas
aeneas/textfile.py
TransliterationMap._process_first_group
def _process_first_group(self, group): """ Process the first group of a rule. """ if "-" in group: # range if len(group.split("-")) == 2: arr = group.split("-") start = self._parse_codepoint(arr[0]) end = self._parse_codepoint(arr[1]) else: # single char/U+xxxx start = self._parse_codepoint(group) end = start result = [] if (start > -1) and (end >= start): for index in range(start, end + 1): result.append(gf.safe_unichr(index)) return result
python
def _process_first_group(self, group): """ Process the first group of a rule. """ if "-" in group: # range if len(group.split("-")) == 2: arr = group.split("-") start = self._parse_codepoint(arr[0]) end = self._parse_codepoint(arr[1]) else: # single char/U+xxxx start = self._parse_codepoint(group) end = start result = [] if (start > -1) and (end >= start): for index in range(start, end + 1): result.append(gf.safe_unichr(index)) return result
[ "def", "_process_first_group", "(", "self", ",", "group", ")", ":", "if", "\"-\"", "in", "group", ":", "# range", "if", "len", "(", "group", ".", "split", "(", "\"-\"", ")", ")", "==", "2", ":", "arr", "=", "group", ".", "split", "(", "\"-\"", ")", "start", "=", "self", ".", "_parse_codepoint", "(", "arr", "[", "0", "]", ")", "end", "=", "self", ".", "_parse_codepoint", "(", "arr", "[", "1", "]", ")", "else", ":", "# single char/U+xxxx", "start", "=", "self", ".", "_parse_codepoint", "(", "group", ")", "end", "=", "start", "result", "=", "[", "]", "if", "(", "start", ">", "-", "1", ")", "and", "(", "end", ">=", "start", ")", ":", "for", "index", "in", "range", "(", "start", ",", "end", "+", "1", ")", ":", "result", ".", "append", "(", "gf", ".", "safe_unichr", "(", "index", ")", ")", "return", "result" ]
Process the first group of a rule.
[ "Process", "the", "first", "group", "of", "a", "rule", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1276-L1294
232,249
readbeyond/aeneas
aeneas/executejob.py
ExecuteJob.load_job
def load_job(self, job): """ Load the job from the given ``Job`` object. :param job: the job to load :type job: :class:`~aeneas.job.Job` :raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job` """ if not isinstance(job, Job): self.log_exc(u"job is not an instance of Job", None, True, ExecuteJobInputError) self.job = job
python
def load_job(self, job): """ Load the job from the given ``Job`` object. :param job: the job to load :type job: :class:`~aeneas.job.Job` :raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job` """ if not isinstance(job, Job): self.log_exc(u"job is not an instance of Job", None, True, ExecuteJobInputError) self.job = job
[ "def", "load_job", "(", "self", ",", "job", ")", ":", "if", "not", "isinstance", "(", "job", ",", "Job", ")", ":", "self", ".", "log_exc", "(", "u\"job is not an instance of Job\"", ",", "None", ",", "True", ",", "ExecuteJobInputError", ")", "self", ".", "job", "=", "job" ]
Load the job from the given ``Job`` object. :param job: the job to load :type job: :class:`~aeneas.job.Job` :raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job`
[ "Load", "the", "job", "from", "the", "given", "Job", "object", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L110-L120
232,250
readbeyond/aeneas
aeneas/executejob.py
ExecuteJob.execute
def execute(self): """ Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution """ self.log(u"Executing job") if self.job is None: self.log_exc(u"The job object is None", None, True, ExecuteJobExecutionError) if len(self.job) == 0: self.log_exc(u"The job has no tasks", None, True, ExecuteJobExecutionError) job_max_tasks = self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] if (job_max_tasks > 0) and (len(self.job) > job_max_tasks): self.log_exc(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (len(self.job), job_max_tasks), None, True, ExecuteJobExecutionError) self.log([u"Number of tasks: '%d'", len(self.job)]) for task in self.job.tasks: try: custom_id = task.configuration["custom_id"] self.log([u"Executing task '%s'...", custom_id]) executor = ExecuteTask(task, rconf=self.rconf, logger=self.logger) executor.execute() self.log([u"Executing task '%s'... done", custom_id]) except Exception as exc: self.log_exc(u"Error while executing task '%s'" % (custom_id), exc, True, ExecuteJobExecutionError) self.log(u"Executing task: succeeded") self.log(u"Executing job: succeeded")
python
def execute(self): """ Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution """ self.log(u"Executing job") if self.job is None: self.log_exc(u"The job object is None", None, True, ExecuteJobExecutionError) if len(self.job) == 0: self.log_exc(u"The job has no tasks", None, True, ExecuteJobExecutionError) job_max_tasks = self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] if (job_max_tasks > 0) and (len(self.job) > job_max_tasks): self.log_exc(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (len(self.job), job_max_tasks), None, True, ExecuteJobExecutionError) self.log([u"Number of tasks: '%d'", len(self.job)]) for task in self.job.tasks: try: custom_id = task.configuration["custom_id"] self.log([u"Executing task '%s'...", custom_id]) executor = ExecuteTask(task, rconf=self.rconf, logger=self.logger) executor.execute() self.log([u"Executing task '%s'... done", custom_id]) except Exception as exc: self.log_exc(u"Error while executing task '%s'" % (custom_id), exc, True, ExecuteJobExecutionError) self.log(u"Executing task: succeeded") self.log(u"Executing job: succeeded")
[ "def", "execute", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Executing job\"", ")", "if", "self", ".", "job", "is", "None", ":", "self", ".", "log_exc", "(", "u\"The job object is None\"", ",", "None", ",", "True", ",", "ExecuteJobExecutionError", ")", "if", "len", "(", "self", ".", "job", ")", "==", "0", ":", "self", ".", "log_exc", "(", "u\"The job has no tasks\"", ",", "None", ",", "True", ",", "ExecuteJobExecutionError", ")", "job_max_tasks", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "JOB_MAX_TASKS", "]", "if", "(", "job_max_tasks", ">", "0", ")", "and", "(", "len", "(", "self", ".", "job", ")", ">", "job_max_tasks", ")", ":", "self", ".", "log_exc", "(", "u\"The Job has %d Tasks, more than the maximum allowed (%d).\"", "%", "(", "len", "(", "self", ".", "job", ")", ",", "job_max_tasks", ")", ",", "None", ",", "True", ",", "ExecuteJobExecutionError", ")", "self", ".", "log", "(", "[", "u\"Number of tasks: '%d'\"", ",", "len", "(", "self", ".", "job", ")", "]", ")", "for", "task", "in", "self", ".", "job", ".", "tasks", ":", "try", ":", "custom_id", "=", "task", ".", "configuration", "[", "\"custom_id\"", "]", "self", ".", "log", "(", "[", "u\"Executing task '%s'...\"", ",", "custom_id", "]", ")", "executor", "=", "ExecuteTask", "(", "task", ",", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", "executor", ".", "execute", "(", ")", "self", ".", "log", "(", "[", "u\"Executing task '%s'... done\"", ",", "custom_id", "]", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"Error while executing task '%s'\"", "%", "(", "custom_id", ")", ",", "exc", ",", "True", ",", "ExecuteJobExecutionError", ")", "self", ".", "log", "(", "u\"Executing task: succeeded\"", ")", "self", ".", "log", "(", "u\"Executing job: succeeded\"", ")" ]
Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
[ "Execute", "the", "job", "that", "is", "execute", "all", "of", "its", "tasks", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L187-L218
232,251
readbeyond/aeneas
aeneas/executejob.py
ExecuteJob.write_output_container
def write_output_container(self, output_directory_path): """ Write the output container for this job. Return the path to output container, which is the concatenation of ``output_directory_path`` and of the output container file or directory name. :param string output_directory_path: the path to a directory where the output container must be created :rtype: string :raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container """ self.log(u"Writing output container for this job") if self.job is None: self.log_exc(u"The job object is None", None, True, ExecuteJobOutputError) if len(self.job) == 0: self.log_exc(u"The job has no tasks", None, True, ExecuteJobOutputError) self.log([u"Number of tasks: '%d'", len(self.job)]) # create temporary directory where the sync map files # will be created # this temporary directory will be compressed into # the output container self.tmp_directory = gf.tmp_directory(root=self.rconf[RuntimeConfiguration.TMP_PATH]) self.log([u"Created temporary directory '%s'", self.tmp_directory]) for task in self.job.tasks: custom_id = task.configuration["custom_id"] # check if the task has sync map and sync map file path if task.sync_map_file_path is None: self.log_exc(u"Task '%s' has sync_map_file_path not set" % (custom_id), None, True, ExecuteJobOutputError) if task.sync_map is None: self.log_exc(u"Task '%s' has sync_map not set" % (custom_id), None, True, ExecuteJobOutputError) try: # output sync map self.log([u"Outputting sync map for task '%s'...", custom_id]) task.output_sync_map_file(self.tmp_directory) self.log([u"Outputting sync map for task '%s'... done", custom_id]) except Exception as exc: self.log_exc(u"Error while outputting sync map for task '%s'" % (custom_id), None, True, ExecuteJobOutputError) # get output container info output_container_format = self.job.configuration["o_container_format"] self.log([u"Output container format: '%s'", output_container_format]) output_file_name = self.job.configuration["o_name"] if ((output_container_format != ContainerFormat.UNPACKED) and (not output_file_name.endswith(output_container_format))): self.log(u"Adding extension to output_file_name") output_file_name += "." + output_container_format self.log([u"Output file name: '%s'", output_file_name]) output_file_path = gf.norm_join( output_directory_path, output_file_name ) self.log([u"Output file path: '%s'", output_file_path]) try: self.log(u"Compressing...") container = Container( output_file_path, output_container_format, logger=self.logger ) container.compress(self.tmp_directory) self.log(u"Compressing... done") self.log([u"Created output file: '%s'", output_file_path]) self.log(u"Writing output container for this job: succeeded") self.clean(False) return output_file_path except Exception as exc: self.clean(False) self.log_exc(u"Error while compressing", exc, True, ExecuteJobOutputError) return None
python
def write_output_container(self, output_directory_path): """ Write the output container for this job. Return the path to output container, which is the concatenation of ``output_directory_path`` and of the output container file or directory name. :param string output_directory_path: the path to a directory where the output container must be created :rtype: string :raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container """ self.log(u"Writing output container for this job") if self.job is None: self.log_exc(u"The job object is None", None, True, ExecuteJobOutputError) if len(self.job) == 0: self.log_exc(u"The job has no tasks", None, True, ExecuteJobOutputError) self.log([u"Number of tasks: '%d'", len(self.job)]) # create temporary directory where the sync map files # will be created # this temporary directory will be compressed into # the output container self.tmp_directory = gf.tmp_directory(root=self.rconf[RuntimeConfiguration.TMP_PATH]) self.log([u"Created temporary directory '%s'", self.tmp_directory]) for task in self.job.tasks: custom_id = task.configuration["custom_id"] # check if the task has sync map and sync map file path if task.sync_map_file_path is None: self.log_exc(u"Task '%s' has sync_map_file_path not set" % (custom_id), None, True, ExecuteJobOutputError) if task.sync_map is None: self.log_exc(u"Task '%s' has sync_map not set" % (custom_id), None, True, ExecuteJobOutputError) try: # output sync map self.log([u"Outputting sync map for task '%s'...", custom_id]) task.output_sync_map_file(self.tmp_directory) self.log([u"Outputting sync map for task '%s'... done", custom_id]) except Exception as exc: self.log_exc(u"Error while outputting sync map for task '%s'" % (custom_id), None, True, ExecuteJobOutputError) # get output container info output_container_format = self.job.configuration["o_container_format"] self.log([u"Output container format: '%s'", output_container_format]) output_file_name = self.job.configuration["o_name"] if ((output_container_format != ContainerFormat.UNPACKED) and (not output_file_name.endswith(output_container_format))): self.log(u"Adding extension to output_file_name") output_file_name += "." + output_container_format self.log([u"Output file name: '%s'", output_file_name]) output_file_path = gf.norm_join( output_directory_path, output_file_name ) self.log([u"Output file path: '%s'", output_file_path]) try: self.log(u"Compressing...") container = Container( output_file_path, output_container_format, logger=self.logger ) container.compress(self.tmp_directory) self.log(u"Compressing... done") self.log([u"Created output file: '%s'", output_file_path]) self.log(u"Writing output container for this job: succeeded") self.clean(False) return output_file_path except Exception as exc: self.clean(False) self.log_exc(u"Error while compressing", exc, True, ExecuteJobOutputError) return None
[ "def", "write_output_container", "(", "self", ",", "output_directory_path", ")", ":", "self", ".", "log", "(", "u\"Writing output container for this job\"", ")", "if", "self", ".", "job", "is", "None", ":", "self", ".", "log_exc", "(", "u\"The job object is None\"", ",", "None", ",", "True", ",", "ExecuteJobOutputError", ")", "if", "len", "(", "self", ".", "job", ")", "==", "0", ":", "self", ".", "log_exc", "(", "u\"The job has no tasks\"", ",", "None", ",", "True", ",", "ExecuteJobOutputError", ")", "self", ".", "log", "(", "[", "u\"Number of tasks: '%d'\"", ",", "len", "(", "self", ".", "job", ")", "]", ")", "# create temporary directory where the sync map files", "# will be created", "# this temporary directory will be compressed into", "# the output container", "self", ".", "tmp_directory", "=", "gf", ".", "tmp_directory", "(", "root", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "TMP_PATH", "]", ")", "self", ".", "log", "(", "[", "u\"Created temporary directory '%s'\"", ",", "self", ".", "tmp_directory", "]", ")", "for", "task", "in", "self", ".", "job", ".", "tasks", ":", "custom_id", "=", "task", ".", "configuration", "[", "\"custom_id\"", "]", "# check if the task has sync map and sync map file path", "if", "task", ".", "sync_map_file_path", "is", "None", ":", "self", ".", "log_exc", "(", "u\"Task '%s' has sync_map_file_path not set\"", "%", "(", "custom_id", ")", ",", "None", ",", "True", ",", "ExecuteJobOutputError", ")", "if", "task", ".", "sync_map", "is", "None", ":", "self", ".", "log_exc", "(", "u\"Task '%s' has sync_map not set\"", "%", "(", "custom_id", ")", ",", "None", ",", "True", ",", "ExecuteJobOutputError", ")", "try", ":", "# output sync map", "self", ".", "log", "(", "[", "u\"Outputting sync map for task '%s'...\"", ",", "custom_id", "]", ")", "task", ".", "output_sync_map_file", "(", "self", ".", "tmp_directory", ")", "self", ".", "log", "(", "[", "u\"Outputting sync map for task '%s'... done\"", ",", "custom_id", "]", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"Error while outputting sync map for task '%s'\"", "%", "(", "custom_id", ")", ",", "None", ",", "True", ",", "ExecuteJobOutputError", ")", "# get output container info", "output_container_format", "=", "self", ".", "job", ".", "configuration", "[", "\"o_container_format\"", "]", "self", ".", "log", "(", "[", "u\"Output container format: '%s'\"", ",", "output_container_format", "]", ")", "output_file_name", "=", "self", ".", "job", ".", "configuration", "[", "\"o_name\"", "]", "if", "(", "(", "output_container_format", "!=", "ContainerFormat", ".", "UNPACKED", ")", "and", "(", "not", "output_file_name", ".", "endswith", "(", "output_container_format", ")", ")", ")", ":", "self", ".", "log", "(", "u\"Adding extension to output_file_name\"", ")", "output_file_name", "+=", "\".\"", "+", "output_container_format", "self", ".", "log", "(", "[", "u\"Output file name: '%s'\"", ",", "output_file_name", "]", ")", "output_file_path", "=", "gf", ".", "norm_join", "(", "output_directory_path", ",", "output_file_name", ")", "self", ".", "log", "(", "[", "u\"Output file path: '%s'\"", ",", "output_file_path", "]", ")", "try", ":", "self", ".", "log", "(", "u\"Compressing...\"", ")", "container", "=", "Container", "(", "output_file_path", ",", "output_container_format", ",", "logger", "=", "self", ".", "logger", ")", "container", ".", "compress", "(", "self", ".", "tmp_directory", ")", "self", ".", "log", "(", "u\"Compressing... done\"", ")", "self", ".", "log", "(", "[", "u\"Created output file: '%s'\"", ",", "output_file_path", "]", ")", "self", ".", "log", "(", "u\"Writing output container for this job: succeeded\"", ")", "self", ".", "clean", "(", "False", ")", "return", "output_file_path", "except", "Exception", "as", "exc", ":", "self", ".", "clean", "(", "False", ")", "self", ".", "log_exc", "(", "u\"Error while compressing\"", ",", "exc", ",", "True", ",", "ExecuteJobOutputError", ")", "return", "None" ]
Write the output container for this job. Return the path to output container, which is the concatenation of ``output_directory_path`` and of the output container file or directory name. :param string output_directory_path: the path to a directory where the output container must be created :rtype: string :raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container
[ "Write", "the", "output", "container", "for", "this", "job", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L220-L296
232,252
readbeyond/aeneas
aeneas/executejob.py
ExecuteJob.clean
def clean(self, remove_working_directory=True): """ Remove the temporary directory. If ``remove_working_directory`` is ``True`` remove the working directory as well, otherwise just remove the temporary directory. :param bool remove_working_directory: if ``True``, remove the working directory as well """ if remove_working_directory is not None: self.log(u"Removing working directory... ") gf.delete_directory(self.working_directory) self.working_directory = None self.log(u"Removing working directory... done") self.log(u"Removing temporary directory... ") gf.delete_directory(self.tmp_directory) self.tmp_directory = None self.log(u"Removing temporary directory... done")
python
def clean(self, remove_working_directory=True): """ Remove the temporary directory. If ``remove_working_directory`` is ``True`` remove the working directory as well, otherwise just remove the temporary directory. :param bool remove_working_directory: if ``True``, remove the working directory as well """ if remove_working_directory is not None: self.log(u"Removing working directory... ") gf.delete_directory(self.working_directory) self.working_directory = None self.log(u"Removing working directory... done") self.log(u"Removing temporary directory... ") gf.delete_directory(self.tmp_directory) self.tmp_directory = None self.log(u"Removing temporary directory... done")
[ "def", "clean", "(", "self", ",", "remove_working_directory", "=", "True", ")", ":", "if", "remove_working_directory", "is", "not", "None", ":", "self", ".", "log", "(", "u\"Removing working directory... \"", ")", "gf", ".", "delete_directory", "(", "self", ".", "working_directory", ")", "self", ".", "working_directory", "=", "None", "self", ".", "log", "(", "u\"Removing working directory... done\"", ")", "self", ".", "log", "(", "u\"Removing temporary directory... \"", ")", "gf", ".", "delete_directory", "(", "self", ".", "tmp_directory", ")", "self", ".", "tmp_directory", "=", "None", "self", ".", "log", "(", "u\"Removing temporary directory... done\"", ")" ]
Remove the temporary directory. If ``remove_working_directory`` is ``True`` remove the working directory as well, otherwise just remove the temporary directory. :param bool remove_working_directory: if ``True``, remove the working directory as well
[ "Remove", "the", "temporary", "directory", ".", "If", "remove_working_directory", "is", "True", "remove", "the", "working", "directory", "as", "well", "otherwise", "just", "remove", "the", "temporary", "directory", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L298-L316
232,253
readbeyond/aeneas
aeneas/tools/plot_waveform.py
PlotWaveformCLI._read_syncmap_file
def _read_syncmap_file(self, path, extension, text=False): """ Read labels from a SyncMap file """ syncmap = SyncMap(logger=self.logger) syncmap.read(extension, path, parameters=None) if text: return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragments] return [(f.begin, f.end, f.text_fragment.identifier) for f in syncmap.fragments]
python
def _read_syncmap_file(self, path, extension, text=False): """ Read labels from a SyncMap file """ syncmap = SyncMap(logger=self.logger) syncmap.read(extension, path, parameters=None) if text: return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragments] return [(f.begin, f.end, f.text_fragment.identifier) for f in syncmap.fragments]
[ "def", "_read_syncmap_file", "(", "self", ",", "path", ",", "extension", ",", "text", "=", "False", ")", ":", "syncmap", "=", "SyncMap", "(", "logger", "=", "self", ".", "logger", ")", "syncmap", ".", "read", "(", "extension", ",", "path", ",", "parameters", "=", "None", ")", "if", "text", ":", "return", "[", "(", "f", ".", "begin", ",", "f", ".", "end", ",", "u\" \"", ".", "join", "(", "f", ".", "text_fragment", ".", "lines", ")", ")", "for", "f", "in", "syncmap", ".", "fragments", "]", "return", "[", "(", "f", ".", "begin", ",", "f", ".", "end", ",", "f", ".", "text_fragment", ".", "identifier", ")", "for", "f", "in", "syncmap", ".", "fragments", "]" ]
Read labels from a SyncMap file
[ "Read", "labels", "from", "a", "SyncMap", "file" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/plot_waveform.py#L156-L162
232,254
readbeyond/aeneas
aeneas/syncmap/__init__.py
SyncMap.has_adjacent_leaves_only
def has_adjacent_leaves_only(self): """ Return ``True`` if the sync map fragments which are the leaves of the sync map tree are all adjacent. :rtype: bool .. versionadded:: 1.7.0 """ leaves = self.leaves() for i in range(len(leaves) - 1): current_interval = leaves[i].interval next_interval = leaves[i + 1].interval if not current_interval.is_adjacent_before(next_interval): return False return True
python
def has_adjacent_leaves_only(self): """ Return ``True`` if the sync map fragments which are the leaves of the sync map tree are all adjacent. :rtype: bool .. versionadded:: 1.7.0 """ leaves = self.leaves() for i in range(len(leaves) - 1): current_interval = leaves[i].interval next_interval = leaves[i + 1].interval if not current_interval.is_adjacent_before(next_interval): return False return True
[ "def", "has_adjacent_leaves_only", "(", "self", ")", ":", "leaves", "=", "self", ".", "leaves", "(", ")", "for", "i", "in", "range", "(", "len", "(", "leaves", ")", "-", "1", ")", ":", "current_interval", "=", "leaves", "[", "i", "]", ".", "interval", "next_interval", "=", "leaves", "[", "i", "+", "1", "]", ".", "interval", "if", "not", "current_interval", ".", "is_adjacent_before", "(", "next_interval", ")", ":", "return", "False", "return", "True" ]
Return ``True`` if the sync map fragments which are the leaves of the sync map tree are all adjacent. :rtype: bool .. versionadded:: 1.7.0
[ "Return", "True", "if", "the", "sync", "map", "fragments", "which", "are", "the", "leaves", "of", "the", "sync", "map", "tree", "are", "all", "adjacent", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L169-L185
232,255
readbeyond/aeneas
aeneas/syncmap/__init__.py
SyncMap.json_string
def json_string(self): """ Return a JSON representation of the sync map. :rtype: string .. versionadded:: 1.3.1 """ def visit_children(node): """ Recursively visit the fragments_tree """ output_fragments = [] for child in node.children_not_empty: fragment = child.value text = fragment.text_fragment output_fragments.append({ "id": text.identifier, "language": text.language, "lines": text.lines, "begin": gf.time_to_ssmmm(fragment.begin), "end": gf.time_to_ssmmm(fragment.end), "children": visit_children(child) }) return output_fragments output_fragments = visit_children(self.fragments_tree) return gf.safe_unicode( json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True) )
python
def json_string(self): """ Return a JSON representation of the sync map. :rtype: string .. versionadded:: 1.3.1 """ def visit_children(node): """ Recursively visit the fragments_tree """ output_fragments = [] for child in node.children_not_empty: fragment = child.value text = fragment.text_fragment output_fragments.append({ "id": text.identifier, "language": text.language, "lines": text.lines, "begin": gf.time_to_ssmmm(fragment.begin), "end": gf.time_to_ssmmm(fragment.end), "children": visit_children(child) }) return output_fragments output_fragments = visit_children(self.fragments_tree) return gf.safe_unicode( json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True) )
[ "def", "json_string", "(", "self", ")", ":", "def", "visit_children", "(", "node", ")", ":", "\"\"\" Recursively visit the fragments_tree \"\"\"", "output_fragments", "=", "[", "]", "for", "child", "in", "node", ".", "children_not_empty", ":", "fragment", "=", "child", ".", "value", "text", "=", "fragment", ".", "text_fragment", "output_fragments", ".", "append", "(", "{", "\"id\"", ":", "text", ".", "identifier", ",", "\"language\"", ":", "text", ".", "language", ",", "\"lines\"", ":", "text", ".", "lines", ",", "\"begin\"", ":", "gf", ".", "time_to_ssmmm", "(", "fragment", ".", "begin", ")", ",", "\"end\"", ":", "gf", ".", "time_to_ssmmm", "(", "fragment", ".", "end", ")", ",", "\"children\"", ":", "visit_children", "(", "child", ")", "}", ")", "return", "output_fragments", "output_fragments", "=", "visit_children", "(", "self", ".", "fragments_tree", ")", "return", "gf", ".", "safe_unicode", "(", "json", ".", "dumps", "(", "{", "\"fragments\"", ":", "output_fragments", "}", ",", "indent", "=", "1", ",", "sort_keys", "=", "True", ")", ")" ]
Return a JSON representation of the sync map. :rtype: string .. versionadded:: 1.3.1
[ "Return", "a", "JSON", "representation", "of", "the", "sync", "map", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L248-L274
232,256
readbeyond/aeneas
aeneas/syncmap/__init__.py
SyncMap.add_fragment
def add_fragment(self, fragment, as_last=True): """ Add the given sync map fragment, as the first or last child of the root node of the sync map tree. :param fragment: the sync map fragment to be added :type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment` :param bool as_last: if ``True``, append fragment; otherwise prepend it :raises: TypeError: if ``fragment`` is ``None`` or it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment` """ if not isinstance(fragment, SyncMapFragment): self.log_exc(u"fragment is not an instance of SyncMapFragment", None, True, TypeError) self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last)
python
def add_fragment(self, fragment, as_last=True): """ Add the given sync map fragment, as the first or last child of the root node of the sync map tree. :param fragment: the sync map fragment to be added :type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment` :param bool as_last: if ``True``, append fragment; otherwise prepend it :raises: TypeError: if ``fragment`` is ``None`` or it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment` """ if not isinstance(fragment, SyncMapFragment): self.log_exc(u"fragment is not an instance of SyncMapFragment", None, True, TypeError) self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last)
[ "def", "add_fragment", "(", "self", ",", "fragment", ",", "as_last", "=", "True", ")", ":", "if", "not", "isinstance", "(", "fragment", ",", "SyncMapFragment", ")", ":", "self", ".", "log_exc", "(", "u\"fragment is not an instance of SyncMapFragment\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "fragments_tree", ".", "add_child", "(", "Tree", "(", "value", "=", "fragment", ")", ",", "as_last", "=", "as_last", ")" ]
Add the given sync map fragment, as the first or last child of the root node of the sync map tree. :param fragment: the sync map fragment to be added :type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment` :param bool as_last: if ``True``, append fragment; otherwise prepend it :raises: TypeError: if ``fragment`` is ``None`` or it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
[ "Add", "the", "given", "sync", "map", "fragment", "as", "the", "first", "or", "last", "child", "of", "the", "root", "node", "of", "the", "sync", "map", "tree", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L276-L290
232,257
readbeyond/aeneas
aeneas/syncmap/__init__.py
SyncMap.output_html_for_tuning
def output_html_for_tuning( self, audio_file_path, output_file_path, parameters=None ): """ Output an HTML file for fine tuning the sync map manually. :param string audio_file_path: the path to the associated audio file :param string output_file_path: the path to the output file to write :param dict parameters: additional parameters .. versionadded:: 1.3.1 """ if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot output HTML file '%s'. Wrong permissions?" % (output_file_path), None, True, OSError) if parameters is None: parameters = {} audio_file_path_absolute = gf.fix_slash(os.path.abspath(audio_file_path)) template_path_absolute = gf.absolute_path(self.FINETUNEAS_PATH, __file__) with io.open(template_path_absolute, "r", encoding="utf-8") as file_obj: template = file_obj.read() for repl in self.FINETUNEAS_REPLACEMENTS: template = template.replace(repl[0], repl[1]) template = template.replace( self.FINETUNEAS_REPLACE_AUDIOFILEPATH, u"audioFilePath = \"file://%s\";" % audio_file_path_absolute ) template = template.replace( self.FINETUNEAS_REPLACE_FRAGMENTS, u"fragments = (%s).fragments;" % self.json_string ) if gc.PPN_TASK_OS_FILE_FORMAT in parameters: output_format = parameters[gc.PPN_TASK_OS_FILE_FORMAT] if output_format in self.FINETUNEAS_ALLOWED_FORMATS: template = template.replace( self.FINETUNEAS_REPLACE_OUTPUT_FORMAT, u"outputFormat = \"%s\";" % output_format ) if output_format == "smil": for key, placeholder, replacement in [ ( gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF, self.FINETUNEAS_REPLACE_SMIL_AUDIOREF, "audioref = \"%s\";" ), ( gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF, self.FINETUNEAS_REPLACE_SMIL_PAGEREF, "pageref = \"%s\";" ), ]: if key in parameters: template = template.replace( placeholder, replacement % parameters[key] ) with io.open(output_file_path, "w", encoding="utf-8") as file_obj: file_obj.write(template)
python
def output_html_for_tuning( self, audio_file_path, output_file_path, parameters=None ): """ Output an HTML file for fine tuning the sync map manually. :param string audio_file_path: the path to the associated audio file :param string output_file_path: the path to the output file to write :param dict parameters: additional parameters .. versionadded:: 1.3.1 """ if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot output HTML file '%s'. Wrong permissions?" % (output_file_path), None, True, OSError) if parameters is None: parameters = {} audio_file_path_absolute = gf.fix_slash(os.path.abspath(audio_file_path)) template_path_absolute = gf.absolute_path(self.FINETUNEAS_PATH, __file__) with io.open(template_path_absolute, "r", encoding="utf-8") as file_obj: template = file_obj.read() for repl in self.FINETUNEAS_REPLACEMENTS: template = template.replace(repl[0], repl[1]) template = template.replace( self.FINETUNEAS_REPLACE_AUDIOFILEPATH, u"audioFilePath = \"file://%s\";" % audio_file_path_absolute ) template = template.replace( self.FINETUNEAS_REPLACE_FRAGMENTS, u"fragments = (%s).fragments;" % self.json_string ) if gc.PPN_TASK_OS_FILE_FORMAT in parameters: output_format = parameters[gc.PPN_TASK_OS_FILE_FORMAT] if output_format in self.FINETUNEAS_ALLOWED_FORMATS: template = template.replace( self.FINETUNEAS_REPLACE_OUTPUT_FORMAT, u"outputFormat = \"%s\";" % output_format ) if output_format == "smil": for key, placeholder, replacement in [ ( gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF, self.FINETUNEAS_REPLACE_SMIL_AUDIOREF, "audioref = \"%s\";" ), ( gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF, self.FINETUNEAS_REPLACE_SMIL_PAGEREF, "pageref = \"%s\";" ), ]: if key in parameters: template = template.replace( placeholder, replacement % parameters[key] ) with io.open(output_file_path, "w", encoding="utf-8") as file_obj: file_obj.write(template)
[ "def", "output_html_for_tuning", "(", "self", ",", "audio_file_path", ",", "output_file_path", ",", "parameters", "=", "None", ")", ":", "if", "not", "gf", ".", "file_can_be_written", "(", "output_file_path", ")", ":", "self", ".", "log_exc", "(", "u\"Cannot output HTML file '%s'. Wrong permissions?\"", "%", "(", "output_file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "if", "parameters", "is", "None", ":", "parameters", "=", "{", "}", "audio_file_path_absolute", "=", "gf", ".", "fix_slash", "(", "os", ".", "path", ".", "abspath", "(", "audio_file_path", ")", ")", "template_path_absolute", "=", "gf", ".", "absolute_path", "(", "self", ".", "FINETUNEAS_PATH", ",", "__file__", ")", "with", "io", ".", "open", "(", "template_path_absolute", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "for", "repl", "in", "self", ".", "FINETUNEAS_REPLACEMENTS", ":", "template", "=", "template", ".", "replace", "(", "repl", "[", "0", "]", ",", "repl", "[", "1", "]", ")", "template", "=", "template", ".", "replace", "(", "self", ".", "FINETUNEAS_REPLACE_AUDIOFILEPATH", ",", "u\"audioFilePath = \\\"file://%s\\\";\"", "%", "audio_file_path_absolute", ")", "template", "=", "template", ".", "replace", "(", "self", ".", "FINETUNEAS_REPLACE_FRAGMENTS", ",", "u\"fragments = (%s).fragments;\"", "%", "self", ".", "json_string", ")", "if", "gc", ".", "PPN_TASK_OS_FILE_FORMAT", "in", "parameters", ":", "output_format", "=", "parameters", "[", "gc", ".", "PPN_TASK_OS_FILE_FORMAT", "]", "if", "output_format", "in", "self", ".", "FINETUNEAS_ALLOWED_FORMATS", ":", "template", "=", "template", ".", "replace", "(", "self", ".", "FINETUNEAS_REPLACE_OUTPUT_FORMAT", ",", "u\"outputFormat = \\\"%s\\\";\"", "%", "output_format", ")", "if", "output_format", "==", "\"smil\"", ":", "for", "key", ",", "placeholder", ",", "replacement", "in", "[", "(", "gc", ".", "PPN_TASK_OS_FILE_SMIL_AUDIO_REF", ",", "self", ".", "FINETUNEAS_REPLACE_SMIL_AUDIOREF", ",", "\"audioref = \\\"%s\\\";\"", ")", ",", "(", "gc", ".", "PPN_TASK_OS_FILE_SMIL_PAGE_REF", ",", "self", ".", "FINETUNEAS_REPLACE_SMIL_PAGEREF", ",", "\"pageref = \\\"%s\\\";\"", ")", ",", "]", ":", "if", "key", "in", "parameters", ":", "template", "=", "template", ".", "replace", "(", "placeholder", ",", "replacement", "%", "parameters", "[", "key", "]", ")", "with", "io", ".", "open", "(", "output_file_path", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "file_obj", ":", "file_obj", ".", "write", "(", "template", ")" ]
Output an HTML file for fine tuning the sync map manually. :param string audio_file_path: the path to the associated audio file :param string output_file_path: the path to the output file to write :param dict parameters: additional parameters .. versionadded:: 1.3.1
[ "Output", "an", "HTML", "file", "for", "fine", "tuning", "the", "sync", "map", "manually", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L309-L368
232,258
readbeyond/aeneas
aeneas/mfcc.py
MFCC._create_dct_matrix
def _create_dct_matrix(self): """ Create the not-quite-DCT matrix as used by Sphinx, and store it in ```self.s2dct```. """ self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size)) for i in range(0, self.mfcc_size): freq = numpy.pi * float(i) / self.filter_bank_size self.s2dct[i] = numpy.cos(freq * numpy.arange(0.5, 0.5 + self.filter_bank_size, 1.0, 'float64')) self.s2dct[:, 0] *= 0.5 self.s2dct = self.s2dct.transpose()
python
def _create_dct_matrix(self): """ Create the not-quite-DCT matrix as used by Sphinx, and store it in ```self.s2dct```. """ self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size)) for i in range(0, self.mfcc_size): freq = numpy.pi * float(i) / self.filter_bank_size self.s2dct[i] = numpy.cos(freq * numpy.arange(0.5, 0.5 + self.filter_bank_size, 1.0, 'float64')) self.s2dct[:, 0] *= 0.5 self.s2dct = self.s2dct.transpose()
[ "def", "_create_dct_matrix", "(", "self", ")", ":", "self", ".", "s2dct", "=", "numpy", ".", "zeros", "(", "(", "self", ".", "mfcc_size", ",", "self", ".", "filter_bank_size", ")", ")", "for", "i", "in", "range", "(", "0", ",", "self", ".", "mfcc_size", ")", ":", "freq", "=", "numpy", ".", "pi", "*", "float", "(", "i", ")", "/", "self", ".", "filter_bank_size", "self", ".", "s2dct", "[", "i", "]", "=", "numpy", ".", "cos", "(", "freq", "*", "numpy", ".", "arange", "(", "0.5", ",", "0.5", "+", "self", ".", "filter_bank_size", ",", "1.0", ",", "'float64'", ")", ")", "self", ".", "s2dct", "[", ":", ",", "0", "]", "*=", "0.5", "self", ".", "s2dct", "=", "self", ".", "s2dct", ".", "transpose", "(", ")" ]
Create the not-quite-DCT matrix as used by Sphinx, and store it in ```self.s2dct```.
[ "Create", "the", "not", "-", "quite", "-", "DCT", "matrix", "as", "used", "by", "Sphinx", "and", "store", "it", "in", "self", ".", "s2dct", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L104-L114
232,259
readbeyond/aeneas
aeneas/mfcc.py
MFCC._create_mel_filter_bank
def _create_mel_filter_bank(self): """ Create the Mel filter bank, and store it in ``self.filters``. Note that it is a function of the audio sample rate, so it cannot be created in the class initializer, but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`. """ self.filters = numpy.zeros((1 + (self.fft_order // 2), self.filter_bank_size), 'd') dfreq = float(self.sample_rate) / self.fft_order nyquist_frequency = self.sample_rate / 2 if self.upper_frequency > nyquist_frequency: self.log_exc(u"Upper frequency %f exceeds Nyquist frequency %f" % (self.upper_frequency, nyquist_frequency), None, True, ValueError) melmax = MFCC._hz2mel(self.upper_frequency) melmin = MFCC._hz2mel(self.lower_frequency) dmelbw = (melmax - melmin) / (self.filter_bank_size + 1) filt_edge = MFCC._mel2hz(melmin + dmelbw * numpy.arange(self.filter_bank_size + 2, dtype='d')) # TODO can this code be written more numpy-style? # (the performance loss is negligible, it is just ugly to see) for whichfilt in range(0, self.filter_bank_size): # int() casts to native int instead of working with numpy.float64 leftfr = int(round(filt_edge[whichfilt] / dfreq)) centerfr = int(round(filt_edge[whichfilt + 1] / dfreq)) rightfr = int(round(filt_edge[whichfilt + 2] / dfreq)) fwidth = (rightfr - leftfr) * dfreq height = 2.0 / fwidth if centerfr != leftfr: leftslope = height / (centerfr - leftfr) else: leftslope = 0 freq = leftfr + 1 while freq < centerfr: self.filters[freq, whichfilt] = (freq - leftfr) * leftslope freq = freq + 1 # the next if should always be true! if freq == centerfr: self.filters[freq, whichfilt] = height freq = freq + 1 if centerfr != rightfr: rightslope = height / (centerfr - rightfr) while freq < rightfr: self.filters[freq, whichfilt] = (freq - rightfr) * rightslope freq = freq + 1
python
def _create_mel_filter_bank(self): """ Create the Mel filter bank, and store it in ``self.filters``. Note that it is a function of the audio sample rate, so it cannot be created in the class initializer, but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`. """ self.filters = numpy.zeros((1 + (self.fft_order // 2), self.filter_bank_size), 'd') dfreq = float(self.sample_rate) / self.fft_order nyquist_frequency = self.sample_rate / 2 if self.upper_frequency > nyquist_frequency: self.log_exc(u"Upper frequency %f exceeds Nyquist frequency %f" % (self.upper_frequency, nyquist_frequency), None, True, ValueError) melmax = MFCC._hz2mel(self.upper_frequency) melmin = MFCC._hz2mel(self.lower_frequency) dmelbw = (melmax - melmin) / (self.filter_bank_size + 1) filt_edge = MFCC._mel2hz(melmin + dmelbw * numpy.arange(self.filter_bank_size + 2, dtype='d')) # TODO can this code be written more numpy-style? # (the performance loss is negligible, it is just ugly to see) for whichfilt in range(0, self.filter_bank_size): # int() casts to native int instead of working with numpy.float64 leftfr = int(round(filt_edge[whichfilt] / dfreq)) centerfr = int(round(filt_edge[whichfilt + 1] / dfreq)) rightfr = int(round(filt_edge[whichfilt + 2] / dfreq)) fwidth = (rightfr - leftfr) * dfreq height = 2.0 / fwidth if centerfr != leftfr: leftslope = height / (centerfr - leftfr) else: leftslope = 0 freq = leftfr + 1 while freq < centerfr: self.filters[freq, whichfilt] = (freq - leftfr) * leftslope freq = freq + 1 # the next if should always be true! if freq == centerfr: self.filters[freq, whichfilt] = height freq = freq + 1 if centerfr != rightfr: rightslope = height / (centerfr - rightfr) while freq < rightfr: self.filters[freq, whichfilt] = (freq - rightfr) * rightslope freq = freq + 1
[ "def", "_create_mel_filter_bank", "(", "self", ")", ":", "self", ".", "filters", "=", "numpy", ".", "zeros", "(", "(", "1", "+", "(", "self", ".", "fft_order", "//", "2", ")", ",", "self", ".", "filter_bank_size", ")", ",", "'d'", ")", "dfreq", "=", "float", "(", "self", ".", "sample_rate", ")", "/", "self", ".", "fft_order", "nyquist_frequency", "=", "self", ".", "sample_rate", "/", "2", "if", "self", ".", "upper_frequency", ">", "nyquist_frequency", ":", "self", ".", "log_exc", "(", "u\"Upper frequency %f exceeds Nyquist frequency %f\"", "%", "(", "self", ".", "upper_frequency", ",", "nyquist_frequency", ")", ",", "None", ",", "True", ",", "ValueError", ")", "melmax", "=", "MFCC", ".", "_hz2mel", "(", "self", ".", "upper_frequency", ")", "melmin", "=", "MFCC", ".", "_hz2mel", "(", "self", ".", "lower_frequency", ")", "dmelbw", "=", "(", "melmax", "-", "melmin", ")", "/", "(", "self", ".", "filter_bank_size", "+", "1", ")", "filt_edge", "=", "MFCC", ".", "_mel2hz", "(", "melmin", "+", "dmelbw", "*", "numpy", ".", "arange", "(", "self", ".", "filter_bank_size", "+", "2", ",", "dtype", "=", "'d'", ")", ")", "# TODO can this code be written more numpy-style?", "# (the performance loss is negligible, it is just ugly to see)", "for", "whichfilt", "in", "range", "(", "0", ",", "self", ".", "filter_bank_size", ")", ":", "# int() casts to native int instead of working with numpy.float64", "leftfr", "=", "int", "(", "round", "(", "filt_edge", "[", "whichfilt", "]", "/", "dfreq", ")", ")", "centerfr", "=", "int", "(", "round", "(", "filt_edge", "[", "whichfilt", "+", "1", "]", "/", "dfreq", ")", ")", "rightfr", "=", "int", "(", "round", "(", "filt_edge", "[", "whichfilt", "+", "2", "]", "/", "dfreq", ")", ")", "fwidth", "=", "(", "rightfr", "-", "leftfr", ")", "*", "dfreq", "height", "=", "2.0", "/", "fwidth", "if", "centerfr", "!=", "leftfr", ":", "leftslope", "=", "height", "/", "(", "centerfr", "-", "leftfr", ")", "else", ":", "leftslope", "=", "0", "freq", "=", "leftfr", "+", "1", "while", "freq", "<", "centerfr", ":", "self", ".", "filters", "[", "freq", ",", "whichfilt", "]", "=", "(", "freq", "-", "leftfr", ")", "*", "leftslope", "freq", "=", "freq", "+", "1", "# the next if should always be true!", "if", "freq", "==", "centerfr", ":", "self", ".", "filters", "[", "freq", ",", "whichfilt", "]", "=", "height", "freq", "=", "freq", "+", "1", "if", "centerfr", "!=", "rightfr", ":", "rightslope", "=", "height", "/", "(", "centerfr", "-", "rightfr", ")", "while", "freq", "<", "rightfr", ":", "self", ".", "filters", "[", "freq", ",", "whichfilt", "]", "=", "(", "freq", "-", "rightfr", ")", "*", "rightslope", "freq", "=", "freq", "+", "1" ]
Create the Mel filter bank, and store it in ``self.filters``. Note that it is a function of the audio sample rate, so it cannot be created in the class initializer, but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`.
[ "Create", "the", "Mel", "filter", "bank", "and", "store", "it", "in", "self", ".", "filters", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L116-L160
232,260
readbeyond/aeneas
aeneas/mfcc.py
MFCC._pre_emphasis
def _pre_emphasis(self): """ Pre-emphasize the entire signal at once by self.emphasis_factor, overwriting ``self.data``. """ self.data = numpy.append(self.data[0], self.data[1:] - self.emphasis_factor * self.data[:-1])
python
def _pre_emphasis(self): """ Pre-emphasize the entire signal at once by self.emphasis_factor, overwriting ``self.data``. """ self.data = numpy.append(self.data[0], self.data[1:] - self.emphasis_factor * self.data[:-1])
[ "def", "_pre_emphasis", "(", "self", ")", ":", "self", ".", "data", "=", "numpy", ".", "append", "(", "self", ".", "data", "[", "0", "]", ",", "self", ".", "data", "[", "1", ":", "]", "-", "self", ".", "emphasis_factor", "*", "self", ".", "data", "[", ":", "-", "1", "]", ")" ]
Pre-emphasize the entire signal at once by self.emphasis_factor, overwriting ``self.data``.
[ "Pre", "-", "emphasize", "the", "entire", "signal", "at", "once", "by", "self", ".", "emphasis_factor", "overwriting", "self", ".", "data", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L162-L167
232,261
readbeyond/aeneas
aeneas/mfcc.py
MFCC.compute_from_data
def compute_from_data(self, data, sample_rate): """ Compute MFCCs for the given audio data. The audio data must be a 1D :class:`numpy.ndarray`, that is, it must represent a monoaural (single channel) array of ``float64`` values in ``[-1.0, 1.0]``. :param data: the audio data :type data: :class:`numpy.ndarray` (1D) :param int sample_rate: the sample rate of the audio data, in samples/s (Hz) :raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono), or if the data is empty :raises: ValueError: if the upper frequency defined in the ``rconf`` is larger than the Nyquist frequenct (i.e., half of ``sample_rate``) """ def _process_frame(self, frame): """ Process each frame, returning the log(power()) of it. """ # apply Hamming window frame *= self.hamming_window # compute RFFT fft = numpy.fft.rfft(frame, self.fft_order) # equivalent to power = fft.real * fft.real + fft.imag * fft.imag power = numpy.square(numpy.absolute(fft)) # # return the log(power()) of the transformed vector # v1 # COMMENTED logspec = numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf)) # COMMENTED return numpy.dot(logspec, self.s2dct) / self.filter_bank_size # v2 return numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf)) if len(data.shape) != 1: self.log_exc(u"The audio data must be a 1D numpy array (mono).", None, True, ValueError) if len(data) < 1: self.log_exc(u"The audio data must not be empty.", None, True, ValueError) self.data = data self.sample_rate = sample_rate # number of samples in the audio data_length = len(self.data) # frame length in number of samples frame_length = int(self.window_length * self.sample_rate) # frame length must be at least equal to the FFT order frame_length_padded = max(frame_length, self.fft_order) # frame shift in number of samples frame_shift = int(self.window_shift * self.sample_rate) # number of MFCC vectors (one for each frame) # this number includes the last shift, # where the data will be padded with zeros # if the remaining samples are less than frame_length_padded number_of_frames = int((1.0 * data_length) / frame_shift) # create Hamming window self.hamming_window = numpy.hamming(frame_length_padded) # build Mel filter bank self._create_mel_filter_bank() # pre-emphasize the entire audio data self._pre_emphasis() # allocate the MFCCs matrix # v1 # COMMENTED mfcc = numpy.zeros((number_of_frames, self.mfcc_size), 'float64') # v2 mfcc = numpy.zeros((number_of_frames, self.filter_bank_size), 'float64') # compute MFCCs one frame at a time for frame_index in range(number_of_frames): # COMMENTED print("Computing frame %d / %d" % (frame_index, number_of_frames)) # get the start and end indices for this frame, # do not overrun the data length frame_start = frame_index * frame_shift frame_end = min(frame_start + frame_length_padded, data_length) # frame is zero-padded if the remaining samples # are less than its length frame = numpy.zeros(frame_length_padded) frame[0:(frame_end - frame_start)] = self.data[frame_start:frame_end] # process the frame mfcc[frame_index] = _process_frame(self, frame) # v1 # COMMENTED return mfcc # v2 # return the dot product with the DCT matrix return numpy.dot(mfcc, self.s2dct) / self.filter_bank_size
python
def compute_from_data(self, data, sample_rate): """ Compute MFCCs for the given audio data. The audio data must be a 1D :class:`numpy.ndarray`, that is, it must represent a monoaural (single channel) array of ``float64`` values in ``[-1.0, 1.0]``. :param data: the audio data :type data: :class:`numpy.ndarray` (1D) :param int sample_rate: the sample rate of the audio data, in samples/s (Hz) :raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono), or if the data is empty :raises: ValueError: if the upper frequency defined in the ``rconf`` is larger than the Nyquist frequenct (i.e., half of ``sample_rate``) """ def _process_frame(self, frame): """ Process each frame, returning the log(power()) of it. """ # apply Hamming window frame *= self.hamming_window # compute RFFT fft = numpy.fft.rfft(frame, self.fft_order) # equivalent to power = fft.real * fft.real + fft.imag * fft.imag power = numpy.square(numpy.absolute(fft)) # # return the log(power()) of the transformed vector # v1 # COMMENTED logspec = numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf)) # COMMENTED return numpy.dot(logspec, self.s2dct) / self.filter_bank_size # v2 return numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf)) if len(data.shape) != 1: self.log_exc(u"The audio data must be a 1D numpy array (mono).", None, True, ValueError) if len(data) < 1: self.log_exc(u"The audio data must not be empty.", None, True, ValueError) self.data = data self.sample_rate = sample_rate # number of samples in the audio data_length = len(self.data) # frame length in number of samples frame_length = int(self.window_length * self.sample_rate) # frame length must be at least equal to the FFT order frame_length_padded = max(frame_length, self.fft_order) # frame shift in number of samples frame_shift = int(self.window_shift * self.sample_rate) # number of MFCC vectors (one for each frame) # this number includes the last shift, # where the data will be padded with zeros # if the remaining samples are less than frame_length_padded number_of_frames = int((1.0 * data_length) / frame_shift) # create Hamming window self.hamming_window = numpy.hamming(frame_length_padded) # build Mel filter bank self._create_mel_filter_bank() # pre-emphasize the entire audio data self._pre_emphasis() # allocate the MFCCs matrix # v1 # COMMENTED mfcc = numpy.zeros((number_of_frames, self.mfcc_size), 'float64') # v2 mfcc = numpy.zeros((number_of_frames, self.filter_bank_size), 'float64') # compute MFCCs one frame at a time for frame_index in range(number_of_frames): # COMMENTED print("Computing frame %d / %d" % (frame_index, number_of_frames)) # get the start and end indices for this frame, # do not overrun the data length frame_start = frame_index * frame_shift frame_end = min(frame_start + frame_length_padded, data_length) # frame is zero-padded if the remaining samples # are less than its length frame = numpy.zeros(frame_length_padded) frame[0:(frame_end - frame_start)] = self.data[frame_start:frame_end] # process the frame mfcc[frame_index] = _process_frame(self, frame) # v1 # COMMENTED return mfcc # v2 # return the dot product with the DCT matrix return numpy.dot(mfcc, self.s2dct) / self.filter_bank_size
[ "def", "compute_from_data", "(", "self", ",", "data", ",", "sample_rate", ")", ":", "def", "_process_frame", "(", "self", ",", "frame", ")", ":", "\"\"\"\n Process each frame, returning the log(power()) of it.\n \"\"\"", "# apply Hamming window", "frame", "*=", "self", ".", "hamming_window", "# compute RFFT", "fft", "=", "numpy", ".", "fft", ".", "rfft", "(", "frame", ",", "self", ".", "fft_order", ")", "# equivalent to power = fft.real * fft.real + fft.imag * fft.imag", "power", "=", "numpy", ".", "square", "(", "numpy", ".", "absolute", "(", "fft", ")", ")", "#", "# return the log(power()) of the transformed vector", "# v1", "# COMMENTED logspec = numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf))", "# COMMENTED return numpy.dot(logspec, self.s2dct) / self.filter_bank_size", "# v2", "return", "numpy", ".", "log", "(", "numpy", ".", "dot", "(", "power", ",", "self", ".", "filters", ")", ".", "clip", "(", "self", ".", "CUTOFF", ",", "numpy", ".", "inf", ")", ")", "if", "len", "(", "data", ".", "shape", ")", "!=", "1", ":", "self", ".", "log_exc", "(", "u\"The audio data must be a 1D numpy array (mono).\"", ",", "None", ",", "True", ",", "ValueError", ")", "if", "len", "(", "data", ")", "<", "1", ":", "self", ".", "log_exc", "(", "u\"The audio data must not be empty.\"", ",", "None", ",", "True", ",", "ValueError", ")", "self", ".", "data", "=", "data", "self", ".", "sample_rate", "=", "sample_rate", "# number of samples in the audio", "data_length", "=", "len", "(", "self", ".", "data", ")", "# frame length in number of samples", "frame_length", "=", "int", "(", "self", ".", "window_length", "*", "self", ".", "sample_rate", ")", "# frame length must be at least equal to the FFT order", "frame_length_padded", "=", "max", "(", "frame_length", ",", "self", ".", "fft_order", ")", "# frame shift in number of samples", "frame_shift", "=", "int", "(", "self", ".", "window_shift", "*", "self", ".", "sample_rate", ")", "# number of MFCC vectors (one for each frame)", "# this number includes the last shift,", "# where the data will be padded with zeros", "# if the remaining samples are less than frame_length_padded", "number_of_frames", "=", "int", "(", "(", "1.0", "*", "data_length", ")", "/", "frame_shift", ")", "# create Hamming window", "self", ".", "hamming_window", "=", "numpy", ".", "hamming", "(", "frame_length_padded", ")", "# build Mel filter bank", "self", ".", "_create_mel_filter_bank", "(", ")", "# pre-emphasize the entire audio data", "self", ".", "_pre_emphasis", "(", ")", "# allocate the MFCCs matrix", "# v1", "# COMMENTED mfcc = numpy.zeros((number_of_frames, self.mfcc_size), 'float64')", "# v2", "mfcc", "=", "numpy", ".", "zeros", "(", "(", "number_of_frames", ",", "self", ".", "filter_bank_size", ")", ",", "'float64'", ")", "# compute MFCCs one frame at a time", "for", "frame_index", "in", "range", "(", "number_of_frames", ")", ":", "# COMMENTED print(\"Computing frame %d / %d\" % (frame_index, number_of_frames))", "# get the start and end indices for this frame,", "# do not overrun the data length", "frame_start", "=", "frame_index", "*", "frame_shift", "frame_end", "=", "min", "(", "frame_start", "+", "frame_length_padded", ",", "data_length", ")", "# frame is zero-padded if the remaining samples", "# are less than its length", "frame", "=", "numpy", ".", "zeros", "(", "frame_length_padded", ")", "frame", "[", "0", ":", "(", "frame_end", "-", "frame_start", ")", "]", "=", "self", ".", "data", "[", "frame_start", ":", "frame_end", "]", "# process the frame", "mfcc", "[", "frame_index", "]", "=", "_process_frame", "(", "self", ",", "frame", ")", "# v1", "# COMMENTED return mfcc", "# v2", "# return the dot product with the DCT matrix", "return", "numpy", ".", "dot", "(", "mfcc", ",", "self", ".", "s2dct", ")", "/", "self", ".", "filter_bank_size" ]
Compute MFCCs for the given audio data. The audio data must be a 1D :class:`numpy.ndarray`, that is, it must represent a monoaural (single channel) array of ``float64`` values in ``[-1.0, 1.0]``. :param data: the audio data :type data: :class:`numpy.ndarray` (1D) :param int sample_rate: the sample rate of the audio data, in samples/s (Hz) :raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono), or if the data is empty :raises: ValueError: if the upper frequency defined in the ``rconf`` is larger than the Nyquist frequenct (i.e., half of ``sample_rate``)
[ "Compute", "MFCCs", "for", "the", "given", "audio", "data", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L169-L265
232,262
readbeyond/aeneas
aeneas/wavfile.py
write
def write(filename, rate, data): """ Write a numpy array as a WAV file Parameters ---------- filename : string or open file handle Output wav file rate : int The sample rate (in samples/sec). data : ndarray A 1-D or 2-D numpy array of either integer or float data-type. Notes ----- * The file can be an open file or a filename. * Writes a simple uncompressed WAV file. * The bits-per-sample will be determined by the data-type. * To write multiple-channels, use a 2-D array of shape (Nsamples, Nchannels). """ if hasattr(filename, 'write'): fid = filename else: fid = open(filename, 'wb') try: dkind = data.dtype.kind if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and data.dtype.itemsize == 1)): raise ValueError("Unsupported data type '%s'" % data.dtype) fid.write(b'RIFF') fid.write(b'\x00\x00\x00\x00') fid.write(b'WAVE') # fmt chunk fid.write(b'fmt ') if dkind == 'f': comp = 3 else: comp = 1 if data.ndim == 1: noc = 1 else: noc = data.shape[1] bits = data.dtype.itemsize * 8 sbytes = rate * (bits // 8) * noc ba = noc * (bits // 8) fid.write(struct.pack('<ihHIIHH', 16, comp, noc, rate, sbytes, ba, bits)) # data chunk fid.write(b'data') fid.write(struct.pack('<i', data.nbytes)) if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and sys.byteorder == 'big'): data = data.byteswap() _array_tofile(fid, data) # Determine file size and place it in correct # position at start of the file. size = fid.tell() fid.seek(4) fid.write(struct.pack('<i', size - 8)) finally: if not hasattr(filename, 'write'): fid.close() else: fid.seek(0)
python
def write(filename, rate, data): """ Write a numpy array as a WAV file Parameters ---------- filename : string or open file handle Output wav file rate : int The sample rate (in samples/sec). data : ndarray A 1-D or 2-D numpy array of either integer or float data-type. Notes ----- * The file can be an open file or a filename. * Writes a simple uncompressed WAV file. * The bits-per-sample will be determined by the data-type. * To write multiple-channels, use a 2-D array of shape (Nsamples, Nchannels). """ if hasattr(filename, 'write'): fid = filename else: fid = open(filename, 'wb') try: dkind = data.dtype.kind if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and data.dtype.itemsize == 1)): raise ValueError("Unsupported data type '%s'" % data.dtype) fid.write(b'RIFF') fid.write(b'\x00\x00\x00\x00') fid.write(b'WAVE') # fmt chunk fid.write(b'fmt ') if dkind == 'f': comp = 3 else: comp = 1 if data.ndim == 1: noc = 1 else: noc = data.shape[1] bits = data.dtype.itemsize * 8 sbytes = rate * (bits // 8) * noc ba = noc * (bits // 8) fid.write(struct.pack('<ihHIIHH', 16, comp, noc, rate, sbytes, ba, bits)) # data chunk fid.write(b'data') fid.write(struct.pack('<i', data.nbytes)) if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and sys.byteorder == 'big'): data = data.byteswap() _array_tofile(fid, data) # Determine file size and place it in correct # position at start of the file. size = fid.tell() fid.seek(4) fid.write(struct.pack('<i', size - 8)) finally: if not hasattr(filename, 'write'): fid.close() else: fid.seek(0)
[ "def", "write", "(", "filename", ",", "rate", ",", "data", ")", ":", "if", "hasattr", "(", "filename", ",", "'write'", ")", ":", "fid", "=", "filename", "else", ":", "fid", "=", "open", "(", "filename", ",", "'wb'", ")", "try", ":", "dkind", "=", "data", ".", "dtype", ".", "kind", "if", "not", "(", "dkind", "==", "'i'", "or", "dkind", "==", "'f'", "or", "(", "dkind", "==", "'u'", "and", "data", ".", "dtype", ".", "itemsize", "==", "1", ")", ")", ":", "raise", "ValueError", "(", "\"Unsupported data type '%s'\"", "%", "data", ".", "dtype", ")", "fid", ".", "write", "(", "b'RIFF'", ")", "fid", ".", "write", "(", "b'\\x00\\x00\\x00\\x00'", ")", "fid", ".", "write", "(", "b'WAVE'", ")", "# fmt chunk", "fid", ".", "write", "(", "b'fmt '", ")", "if", "dkind", "==", "'f'", ":", "comp", "=", "3", "else", ":", "comp", "=", "1", "if", "data", ".", "ndim", "==", "1", ":", "noc", "=", "1", "else", ":", "noc", "=", "data", ".", "shape", "[", "1", "]", "bits", "=", "data", ".", "dtype", ".", "itemsize", "*", "8", "sbytes", "=", "rate", "*", "(", "bits", "//", "8", ")", "*", "noc", "ba", "=", "noc", "*", "(", "bits", "//", "8", ")", "fid", ".", "write", "(", "struct", ".", "pack", "(", "'<ihHIIHH'", ",", "16", ",", "comp", ",", "noc", ",", "rate", ",", "sbytes", ",", "ba", ",", "bits", ")", ")", "# data chunk", "fid", ".", "write", "(", "b'data'", ")", "fid", ".", "write", "(", "struct", ".", "pack", "(", "'<i'", ",", "data", ".", "nbytes", ")", ")", "if", "data", ".", "dtype", ".", "byteorder", "==", "'>'", "or", "(", "data", ".", "dtype", ".", "byteorder", "==", "'='", "and", "sys", ".", "byteorder", "==", "'big'", ")", ":", "data", "=", "data", ".", "byteswap", "(", ")", "_array_tofile", "(", "fid", ",", "data", ")", "# Determine file size and place it in correct", "# position at start of the file.", "size", "=", "fid", ".", "tell", "(", ")", "fid", ".", "seek", "(", "4", ")", "fid", ".", "write", "(", "struct", ".", "pack", "(", "'<i'", ",", "size", "-", "8", ")", ")", "finally", ":", "if", "not", "hasattr", "(", "filename", ",", "'write'", ")", ":", "fid", ".", "close", "(", ")", "else", ":", "fid", ".", "seek", "(", "0", ")" ]
Write a numpy array as a WAV file Parameters ---------- filename : string or open file handle Output wav file rate : int The sample rate (in samples/sec). data : ndarray A 1-D or 2-D numpy array of either integer or float data-type. Notes ----- * The file can be an open file or a filename. * Writes a simple uncompressed WAV file. * The bits-per-sample will be determined by the data-type. * To write multiple-channels, use a 2-D array of shape (Nsamples, Nchannels).
[ "Write", "a", "numpy", "array", "as", "a", "WAV", "file" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/wavfile.py#L200-L270
232,263
readbeyond/aeneas
aeneas/globalfunctions.py
safe_print
def safe_print(msg): """ Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message """ try: print(msg) except UnicodeEncodeError: try: # NOTE encoding and decoding so that in Python 3 no b"..." is printed encoded = msg.encode(sys.stdout.encoding, "replace") decoded = encoded.decode(sys.stdout.encoding, "replace") print(decoded) except (UnicodeDecodeError, UnicodeEncodeError): print(u"[ERRO] An unexpected error happened while printing to stdout.") print(u"[ERRO] Please check that your file/string encoding matches the shell encoding.") print(u"[ERRO] If possible, set your shell encoding to UTF-8 and convert any files with legacy encodings.")
python
def safe_print(msg): """ Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message """ try: print(msg) except UnicodeEncodeError: try: # NOTE encoding and decoding so that in Python 3 no b"..." is printed encoded = msg.encode(sys.stdout.encoding, "replace") decoded = encoded.decode(sys.stdout.encoding, "replace") print(decoded) except (UnicodeDecodeError, UnicodeEncodeError): print(u"[ERRO] An unexpected error happened while printing to stdout.") print(u"[ERRO] Please check that your file/string encoding matches the shell encoding.") print(u"[ERRO] If possible, set your shell encoding to UTF-8 and convert any files with legacy encodings.")
[ "def", "safe_print", "(", "msg", ")", ":", "try", ":", "print", "(", "msg", ")", "except", "UnicodeEncodeError", ":", "try", ":", "# NOTE encoding and decoding so that in Python 3 no b\"...\" is printed", "encoded", "=", "msg", ".", "encode", "(", "sys", ".", "stdout", ".", "encoding", ",", "\"replace\"", ")", "decoded", "=", "encoded", ".", "decode", "(", "sys", ".", "stdout", ".", "encoding", ",", "\"replace\"", ")", "print", "(", "decoded", ")", "except", "(", "UnicodeDecodeError", ",", "UnicodeEncodeError", ")", ":", "print", "(", "u\"[ERRO] An unexpected error happened while printing to stdout.\"", ")", "print", "(", "u\"[ERRO] Please check that your file/string encoding matches the shell encoding.\"", ")", "print", "(", "u\"[ERRO] If possible, set your shell encoding to UTF-8 and convert any files with legacy encodings.\"", ")" ]
Safely print a given Unicode string to stdout, possibly replacing characters non-printable in the current stdout encoding. :param string msg: the message
[ "Safely", "print", "a", "given", "Unicode", "string", "to", "stdout", "possibly", "replacing", "characters", "non", "-", "printable", "in", "the", "current", "stdout", "encoding", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L65-L84
232,264
readbeyond/aeneas
aeneas/globalfunctions.py
print_error
def print_error(msg, color=True): """ Print an error message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END)) else: safe_print(u"[ERRO] %s" % (msg))
python
def print_error(msg, color=True): """ Print an error message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END)) else: safe_print(u"[ERRO] %s" % (msg))
[ "def", "print_error", "(", "msg", ",", "color", "=", "True", ")", ":", "if", "color", "and", "is_posix", "(", ")", ":", "safe_print", "(", "u\"%s[ERRO] %s%s\"", "%", "(", "ANSI_ERROR", ",", "msg", ",", "ANSI_END", ")", ")", "else", ":", "safe_print", "(", "u\"[ERRO] %s\"", "%", "(", "msg", ")", ")" ]
Print an error message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
[ "Print", "an", "error", "message", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L87-L97
232,265
readbeyond/aeneas
aeneas/globalfunctions.py
print_success
def print_success(msg, color=True): """ Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END)) else: safe_print(u"[INFO] %s" % (msg))
python
def print_success(msg, color=True): """ Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END)) else: safe_print(u"[INFO] %s" % (msg))
[ "def", "print_success", "(", "msg", ",", "color", "=", "True", ")", ":", "if", "color", "and", "is_posix", "(", ")", ":", "safe_print", "(", "u\"%s[INFO] %s%s\"", "%", "(", "ANSI_OK", ",", "msg", ",", "ANSI_END", ")", ")", "else", ":", "safe_print", "(", "u\"[INFO] %s\"", "%", "(", "msg", ")", ")" ]
Print a success message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
[ "Print", "a", "success", "message", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L110-L120
232,266
readbeyond/aeneas
aeneas/globalfunctions.py
print_warning
def print_warning(msg, color=True): """ Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[WARN] %s%s" % (ANSI_WARNING, msg, ANSI_END)) else: safe_print(u"[WARN] %s" % (msg))
python
def print_warning(msg, color=True): """ Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color """ if color and is_posix(): safe_print(u"%s[WARN] %s%s" % (ANSI_WARNING, msg, ANSI_END)) else: safe_print(u"[WARN] %s" % (msg))
[ "def", "print_warning", "(", "msg", ",", "color", "=", "True", ")", ":", "if", "color", "and", "is_posix", "(", ")", ":", "safe_print", "(", "u\"%s[WARN] %s%s\"", "%", "(", "ANSI_WARNING", ",", "msg", ",", "ANSI_END", ")", ")", "else", ":", "safe_print", "(", "u\"[WARN] %s\"", "%", "(", "msg", ")", ")" ]
Print a warning message. :param string msg: the message :param bool color: if ``True``, print with POSIX color
[ "Print", "a", "warning", "message", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L123-L133
232,267
readbeyond/aeneas
aeneas/globalfunctions.py
file_extension
def file_extension(path): """ Return the file extension. Examples: :: /foo/bar.baz => baz None => None :param string path: the file path :rtype: string """ if path is None: return None ext = os.path.splitext(os.path.basename(path))[1] if ext.startswith("."): ext = ext[1:] return ext
python
def file_extension(path): """ Return the file extension. Examples: :: /foo/bar.baz => baz None => None :param string path: the file path :rtype: string """ if path is None: return None ext = os.path.splitext(os.path.basename(path))[1] if ext.startswith("."): ext = ext[1:] return ext
[ "def", "file_extension", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "None", "ext", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "[", "1", "]", "if", "ext", ".", "startswith", "(", "\".\"", ")", ":", "ext", "=", "ext", "[", "1", ":", "]", "return", "ext" ]
Return the file extension. Examples: :: /foo/bar.baz => baz None => None :param string path: the file path :rtype: string
[ "Return", "the", "file", "extension", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L196-L213
232,268
readbeyond/aeneas
aeneas/globalfunctions.py
mimetype_from_path
def mimetype_from_path(path): """ Return a mimetype from the file extension. :param string path: the file path :rtype: string """ extension = file_extension(path) if extension is not None: extension = extension.lower() if extension in gc.MIMETYPE_MAP: return gc.MIMETYPE_MAP[extension] return None
python
def mimetype_from_path(path): """ Return a mimetype from the file extension. :param string path: the file path :rtype: string """ extension = file_extension(path) if extension is not None: extension = extension.lower() if extension in gc.MIMETYPE_MAP: return gc.MIMETYPE_MAP[extension] return None
[ "def", "mimetype_from_path", "(", "path", ")", ":", "extension", "=", "file_extension", "(", "path", ")", "if", "extension", "is", "not", "None", ":", "extension", "=", "extension", ".", "lower", "(", ")", "if", "extension", "in", "gc", ".", "MIMETYPE_MAP", ":", "return", "gc", ".", "MIMETYPE_MAP", "[", "extension", "]", "return", "None" ]
Return a mimetype from the file extension. :param string path: the file path :rtype: string
[ "Return", "a", "mimetype", "from", "the", "file", "extension", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L216-L228
232,269
readbeyond/aeneas
aeneas/globalfunctions.py
file_name_without_extension
def file_name_without_extension(path): """ Return the file name without extension. Examples: :: /foo/bar.baz => bar /foo/bar => bar None => None :param string path: the file path :rtype: string """ if path is None: return None return os.path.splitext(os.path.basename(path))[0]
python
def file_name_without_extension(path): """ Return the file name without extension. Examples: :: /foo/bar.baz => bar /foo/bar => bar None => None :param string path: the file path :rtype: string """ if path is None: return None return os.path.splitext(os.path.basename(path))[0]
[ "def", "file_name_without_extension", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "None", "return", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", "[", "0", "]" ]
Return the file name without extension. Examples: :: /foo/bar.baz => bar /foo/bar => bar None => None :param string path: the file path :rtype: string
[ "Return", "the", "file", "name", "without", "extension", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L231-L246
232,270
readbeyond/aeneas
aeneas/globalfunctions.py
safe_float
def safe_float(string, default=None): """ Safely parse a string into a float. On error return the ``default`` value. :param string string: string value to be converted :param float default: default value to be used in case of failure :rtype: float """ value = default try: value = float(string) except TypeError: pass except ValueError: pass return value
python
def safe_float(string, default=None): """ Safely parse a string into a float. On error return the ``default`` value. :param string string: string value to be converted :param float default: default value to be used in case of failure :rtype: float """ value = default try: value = float(string) except TypeError: pass except ValueError: pass return value
[ "def", "safe_float", "(", "string", ",", "default", "=", "None", ")", ":", "value", "=", "default", "try", ":", "value", "=", "float", "(", "string", ")", "except", "TypeError", ":", "pass", "except", "ValueError", ":", "pass", "return", "value" ]
Safely parse a string into a float. On error return the ``default`` value. :param string string: string value to be converted :param float default: default value to be used in case of failure :rtype: float
[ "Safely", "parse", "a", "string", "into", "a", "float", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L272-L289
232,271
readbeyond/aeneas
aeneas/globalfunctions.py
safe_int
def safe_int(string, default=None): """ Safely parse a string into an int. On error return the ``default`` value. :param string string: string value to be converted :param int default: default value to be used in case of failure :rtype: int """ value = safe_float(string, default) if value is not None: value = int(value) return value
python
def safe_int(string, default=None): """ Safely parse a string into an int. On error return the ``default`` value. :param string string: string value to be converted :param int default: default value to be used in case of failure :rtype: int """ value = safe_float(string, default) if value is not None: value = int(value) return value
[ "def", "safe_int", "(", "string", ",", "default", "=", "None", ")", ":", "value", "=", "safe_float", "(", "string", ",", "default", ")", "if", "value", "is", "not", "None", ":", "value", "=", "int", "(", "value", ")", "return", "value" ]
Safely parse a string into an int. On error return the ``default`` value. :param string string: string value to be converted :param int default: default value to be used in case of failure :rtype: int
[ "Safely", "parse", "a", "string", "into", "an", "int", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L292-L305
232,272
readbeyond/aeneas
aeneas/globalfunctions.py
safe_get
def safe_get(dictionary, key, default_value, can_return_none=True): """ Safely perform a dictionary get, returning the default value if the key is not found. :param dict dictionary: the dictionary :param string key: the key :param variant default_value: the default value to be returned :param bool can_return_none: if ``True``, the function can return ``None``; otherwise, return ``default_value`` even if the dictionary lookup succeeded :rtype: variant """ return_value = default_value try: return_value = dictionary[key] if (return_value is None) and (not can_return_none): return_value = default_value except (KeyError, TypeError): # KeyError if key is not present in dictionary # TypeError if dictionary is None pass return return_value
python
def safe_get(dictionary, key, default_value, can_return_none=True): """ Safely perform a dictionary get, returning the default value if the key is not found. :param dict dictionary: the dictionary :param string key: the key :param variant default_value: the default value to be returned :param bool can_return_none: if ``True``, the function can return ``None``; otherwise, return ``default_value`` even if the dictionary lookup succeeded :rtype: variant """ return_value = default_value try: return_value = dictionary[key] if (return_value is None) and (not can_return_none): return_value = default_value except (KeyError, TypeError): # KeyError if key is not present in dictionary # TypeError if dictionary is None pass return return_value
[ "def", "safe_get", "(", "dictionary", ",", "key", ",", "default_value", ",", "can_return_none", "=", "True", ")", ":", "return_value", "=", "default_value", "try", ":", "return_value", "=", "dictionary", "[", "key", "]", "if", "(", "return_value", "is", "None", ")", "and", "(", "not", "can_return_none", ")", ":", "return_value", "=", "default_value", "except", "(", "KeyError", ",", "TypeError", ")", ":", "# KeyError if key is not present in dictionary", "# TypeError if dictionary is None", "pass", "return", "return_value" ]
Safely perform a dictionary get, returning the default value if the key is not found. :param dict dictionary: the dictionary :param string key: the key :param variant default_value: the default value to be returned :param bool can_return_none: if ``True``, the function can return ``None``; otherwise, return ``default_value`` even if the dictionary lookup succeeded :rtype: variant
[ "Safely", "perform", "a", "dictionary", "get", "returning", "the", "default", "value", "if", "the", "key", "is", "not", "found", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L308-L330
232,273
readbeyond/aeneas
aeneas/globalfunctions.py
norm_join
def norm_join(prefix, suffix): """ Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string """ if (prefix is None) and (suffix is None): return "." if prefix is None: return os.path.normpath(suffix) if suffix is None: return os.path.normpath(prefix) return os.path.normpath(os.path.join(prefix, suffix))
python
def norm_join(prefix, suffix): """ Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string """ if (prefix is None) and (suffix is None): return "." if prefix is None: return os.path.normpath(suffix) if suffix is None: return os.path.normpath(prefix) return os.path.normpath(os.path.join(prefix, suffix))
[ "def", "norm_join", "(", "prefix", ",", "suffix", ")", ":", "if", "(", "prefix", "is", "None", ")", "and", "(", "suffix", "is", "None", ")", ":", "return", "\".\"", "if", "prefix", "is", "None", ":", "return", "os", ".", "path", ".", "normpath", "(", "suffix", ")", "if", "suffix", "is", "None", ":", "return", "os", ".", "path", ".", "normpath", "(", "prefix", ")", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "prefix", ",", "suffix", ")", ")" ]
Join ``prefix`` and ``suffix`` paths and return the resulting path, normalized. :param string prefix: the prefix path :param string suffix: the suffix path :rtype: string
[ "Join", "prefix", "and", "suffix", "paths", "and", "return", "the", "resulting", "path", "normalized", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L333-L348
232,274
readbeyond/aeneas
aeneas/globalfunctions.py
copytree
def copytree(source_directory, destination_directory, ignore=None): """ Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist, we cannot use for our purposes. Code adapted from http://stackoverflow.com/a/12686557 :param string source_directory: the source directory, already existing :param string destination_directory: the destination directory, already existing """ if os.path.isdir(source_directory): if not os.path.isdir(destination_directory): os.makedirs(destination_directory) files = os.listdir(source_directory) if ignore is not None: ignored = ignore(source_directory, files) else: ignored = set() for f in files: if f not in ignored: copytree( os.path.join(source_directory, f), os.path.join(destination_directory, f), ignore ) else: shutil.copyfile(source_directory, destination_directory)
python
def copytree(source_directory, destination_directory, ignore=None): """ Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist, we cannot use for our purposes. Code adapted from http://stackoverflow.com/a/12686557 :param string source_directory: the source directory, already existing :param string destination_directory: the destination directory, already existing """ if os.path.isdir(source_directory): if not os.path.isdir(destination_directory): os.makedirs(destination_directory) files = os.listdir(source_directory) if ignore is not None: ignored = ignore(source_directory, files) else: ignored = set() for f in files: if f not in ignored: copytree( os.path.join(source_directory, f), os.path.join(destination_directory, f), ignore ) else: shutil.copyfile(source_directory, destination_directory)
[ "def", "copytree", "(", "source_directory", ",", "destination_directory", ",", "ignore", "=", "None", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "source_directory", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "destination_directory", ")", ":", "os", ".", "makedirs", "(", "destination_directory", ")", "files", "=", "os", ".", "listdir", "(", "source_directory", ")", "if", "ignore", "is", "not", "None", ":", "ignored", "=", "ignore", "(", "source_directory", ",", "files", ")", "else", ":", "ignored", "=", "set", "(", ")", "for", "f", "in", "files", ":", "if", "f", "not", "in", "ignored", ":", "copytree", "(", "os", ".", "path", ".", "join", "(", "source_directory", ",", "f", ")", ",", "os", ".", "path", ".", "join", "(", "destination_directory", ",", "f", ")", ",", "ignore", ")", "else", ":", "shutil", ".", "copyfile", "(", "source_directory", ",", "destination_directory", ")" ]
Recursively copy the contents of a source directory into a destination directory. Both directories must exist. This function does not copy the root directory ``source_directory`` into ``destination_directory``. Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist, we cannot use for our purposes. Code adapted from http://stackoverflow.com/a/12686557 :param string source_directory: the source directory, already existing :param string destination_directory: the destination directory, already existing
[ "Recursively", "copy", "the", "contents", "of", "a", "source", "directory", "into", "a", "destination", "directory", ".", "Both", "directories", "must", "exist", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L501-L534
232,275
readbeyond/aeneas
aeneas/globalfunctions.py
ensure_parent_directory
def ensure_parent_directory(path, ensure_parent=True): """ Ensures the parent directory exists. :param string path: the path of the file :param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists; if ``False``, ensure ``path`` exists :raises: OSError: if the path cannot be created """ parent_directory = os.path.abspath(path) if ensure_parent: parent_directory = os.path.dirname(parent_directory) if not os.path.exists(parent_directory): try: os.makedirs(parent_directory) except (IOError, OSError): raise OSError(u"Directory '%s' cannot be created" % parent_directory)
python
def ensure_parent_directory(path, ensure_parent=True): """ Ensures the parent directory exists. :param string path: the path of the file :param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists; if ``False``, ensure ``path`` exists :raises: OSError: if the path cannot be created """ parent_directory = os.path.abspath(path) if ensure_parent: parent_directory = os.path.dirname(parent_directory) if not os.path.exists(parent_directory): try: os.makedirs(parent_directory) except (IOError, OSError): raise OSError(u"Directory '%s' cannot be created" % parent_directory)
[ "def", "ensure_parent_directory", "(", "path", ",", "ensure_parent", "=", "True", ")", ":", "parent_directory", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "ensure_parent", ":", "parent_directory", "=", "os", ".", "path", ".", "dirname", "(", "parent_directory", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "parent_directory", ")", ":", "try", ":", "os", ".", "makedirs", "(", "parent_directory", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "raise", "OSError", "(", "u\"Directory '%s' cannot be created\"", "%", "parent_directory", ")" ]
Ensures the parent directory exists. :param string path: the path of the file :param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists; if ``False``, ensure ``path`` exists :raises: OSError: if the path cannot be created
[ "Ensures", "the", "parent", "directory", "exists", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L537-L553
232,276
readbeyond/aeneas
aeneas/globalfunctions.py
can_run_c_extension
def can_run_c_extension(name=None): """ Determine whether the given Python C extension loads correctly. If ``name`` is ``None``, tests all Python C extensions, and return ``True`` if and only if all load correctly. :param string name: the name of the Python C extension to test :rtype: bool """ def can_run_cdtw(): """ Python C extension for computing DTW """ try: import aeneas.cdtw.cdtw return True except ImportError: return False def can_run_cmfcc(): """ Python C extension for computing MFCC """ try: import aeneas.cmfcc.cmfcc return True except ImportError: return False def can_run_cew(): """ Python C extension for synthesizing with eSpeak """ try: import aeneas.cew.cew return True except ImportError: return False def can_run_cfw(): """ Python C extension for synthesizing with Festival """ try: import aeneas.cfw.cfw return True except ImportError: return False if name == "cdtw": return can_run_cdtw() elif name == "cmfcc": return can_run_cmfcc() elif name == "cew": return can_run_cew() elif name == "cfw": return can_run_cfw() else: # NOTE cfw is still experimental! return can_run_cdtw() and can_run_cmfcc() and can_run_cew()
python
def can_run_c_extension(name=None): """ Determine whether the given Python C extension loads correctly. If ``name`` is ``None``, tests all Python C extensions, and return ``True`` if and only if all load correctly. :param string name: the name of the Python C extension to test :rtype: bool """ def can_run_cdtw(): """ Python C extension for computing DTW """ try: import aeneas.cdtw.cdtw return True except ImportError: return False def can_run_cmfcc(): """ Python C extension for computing MFCC """ try: import aeneas.cmfcc.cmfcc return True except ImportError: return False def can_run_cew(): """ Python C extension for synthesizing with eSpeak """ try: import aeneas.cew.cew return True except ImportError: return False def can_run_cfw(): """ Python C extension for synthesizing with Festival """ try: import aeneas.cfw.cfw return True except ImportError: return False if name == "cdtw": return can_run_cdtw() elif name == "cmfcc": return can_run_cmfcc() elif name == "cew": return can_run_cew() elif name == "cfw": return can_run_cfw() else: # NOTE cfw is still experimental! return can_run_cdtw() and can_run_cmfcc() and can_run_cew()
[ "def", "can_run_c_extension", "(", "name", "=", "None", ")", ":", "def", "can_run_cdtw", "(", ")", ":", "\"\"\" Python C extension for computing DTW \"\"\"", "try", ":", "import", "aeneas", ".", "cdtw", ".", "cdtw", "return", "True", "except", "ImportError", ":", "return", "False", "def", "can_run_cmfcc", "(", ")", ":", "\"\"\" Python C extension for computing MFCC \"\"\"", "try", ":", "import", "aeneas", ".", "cmfcc", ".", "cmfcc", "return", "True", "except", "ImportError", ":", "return", "False", "def", "can_run_cew", "(", ")", ":", "\"\"\" Python C extension for synthesizing with eSpeak \"\"\"", "try", ":", "import", "aeneas", ".", "cew", ".", "cew", "return", "True", "except", "ImportError", ":", "return", "False", "def", "can_run_cfw", "(", ")", ":", "\"\"\" Python C extension for synthesizing with Festival \"\"\"", "try", ":", "import", "aeneas", ".", "cfw", ".", "cfw", "return", "True", "except", "ImportError", ":", "return", "False", "if", "name", "==", "\"cdtw\"", ":", "return", "can_run_cdtw", "(", ")", "elif", "name", "==", "\"cmfcc\"", ":", "return", "can_run_cmfcc", "(", ")", "elif", "name", "==", "\"cew\"", ":", "return", "can_run_cew", "(", ")", "elif", "name", "==", "\"cfw\"", ":", "return", "can_run_cfw", "(", ")", "else", ":", "# NOTE cfw is still experimental!", "return", "can_run_cdtw", "(", ")", "and", "can_run_cmfcc", "(", ")", "and", "can_run_cew", "(", ")" ]
Determine whether the given Python C extension loads correctly. If ``name`` is ``None``, tests all Python C extensions, and return ``True`` if and only if all load correctly. :param string name: the name of the Python C extension to test :rtype: bool
[ "Determine", "whether", "the", "given", "Python", "C", "extension", "loads", "correctly", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L805-L857
232,277
readbeyond/aeneas
aeneas/globalfunctions.py
run_c_extension_with_fallback
def run_c_extension_with_fallback( log_function, extension, c_function, py_function, args, rconf ): """ Run a function calling a C extension, falling back to a pure Python function if the former does not succeed. :param function log_function: a logger function :param string extension: the name of the extension :param function c_function: the (Python) function calling the C extension :param function py_function: the (Python) function providing the fallback :param rconf: the runtime configuration :type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration` :rtype: depends on the extension being called :raises: RuntimeError: if both the C extension and the pure Python code did not succeed. .. versionadded:: 1.4.0 """ computed = False if not rconf[u"c_extensions"]: log_function(u"C extensions disabled") elif extension not in rconf: log_function([u"C extension '%s' not recognized", extension]) elif not rconf[extension]: log_function([u"C extension '%s' disabled", extension]) else: log_function([u"C extension '%s' enabled", extension]) if c_function is None: log_function(u"C function is None") elif can_run_c_extension(extension): log_function([u"C extension '%s' enabled and it can be loaded", extension]) computed, result = c_function(*args) else: log_function([u"C extension '%s' enabled but it cannot be loaded", extension]) if not computed: if py_function is None: log_function(u"Python function is None") else: log_function(u"Running the pure Python code") computed, result = py_function(*args) if not computed: raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)") return result
python
def run_c_extension_with_fallback( log_function, extension, c_function, py_function, args, rconf ): """ Run a function calling a C extension, falling back to a pure Python function if the former does not succeed. :param function log_function: a logger function :param string extension: the name of the extension :param function c_function: the (Python) function calling the C extension :param function py_function: the (Python) function providing the fallback :param rconf: the runtime configuration :type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration` :rtype: depends on the extension being called :raises: RuntimeError: if both the C extension and the pure Python code did not succeed. .. versionadded:: 1.4.0 """ computed = False if not rconf[u"c_extensions"]: log_function(u"C extensions disabled") elif extension not in rconf: log_function([u"C extension '%s' not recognized", extension]) elif not rconf[extension]: log_function([u"C extension '%s' disabled", extension]) else: log_function([u"C extension '%s' enabled", extension]) if c_function is None: log_function(u"C function is None") elif can_run_c_extension(extension): log_function([u"C extension '%s' enabled and it can be loaded", extension]) computed, result = c_function(*args) else: log_function([u"C extension '%s' enabled but it cannot be loaded", extension]) if not computed: if py_function is None: log_function(u"Python function is None") else: log_function(u"Running the pure Python code") computed, result = py_function(*args) if not computed: raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)") return result
[ "def", "run_c_extension_with_fallback", "(", "log_function", ",", "extension", ",", "c_function", ",", "py_function", ",", "args", ",", "rconf", ")", ":", "computed", "=", "False", "if", "not", "rconf", "[", "u\"c_extensions\"", "]", ":", "log_function", "(", "u\"C extensions disabled\"", ")", "elif", "extension", "not", "in", "rconf", ":", "log_function", "(", "[", "u\"C extension '%s' not recognized\"", ",", "extension", "]", ")", "elif", "not", "rconf", "[", "extension", "]", ":", "log_function", "(", "[", "u\"C extension '%s' disabled\"", ",", "extension", "]", ")", "else", ":", "log_function", "(", "[", "u\"C extension '%s' enabled\"", ",", "extension", "]", ")", "if", "c_function", "is", "None", ":", "log_function", "(", "u\"C function is None\"", ")", "elif", "can_run_c_extension", "(", "extension", ")", ":", "log_function", "(", "[", "u\"C extension '%s' enabled and it can be loaded\"", ",", "extension", "]", ")", "computed", ",", "result", "=", "c_function", "(", "*", "args", ")", "else", ":", "log_function", "(", "[", "u\"C extension '%s' enabled but it cannot be loaded\"", ",", "extension", "]", ")", "if", "not", "computed", ":", "if", "py_function", "is", "None", ":", "log_function", "(", "u\"Python function is None\"", ")", "else", ":", "log_function", "(", "u\"Running the pure Python code\"", ")", "computed", ",", "result", "=", "py_function", "(", "*", "args", ")", "if", "not", "computed", ":", "raise", "RuntimeError", "(", "u\"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)\"", ")", "return", "result" ]
Run a function calling a C extension, falling back to a pure Python function if the former does not succeed. :param function log_function: a logger function :param string extension: the name of the extension :param function c_function: the (Python) function calling the C extension :param function py_function: the (Python) function providing the fallback :param rconf: the runtime configuration :type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration` :rtype: depends on the extension being called :raises: RuntimeError: if both the C extension and the pure Python code did not succeed. .. versionadded:: 1.4.0
[ "Run", "a", "function", "calling", "a", "C", "extension", "falling", "back", "to", "a", "pure", "Python", "function", "if", "the", "former", "does", "not", "succeed", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L860-L908
232,278
readbeyond/aeneas
aeneas/globalfunctions.py
file_can_be_read
def file_can_be_read(path): """ Return ``True`` if the file at the given ``path`` can be read. :param string path: the file path :rtype: bool .. versionadded:: 1.4.0 """ if path is None: return False try: with io.open(path, "rb") as test_file: pass return True except (IOError, OSError): pass return False
python
def file_can_be_read(path): """ Return ``True`` if the file at the given ``path`` can be read. :param string path: the file path :rtype: bool .. versionadded:: 1.4.0 """ if path is None: return False try: with io.open(path, "rb") as test_file: pass return True except (IOError, OSError): pass return False
[ "def", "file_can_be_read", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "False", "try", ":", "with", "io", ".", "open", "(", "path", ",", "\"rb\"", ")", "as", "test_file", ":", "pass", "return", "True", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "return", "False" ]
Return ``True`` if the file at the given ``path`` can be read. :param string path: the file path :rtype: bool .. versionadded:: 1.4.0
[ "Return", "True", "if", "the", "file", "at", "the", "given", "path", "can", "be", "read", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L911-L928
232,279
readbeyond/aeneas
aeneas/globalfunctions.py
file_can_be_written
def file_can_be_written(path): """ Return ``True`` if a file can be written at the given ``path``. :param string path: the file path :rtype: bool .. warning:: This function will attempt to open the given ``path`` in write mode, possibly destroying the file previously existing there. .. versionadded:: 1.4.0 """ if path is None: return False try: with io.open(path, "wb") as test_file: pass delete_file(None, path) return True except (IOError, OSError): pass return False
python
def file_can_be_written(path): """ Return ``True`` if a file can be written at the given ``path``. :param string path: the file path :rtype: bool .. warning:: This function will attempt to open the given ``path`` in write mode, possibly destroying the file previously existing there. .. versionadded:: 1.4.0 """ if path is None: return False try: with io.open(path, "wb") as test_file: pass delete_file(None, path) return True except (IOError, OSError): pass return False
[ "def", "file_can_be_written", "(", "path", ")", ":", "if", "path", "is", "None", ":", "return", "False", "try", ":", "with", "io", ".", "open", "(", "path", ",", "\"wb\"", ")", "as", "test_file", ":", "pass", "delete_file", "(", "None", ",", "path", ")", "return", "True", "except", "(", "IOError", ",", "OSError", ")", ":", "pass", "return", "False" ]
Return ``True`` if a file can be written at the given ``path``. :param string path: the file path :rtype: bool .. warning:: This function will attempt to open the given ``path`` in write mode, possibly destroying the file previously existing there. .. versionadded:: 1.4.0
[ "Return", "True", "if", "a", "file", "can", "be", "written", "at", "the", "given", "path", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L931-L952
232,280
readbeyond/aeneas
aeneas/globalfunctions.py
read_file_bytes
def read_file_bytes(input_file_path): """ Read the file at the given file path and return its contents as a byte string, or ``None`` if an error occurred. :param string input_file_path: the file path :rtype: bytes """ contents = None try: with io.open(input_file_path, "rb") as input_file: contents = input_file.read() except: pass return contents
python
def read_file_bytes(input_file_path): """ Read the file at the given file path and return its contents as a byte string, or ``None`` if an error occurred. :param string input_file_path: the file path :rtype: bytes """ contents = None try: with io.open(input_file_path, "rb") as input_file: contents = input_file.read() except: pass return contents
[ "def", "read_file_bytes", "(", "input_file_path", ")", ":", "contents", "=", "None", "try", ":", "with", "io", ".", "open", "(", "input_file_path", ",", "\"rb\"", ")", "as", "input_file", ":", "contents", "=", "input_file", ".", "read", "(", ")", "except", ":", "pass", "return", "contents" ]
Read the file at the given file path and return its contents as a byte string, or ``None`` if an error occurred. :param string input_file_path: the file path :rtype: bytes
[ "Read", "the", "file", "at", "the", "given", "file", "path", "and", "return", "its", "contents", "as", "a", "byte", "string", "or", "None", "if", "an", "error", "occurred", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1101-L1116
232,281
readbeyond/aeneas
aeneas/globalfunctions.py
human_readable_number
def human_readable_number(number, suffix=""): """ Format the given number into a human-readable string. Code adapted from http://stackoverflow.com/a/1094933 :param variant number: the number (int or float) :param string suffix: the unit of the number :rtype: string """ for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: if abs(number) < 1024.0: return "%3.1f%s%s" % (number, unit, suffix) number /= 1024.0 return "%.1f%s%s" % (number, "Y", suffix)
python
def human_readable_number(number, suffix=""): """ Format the given number into a human-readable string. Code adapted from http://stackoverflow.com/a/1094933 :param variant number: the number (int or float) :param string suffix: the unit of the number :rtype: string """ for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]: if abs(number) < 1024.0: return "%3.1f%s%s" % (number, unit, suffix) number /= 1024.0 return "%.1f%s%s" % (number, "Y", suffix)
[ "def", "human_readable_number", "(", "number", ",", "suffix", "=", "\"\"", ")", ":", "for", "unit", "in", "[", "\"\"", ",", "\"K\"", ",", "\"M\"", ",", "\"G\"", ",", "\"T\"", ",", "\"P\"", ",", "\"E\"", ",", "\"Z\"", "]", ":", "if", "abs", "(", "number", ")", "<", "1024.0", ":", "return", "\"%3.1f%s%s\"", "%", "(", "number", ",", "unit", ",", "suffix", ")", "number", "/=", "1024.0", "return", "\"%.1f%s%s\"", "%", "(", "number", ",", "\"Y\"", ",", "suffix", ")" ]
Format the given number into a human-readable string. Code adapted from http://stackoverflow.com/a/1094933 :param variant number: the number (int or float) :param string suffix: the unit of the number :rtype: string
[ "Format", "the", "given", "number", "into", "a", "human", "-", "readable", "string", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1119-L1133
232,282
readbeyond/aeneas
aeneas/globalfunctions.py
safe_unichr
def safe_unichr(codepoint): """ Safely return a Unicode string of length one, containing the Unicode character with given codepoint. :param int codepoint: the codepoint :rtype: string """ if is_py2_narrow_build(): return ("\\U%08x" % codepoint).decode("unicode-escape") elif PY2: return unichr(codepoint) return chr(codepoint)
python
def safe_unichr(codepoint): """ Safely return a Unicode string of length one, containing the Unicode character with given codepoint. :param int codepoint: the codepoint :rtype: string """ if is_py2_narrow_build(): return ("\\U%08x" % codepoint).decode("unicode-escape") elif PY2: return unichr(codepoint) return chr(codepoint)
[ "def", "safe_unichr", "(", "codepoint", ")", ":", "if", "is_py2_narrow_build", "(", ")", ":", "return", "(", "\"\\\\U%08x\"", "%", "codepoint", ")", ".", "decode", "(", "\"unicode-escape\"", ")", "elif", "PY2", ":", "return", "unichr", "(", "codepoint", ")", "return", "chr", "(", "codepoint", ")" ]
Safely return a Unicode string of length one, containing the Unicode character with given codepoint. :param int codepoint: the codepoint :rtype: string
[ "Safely", "return", "a", "Unicode", "string", "of", "length", "one", "containing", "the", "Unicode", "character", "with", "given", "codepoint", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1192-L1204
232,283
readbeyond/aeneas
aeneas/globalfunctions.py
safe_unicode_stdin
def safe_unicode_stdin(string): """ Safely convert the given string to a Unicode string, decoding using ``sys.stdin.encoding`` if needed. If running from a frozen binary, ``utf-8`` encoding is assumed. :param variant string: the byte string or Unicode string to convert :rtype: string """ if string is None: return None if is_bytes(string): if FROZEN: return string.decode("utf-8") try: return string.decode(sys.stdin.encoding) except UnicodeDecodeError: return string.decode(sys.stdin.encoding, "replace") except: return string.decode("utf-8") return string
python
def safe_unicode_stdin(string): """ Safely convert the given string to a Unicode string, decoding using ``sys.stdin.encoding`` if needed. If running from a frozen binary, ``utf-8`` encoding is assumed. :param variant string: the byte string or Unicode string to convert :rtype: string """ if string is None: return None if is_bytes(string): if FROZEN: return string.decode("utf-8") try: return string.decode(sys.stdin.encoding) except UnicodeDecodeError: return string.decode(sys.stdin.encoding, "replace") except: return string.decode("utf-8") return string
[ "def", "safe_unicode_stdin", "(", "string", ")", ":", "if", "string", "is", "None", ":", "return", "None", "if", "is_bytes", "(", "string", ")", ":", "if", "FROZEN", ":", "return", "string", ".", "decode", "(", "\"utf-8\"", ")", "try", ":", "return", "string", ".", "decode", "(", "sys", ".", "stdin", ".", "encoding", ")", "except", "UnicodeDecodeError", ":", "return", "string", ".", "decode", "(", "sys", ".", "stdin", ".", "encoding", ",", "\"replace\"", ")", "except", ":", "return", "string", ".", "decode", "(", "\"utf-8\"", ")", "return", "string" ]
Safely convert the given string to a Unicode string, decoding using ``sys.stdin.encoding`` if needed. If running from a frozen binary, ``utf-8`` encoding is assumed. :param variant string: the byte string or Unicode string to convert :rtype: string
[ "Safely", "convert", "the", "given", "string", "to", "a", "Unicode", "string", "decoding", "using", "sys", ".", "stdin", ".", "encoding", "if", "needed", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1235-L1256
232,284
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
TTSCache.get
def get(self, fragment_info): """ Get the value associated with the given key. :param fragment_info: the text key :type fragment_info: tuple of str ``(language, text)`` :raises: KeyError if the key is not present in the cache """ if not self.is_cached(fragment_info): raise KeyError(u"Attempt to get text not cached") return self.cache[fragment_info]
python
def get(self, fragment_info): """ Get the value associated with the given key. :param fragment_info: the text key :type fragment_info: tuple of str ``(language, text)`` :raises: KeyError if the key is not present in the cache """ if not self.is_cached(fragment_info): raise KeyError(u"Attempt to get text not cached") return self.cache[fragment_info]
[ "def", "get", "(", "self", ",", "fragment_info", ")", ":", "if", "not", "self", ".", "is_cached", "(", "fragment_info", ")", ":", "raise", "KeyError", "(", "u\"Attempt to get text not cached\"", ")", "return", "self", ".", "cache", "[", "fragment_info", "]" ]
Get the value associated with the given key. :param fragment_info: the text key :type fragment_info: tuple of str ``(language, text)`` :raises: KeyError if the key is not present in the cache
[ "Get", "the", "value", "associated", "with", "the", "given", "key", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L116-L126
232,285
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
TTSCache.clear
def clear(self): """ Clear the cache and remove all the files from disk. """ self.log(u"Clearing cache...") for file_handler, file_info in self.cache.values(): self.log([u" Removing file '%s'", file_info]) gf.delete_file(file_handler, file_info) self._initialize_cache() self.log(u"Clearing cache... done")
python
def clear(self): """ Clear the cache and remove all the files from disk. """ self.log(u"Clearing cache...") for file_handler, file_info in self.cache.values(): self.log([u" Removing file '%s'", file_info]) gf.delete_file(file_handler, file_info) self._initialize_cache() self.log(u"Clearing cache... done")
[ "def", "clear", "(", "self", ")", ":", "self", ".", "log", "(", "u\"Clearing cache...\"", ")", "for", "file_handler", ",", "file_info", "in", "self", ".", "cache", ".", "values", "(", ")", ":", "self", ".", "log", "(", "[", "u\" Removing file '%s'\"", ",", "file_info", "]", ")", "gf", ".", "delete_file", "(", "file_handler", ",", "file_info", ")", "self", ".", "_initialize_cache", "(", ")", "self", ".", "log", "(", "u\"Clearing cache... done\"", ")" ]
Clear the cache and remove all the files from disk.
[ "Clear", "the", "cache", "and", "remove", "all", "the", "files", "from", "disk", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L128-L137
232,286
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._language_to_voice_code
def _language_to_voice_code(self, language): """ Translate a language value to a voice code. If you want to mock support for a language by using a voice for a similar language, please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary. :param language: the requested language :type language: :class:`~aeneas.language.Language` :rtype: string """ voice_code = self.rconf[RuntimeConfiguration.TTS_VOICE_CODE] if voice_code is None: try: voice_code = self.LANGUAGE_TO_VOICE_CODE[language] except KeyError as exc: self.log_exc(u"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE" % (language), exc, False, None) self.log_warn(u"Using the language code as the voice code") voice_code = language else: self.log(u"TTS voice override in rconf") self.log([u"Language to voice code: '%s' => '%s'", language, voice_code]) return voice_code
python
def _language_to_voice_code(self, language): """ Translate a language value to a voice code. If you want to mock support for a language by using a voice for a similar language, please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary. :param language: the requested language :type language: :class:`~aeneas.language.Language` :rtype: string """ voice_code = self.rconf[RuntimeConfiguration.TTS_VOICE_CODE] if voice_code is None: try: voice_code = self.LANGUAGE_TO_VOICE_CODE[language] except KeyError as exc: self.log_exc(u"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE" % (language), exc, False, None) self.log_warn(u"Using the language code as the voice code") voice_code = language else: self.log(u"TTS voice override in rconf") self.log([u"Language to voice code: '%s' => '%s'", language, voice_code]) return voice_code
[ "def", "_language_to_voice_code", "(", "self", ",", "language", ")", ":", "voice_code", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "TTS_VOICE_CODE", "]", "if", "voice_code", "is", "None", ":", "try", ":", "voice_code", "=", "self", ".", "LANGUAGE_TO_VOICE_CODE", "[", "language", "]", "except", "KeyError", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE\"", "%", "(", "language", ")", ",", "exc", ",", "False", ",", "None", ")", "self", ".", "log_warn", "(", "u\"Using the language code as the voice code\"", ")", "voice_code", "=", "language", "else", ":", "self", ".", "log", "(", "u\"TTS voice override in rconf\"", ")", "self", ".", "log", "(", "[", "u\"Language to voice code: '%s' => '%s'\"", ",", "language", ",", "voice_code", "]", ")", "return", "voice_code" ]
Translate a language value to a voice code. If you want to mock support for a language by using a voice for a similar language, please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary. :param language: the requested language :type language: :class:`~aeneas.language.Language` :rtype: string
[ "Translate", "a", "language", "value", "to", "a", "voice", "code", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L299-L322
232,287
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper.clear_cache
def clear_cache(self): """ Clear the TTS cache, removing all cache files from disk. .. versionadded:: 1.6.0 """ if self.use_cache: self.log(u"Requested to clear TTS cache") self.cache.clear()
python
def clear_cache(self): """ Clear the TTS cache, removing all cache files from disk. .. versionadded:: 1.6.0 """ if self.use_cache: self.log(u"Requested to clear TTS cache") self.cache.clear()
[ "def", "clear_cache", "(", "self", ")", ":", "if", "self", ".", "use_cache", ":", "self", ".", "log", "(", "u\"Requested to clear TTS cache\"", ")", "self", ".", "cache", ".", "clear", "(", ")" ]
Clear the TTS cache, removing all cache files from disk. .. versionadded:: 1.6.0
[ "Clear", "the", "TTS", "cache", "removing", "all", "cache", "files", "from", "disk", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L331-L339
232,288
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper.set_subprocess_arguments
def set_subprocess_arguments(self, subprocess_arguments): """ Set the list of arguments that the wrapper will pass to ``subprocess``. Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced by actual values in the ``_synthesize_multiple_subprocess()`` and ``_synthesize_single_subprocess()`` built-in functions. Literal parameters will be passed unchanged. The list should start with the path to the TTS engine. This function should be called in the constructor of concrete subclasses. :param list subprocess_arguments: the list of arguments to be passed to the TTS engine via subprocess """ # NOTE this is a method because we might need to access self.rconf, # so we cannot specify the list of arguments as a class field self.subprocess_arguments = subprocess_arguments self.log([u"Subprocess arguments: %s", subprocess_arguments])
python
def set_subprocess_arguments(self, subprocess_arguments): """ Set the list of arguments that the wrapper will pass to ``subprocess``. Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced by actual values in the ``_synthesize_multiple_subprocess()`` and ``_synthesize_single_subprocess()`` built-in functions. Literal parameters will be passed unchanged. The list should start with the path to the TTS engine. This function should be called in the constructor of concrete subclasses. :param list subprocess_arguments: the list of arguments to be passed to the TTS engine via subprocess """ # NOTE this is a method because we might need to access self.rconf, # so we cannot specify the list of arguments as a class field self.subprocess_arguments = subprocess_arguments self.log([u"Subprocess arguments: %s", subprocess_arguments])
[ "def", "set_subprocess_arguments", "(", "self", ",", "subprocess_arguments", ")", ":", "# NOTE this is a method because we might need to access self.rconf,", "# so we cannot specify the list of arguments as a class field", "self", ".", "subprocess_arguments", "=", "subprocess_arguments", "self", ".", "log", "(", "[", "u\"Subprocess arguments: %s\"", ",", "subprocess_arguments", "]", ")" ]
Set the list of arguments that the wrapper will pass to ``subprocess``. Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced by actual values in the ``_synthesize_multiple_subprocess()`` and ``_synthesize_single_subprocess()`` built-in functions. Literal parameters will be passed unchanged. The list should start with the path to the TTS engine. This function should be called in the constructor of concrete subclasses. :param list subprocess_arguments: the list of arguments to be passed to the TTS engine via subprocess
[ "Set", "the", "list", "of", "arguments", "that", "the", "wrapper", "will", "pass", "to", "subprocess", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L341-L361
232,289
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper.synthesize_multiple
def synthesize_multiple(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize the text contained in the given fragment list into a WAVE file. Return a tuple (anchors, total_time, num_chars). Concrete subclasses must implement at least one of the following private functions: 1. ``_synthesize_multiple_python()`` 2. ``_synthesize_multiple_c_extension()`` 3. ``_synthesize_multiple_subprocess()`` :param text_file: the text file to be synthesized :type text_file: :class:`~aeneas.textfile.TextFile` :param string output_file_path: the path to the output audio file :param quit_after: stop synthesizing as soon as reaching this many seconds :type quit_after: :class:`~aeneas.exacttiming.TimeValue` :param bool backwards: if > 0, synthesize from the end of the text file :rtype: tuple (anchors, total_time, num_chars) :raises: TypeError: if ``text_file`` is ``None`` or one of the text fragments is not a Unicode string :raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False`` and a fragment has a language code not supported by the TTS engine, or if ``text_file`` has no fragments or all its fragments are empty :raises: OSError: if output file cannot be written to ``output_file_path`` :raises: RuntimeError: if both the C extension and the pure Python code did not succeed. """ if text_file is None: self.log_exc(u"text_file is None", None, True, TypeError) if len(text_file) < 1: self.log_exc(u"The text file has no fragments", None, True, ValueError) if text_file.chars == 0: self.log_exc(u"All fragments in the text file are empty", None, True, ValueError) if not self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]: for fragment in text_file.fragments: if fragment.language not in self.LANGUAGE_TO_VOICE_CODE: self.log_exc(u"Language '%s' is not supported by the selected TTS engine" % (fragment.language), None, True, ValueError) for fragment in text_file.fragments: for line in fragment.lines: if not gf.is_unicode(line): self.log_exc(u"The text file contain a line which is not a Unicode string", None, True, TypeError) # log parameters if quit_after is not None: self.log([u"Quit after reaching %.3f", quit_after]) if backwards: self.log(u"Synthesizing backwards") # check that output_file_path can be written if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError) # first, call Python function _synthesize_multiple_python() if available if self.HAS_PYTHON_CALL: self.log(u"Calling TTS engine via Python") try: computed, result = self._synthesize_multiple_python(text_file, output_file_path, quit_after, backwards) if computed: self.log(u"The _synthesize_multiple_python call was successful, returning anchors") return result else: self.log(u"The _synthesize_multiple_python call failed") except Exception as exc: self.log_exc(u"An unexpected error occurred while calling _synthesize_multiple_python", exc, False, None) # call _synthesize_multiple_c_extension() or _synthesize_multiple_subprocess() self.log(u"Calling TTS engine via C extension or subprocess") c_extension_function = self._synthesize_multiple_c_extension if self.HAS_C_EXTENSION_CALL else None subprocess_function = self._synthesize_multiple_subprocess if self.HAS_SUBPROCESS_CALL else None return gf.run_c_extension_with_fallback( self.log, self.C_EXTENSION_NAME, c_extension_function, subprocess_function, (text_file, output_file_path, quit_after, backwards), rconf=self.rconf )
python
def synthesize_multiple(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize the text contained in the given fragment list into a WAVE file. Return a tuple (anchors, total_time, num_chars). Concrete subclasses must implement at least one of the following private functions: 1. ``_synthesize_multiple_python()`` 2. ``_synthesize_multiple_c_extension()`` 3. ``_synthesize_multiple_subprocess()`` :param text_file: the text file to be synthesized :type text_file: :class:`~aeneas.textfile.TextFile` :param string output_file_path: the path to the output audio file :param quit_after: stop synthesizing as soon as reaching this many seconds :type quit_after: :class:`~aeneas.exacttiming.TimeValue` :param bool backwards: if > 0, synthesize from the end of the text file :rtype: tuple (anchors, total_time, num_chars) :raises: TypeError: if ``text_file`` is ``None`` or one of the text fragments is not a Unicode string :raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False`` and a fragment has a language code not supported by the TTS engine, or if ``text_file`` has no fragments or all its fragments are empty :raises: OSError: if output file cannot be written to ``output_file_path`` :raises: RuntimeError: if both the C extension and the pure Python code did not succeed. """ if text_file is None: self.log_exc(u"text_file is None", None, True, TypeError) if len(text_file) < 1: self.log_exc(u"The text file has no fragments", None, True, ValueError) if text_file.chars == 0: self.log_exc(u"All fragments in the text file are empty", None, True, ValueError) if not self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]: for fragment in text_file.fragments: if fragment.language not in self.LANGUAGE_TO_VOICE_CODE: self.log_exc(u"Language '%s' is not supported by the selected TTS engine" % (fragment.language), None, True, ValueError) for fragment in text_file.fragments: for line in fragment.lines: if not gf.is_unicode(line): self.log_exc(u"The text file contain a line which is not a Unicode string", None, True, TypeError) # log parameters if quit_after is not None: self.log([u"Quit after reaching %.3f", quit_after]) if backwards: self.log(u"Synthesizing backwards") # check that output_file_path can be written if not gf.file_can_be_written(output_file_path): self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError) # first, call Python function _synthesize_multiple_python() if available if self.HAS_PYTHON_CALL: self.log(u"Calling TTS engine via Python") try: computed, result = self._synthesize_multiple_python(text_file, output_file_path, quit_after, backwards) if computed: self.log(u"The _synthesize_multiple_python call was successful, returning anchors") return result else: self.log(u"The _synthesize_multiple_python call failed") except Exception as exc: self.log_exc(u"An unexpected error occurred while calling _synthesize_multiple_python", exc, False, None) # call _synthesize_multiple_c_extension() or _synthesize_multiple_subprocess() self.log(u"Calling TTS engine via C extension or subprocess") c_extension_function = self._synthesize_multiple_c_extension if self.HAS_C_EXTENSION_CALL else None subprocess_function = self._synthesize_multiple_subprocess if self.HAS_SUBPROCESS_CALL else None return gf.run_c_extension_with_fallback( self.log, self.C_EXTENSION_NAME, c_extension_function, subprocess_function, (text_file, output_file_path, quit_after, backwards), rconf=self.rconf )
[ "def", "synthesize_multiple", "(", "self", ",", "text_file", ",", "output_file_path", ",", "quit_after", "=", "None", ",", "backwards", "=", "False", ")", ":", "if", "text_file", "is", "None", ":", "self", ".", "log_exc", "(", "u\"text_file is None\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "len", "(", "text_file", ")", "<", "1", ":", "self", ".", "log_exc", "(", "u\"The text file has no fragments\"", ",", "None", ",", "True", ",", "ValueError", ")", "if", "text_file", ".", "chars", "==", "0", ":", "self", ".", "log_exc", "(", "u\"All fragments in the text file are empty\"", ",", "None", ",", "True", ",", "ValueError", ")", "if", "not", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "ALLOW_UNLISTED_LANGUAGES", "]", ":", "for", "fragment", "in", "text_file", ".", "fragments", ":", "if", "fragment", ".", "language", "not", "in", "self", ".", "LANGUAGE_TO_VOICE_CODE", ":", "self", ".", "log_exc", "(", "u\"Language '%s' is not supported by the selected TTS engine\"", "%", "(", "fragment", ".", "language", ")", ",", "None", ",", "True", ",", "ValueError", ")", "for", "fragment", "in", "text_file", ".", "fragments", ":", "for", "line", "in", "fragment", ".", "lines", ":", "if", "not", "gf", ".", "is_unicode", "(", "line", ")", ":", "self", ".", "log_exc", "(", "u\"The text file contain a line which is not a Unicode string\"", ",", "None", ",", "True", ",", "TypeError", ")", "# log parameters", "if", "quit_after", "is", "not", "None", ":", "self", ".", "log", "(", "[", "u\"Quit after reaching %.3f\"", ",", "quit_after", "]", ")", "if", "backwards", ":", "self", ".", "log", "(", "u\"Synthesizing backwards\"", ")", "# check that output_file_path can be written", "if", "not", "gf", ".", "file_can_be_written", "(", "output_file_path", ")", ":", "self", ".", "log_exc", "(", "u\"Cannot write to output file '%s'\"", "%", "(", "output_file_path", ")", ",", "None", ",", "True", ",", "OSError", ")", "# first, call Python function _synthesize_multiple_python() if available", "if", "self", ".", "HAS_PYTHON_CALL", ":", "self", ".", "log", "(", "u\"Calling TTS engine via Python\"", ")", "try", ":", "computed", ",", "result", "=", "self", ".", "_synthesize_multiple_python", "(", "text_file", ",", "output_file_path", ",", "quit_after", ",", "backwards", ")", "if", "computed", ":", "self", ".", "log", "(", "u\"The _synthesize_multiple_python call was successful, returning anchors\"", ")", "return", "result", "else", ":", "self", ".", "log", "(", "u\"The _synthesize_multiple_python call failed\"", ")", "except", "Exception", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"An unexpected error occurred while calling _synthesize_multiple_python\"", ",", "exc", ",", "False", ",", "None", ")", "# call _synthesize_multiple_c_extension() or _synthesize_multiple_subprocess()", "self", ".", "log", "(", "u\"Calling TTS engine via C extension or subprocess\"", ")", "c_extension_function", "=", "self", ".", "_synthesize_multiple_c_extension", "if", "self", ".", "HAS_C_EXTENSION_CALL", "else", "None", "subprocess_function", "=", "self", ".", "_synthesize_multiple_subprocess", "if", "self", ".", "HAS_SUBPROCESS_CALL", "else", "None", "return", "gf", ".", "run_c_extension_with_fallback", "(", "self", ".", "log", ",", "self", ".", "C_EXTENSION_NAME", ",", "c_extension_function", ",", "subprocess_function", ",", "(", "text_file", ",", "output_file_path", ",", "quit_after", ",", "backwards", ")", ",", "rconf", "=", "self", ".", "rconf", ")" ]
Synthesize the text contained in the given fragment list into a WAVE file. Return a tuple (anchors, total_time, num_chars). Concrete subclasses must implement at least one of the following private functions: 1. ``_synthesize_multiple_python()`` 2. ``_synthesize_multiple_c_extension()`` 3. ``_synthesize_multiple_subprocess()`` :param text_file: the text file to be synthesized :type text_file: :class:`~aeneas.textfile.TextFile` :param string output_file_path: the path to the output audio file :param quit_after: stop synthesizing as soon as reaching this many seconds :type quit_after: :class:`~aeneas.exacttiming.TimeValue` :param bool backwards: if > 0, synthesize from the end of the text file :rtype: tuple (anchors, total_time, num_chars) :raises: TypeError: if ``text_file`` is ``None`` or one of the text fragments is not a Unicode string :raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False`` and a fragment has a language code not supported by the TTS engine, or if ``text_file`` has no fragments or all its fragments are empty :raises: OSError: if output file cannot be written to ``output_file_path`` :raises: RuntimeError: if both the C extension and the pure Python code did not succeed.
[ "Synthesize", "the", "text", "contained", "in", "the", "given", "fragment", "list", "into", "a", "WAVE", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L363-L443
232,290
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._synthesize_multiple_python
def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars)) """ self.log(u"Synthesizing multiple via a Python call...") ret = self._synthesize_multiple_generic( helper_function=self._synthesize_single_python_helper, text_file=text_file, output_file_path=output_file_path, quit_after=quit_after, backwards=backwards ) self.log(u"Synthesizing multiple via a Python call... done") return ret
python
def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars)) """ self.log(u"Synthesizing multiple via a Python call...") ret = self._synthesize_multiple_generic( helper_function=self._synthesize_single_python_helper, text_file=text_file, output_file_path=output_file_path, quit_after=quit_after, backwards=backwards ) self.log(u"Synthesizing multiple via a Python call... done") return ret
[ "def", "_synthesize_multiple_python", "(", "self", ",", "text_file", ",", "output_file_path", ",", "quit_after", "=", "None", ",", "backwards", "=", "False", ")", ":", "self", ".", "log", "(", "u\"Synthesizing multiple via a Python call...\"", ")", "ret", "=", "self", ".", "_synthesize_multiple_generic", "(", "helper_function", "=", "self", ".", "_synthesize_single_python_helper", ",", "text_file", "=", "text_file", ",", "output_file_path", "=", "output_file_path", ",", "quit_after", "=", "quit_after", ",", "backwards", "=", "backwards", ")", "self", ".", "log", "(", "u\"Synthesizing multiple via a Python call... done\"", ")", "return", "ret" ]
Synthesize multiple fragments via a Python call. :rtype: tuple (result, (anchors, current_time, num_chars))
[ "Synthesize", "multiple", "fragments", "via", "a", "Python", "call", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L445-L460
232,291
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._synthesize_multiple_subprocess
def _synthesize_multiple_subprocess(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments via ``subprocess``. :rtype: tuple (result, (anchors, current_time, num_chars)) """ self.log(u"Synthesizing multiple via subprocess...") ret = self._synthesize_multiple_generic( helper_function=self._synthesize_single_subprocess_helper, text_file=text_file, output_file_path=output_file_path, quit_after=quit_after, backwards=backwards ) self.log(u"Synthesizing multiple via subprocess... done") return ret
python
def _synthesize_multiple_subprocess(self, text_file, output_file_path, quit_after=None, backwards=False): """ Synthesize multiple fragments via ``subprocess``. :rtype: tuple (result, (anchors, current_time, num_chars)) """ self.log(u"Synthesizing multiple via subprocess...") ret = self._synthesize_multiple_generic( helper_function=self._synthesize_single_subprocess_helper, text_file=text_file, output_file_path=output_file_path, quit_after=quit_after, backwards=backwards ) self.log(u"Synthesizing multiple via subprocess... done") return ret
[ "def", "_synthesize_multiple_subprocess", "(", "self", ",", "text_file", ",", "output_file_path", ",", "quit_after", "=", "None", ",", "backwards", "=", "False", ")", ":", "self", ".", "log", "(", "u\"Synthesizing multiple via subprocess...\"", ")", "ret", "=", "self", ".", "_synthesize_multiple_generic", "(", "helper_function", "=", "self", ".", "_synthesize_single_subprocess_helper", ",", "text_file", "=", "text_file", ",", "output_file_path", "=", "output_file_path", ",", "quit_after", "=", "quit_after", ",", "backwards", "=", "backwards", ")", "self", ".", "log", "(", "u\"Synthesizing multiple via subprocess... done\"", ")", "return", "ret" ]
Synthesize multiple fragments via ``subprocess``. :rtype: tuple (result, (anchors, current_time, num_chars))
[ "Synthesize", "multiple", "fragments", "via", "subprocess", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L496-L511
232,292
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._read_audio_data
def _read_audio_data(self, file_path): """ Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception """ try: self.log(u"Reading audio data...") # if we know the TTS outputs to PCM16 mono WAVE # with the correct sample rate, # we can read samples directly from it, # without an intermediate conversion through ffmpeg audio_file = AudioFile( file_path=file_path, file_format=self.OUTPUT_AUDIO_FORMAT, rconf=self.rconf, logger=self.logger ) audio_file.read_samples_from_file() self.log([u"Duration of '%s': %f", file_path, audio_file.audio_length]) self.log(u"Reading audio data... done") return (True, ( audio_file.audio_length, audio_file.audio_sample_rate, audio_file.audio_format, audio_file.audio_samples )) except (AudioFileUnsupportedFormatError, OSError) as exc: self.log_exc(u"An unexpected error occurred while reading audio data", exc, True, None) return (False, None)
python
def _read_audio_data(self, file_path): """ Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception """ try: self.log(u"Reading audio data...") # if we know the TTS outputs to PCM16 mono WAVE # with the correct sample rate, # we can read samples directly from it, # without an intermediate conversion through ffmpeg audio_file = AudioFile( file_path=file_path, file_format=self.OUTPUT_AUDIO_FORMAT, rconf=self.rconf, logger=self.logger ) audio_file.read_samples_from_file() self.log([u"Duration of '%s': %f", file_path, audio_file.audio_length]) self.log(u"Reading audio data... done") return (True, ( audio_file.audio_length, audio_file.audio_sample_rate, audio_file.audio_format, audio_file.audio_samples )) except (AudioFileUnsupportedFormatError, OSError) as exc: self.log_exc(u"An unexpected error occurred while reading audio data", exc, True, None) return (False, None)
[ "def", "_read_audio_data", "(", "self", ",", "file_path", ")", ":", "try", ":", "self", ".", "log", "(", "u\"Reading audio data...\"", ")", "# if we know the TTS outputs to PCM16 mono WAVE", "# with the correct sample rate,", "# we can read samples directly from it,", "# without an intermediate conversion through ffmpeg", "audio_file", "=", "AudioFile", "(", "file_path", "=", "file_path", ",", "file_format", "=", "self", ".", "OUTPUT_AUDIO_FORMAT", ",", "rconf", "=", "self", ".", "rconf", ",", "logger", "=", "self", ".", "logger", ")", "audio_file", ".", "read_samples_from_file", "(", ")", "self", ".", "log", "(", "[", "u\"Duration of '%s': %f\"", ",", "file_path", ",", "audio_file", ".", "audio_length", "]", ")", "self", ".", "log", "(", "u\"Reading audio data... done\"", ")", "return", "(", "True", ",", "(", "audio_file", ".", "audio_length", ",", "audio_file", ".", "audio_sample_rate", ",", "audio_file", ".", "audio_format", ",", "audio_file", ".", "audio_samples", ")", ")", "except", "(", "AudioFileUnsupportedFormatError", ",", "OSError", ")", "as", "exc", ":", "self", ".", "log_exc", "(", "u\"An unexpected error occurred while reading audio data\"", ",", "exc", ",", "True", ",", "None", ")", "return", "(", "False", ",", "None", ")" ]
Read audio data from file. :rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
[ "Read", "audio", "data", "from", "file", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L639-L668
232,293
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._loop_no_cache
def _loop_no_cache(self, helper_function, num, fragment): """ Synthesize all fragments without using the cache """ self.log([u"Examining fragment %d (no cache)...", num]) # synthesize and get the duration of the output file voice_code = self._language_to_voice_code(fragment.language) self.log(u"Calling helper function") succeeded, data = helper_function( text=fragment.filtered_text, voice_code=voice_code, output_file_path=None, return_audio_data=True ) # check output if not succeeded: self.log_crit(u"An unexpected error occurred in helper_function") return (False, None) self.log([u"Examining fragment %d (no cache)... done", num]) return (True, data)
python
def _loop_no_cache(self, helper_function, num, fragment): """ Synthesize all fragments without using the cache """ self.log([u"Examining fragment %d (no cache)...", num]) # synthesize and get the duration of the output file voice_code = self._language_to_voice_code(fragment.language) self.log(u"Calling helper function") succeeded, data = helper_function( text=fragment.filtered_text, voice_code=voice_code, output_file_path=None, return_audio_data=True ) # check output if not succeeded: self.log_crit(u"An unexpected error occurred in helper_function") return (False, None) self.log([u"Examining fragment %d (no cache)... done", num]) return (True, data)
[ "def", "_loop_no_cache", "(", "self", ",", "helper_function", ",", "num", ",", "fragment", ")", ":", "self", ".", "log", "(", "[", "u\"Examining fragment %d (no cache)...\"", ",", "num", "]", ")", "# synthesize and get the duration of the output file", "voice_code", "=", "self", ".", "_language_to_voice_code", "(", "fragment", ".", "language", ")", "self", ".", "log", "(", "u\"Calling helper function\"", ")", "succeeded", ",", "data", "=", "helper_function", "(", "text", "=", "fragment", ".", "filtered_text", ",", "voice_code", "=", "voice_code", ",", "output_file_path", "=", "None", ",", "return_audio_data", "=", "True", ")", "# check output", "if", "not", "succeeded", ":", "self", ".", "log_crit", "(", "u\"An unexpected error occurred in helper_function\"", ")", "return", "(", "False", ",", "None", ")", "self", ".", "log", "(", "[", "u\"Examining fragment %d (no cache)... done\"", ",", "num", "]", ")", "return", "(", "True", ",", "data", ")" ]
Synthesize all fragments without using the cache
[ "Synthesize", "all", "fragments", "without", "using", "the", "cache" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L769-L786
232,294
readbeyond/aeneas
aeneas/ttswrappers/basettswrapper.py
BaseTTSWrapper._loop_use_cache
def _loop_use_cache(self, helper_function, num, fragment): """ Synthesize all fragments using the cache """ self.log([u"Examining fragment %d (cache)...", num]) fragment_info = (fragment.language, fragment.filtered_text) if self.cache.is_cached(fragment_info): self.log(u"Fragment cached: retrieving audio data from cache") # read data from file, whose path is in the cache file_handler, file_path = self.cache.get(fragment_info) self.log([u"Reading cached fragment at '%s'...", file_path]) succeeded, data = self._read_audio_data(file_path) if not succeeded: self.log_crit(u"An unexpected error occurred while reading cached audio file") return (False, None) self.log([u"Reading cached fragment at '%s'... done", file_path]) else: self.log(u"Fragment not cached: synthesizing and caching") # creating destination file file_info = gf.tmp_file(suffix=u".cache.wav", root=self.rconf[RuntimeConfiguration.TMP_PATH]) file_handler, file_path = file_info self.log([u"Synthesizing fragment to '%s'...", file_path]) # synthesize and get the duration of the output file voice_code = self._language_to_voice_code(fragment.language) self.log(u"Calling helper function") succeeded, data = helper_function( text=fragment.filtered_text, voice_code=voice_code, output_file_path=file_path, return_audio_data=True ) # check output if not succeeded: self.log_crit(u"An unexpected error occurred in helper_function") return (False, None) self.log([u"Synthesizing fragment to '%s'... done", file_path]) duration, sr_nu, enc_nu, samples = data if duration > 0: self.log(u"Fragment has > 0 duration, adding it to cache") self.cache.add(fragment_info, file_info) self.log(u"Added fragment to cache") else: self.log(u"Fragment has zero duration, not adding it to cache") self.log([u"Closing file handler for cached output file path '%s'", file_path]) gf.close_file_handler(file_handler) self.log([u"Examining fragment %d (cache)... done", num]) return (True, data)
python
def _loop_use_cache(self, helper_function, num, fragment): """ Synthesize all fragments using the cache """ self.log([u"Examining fragment %d (cache)...", num]) fragment_info = (fragment.language, fragment.filtered_text) if self.cache.is_cached(fragment_info): self.log(u"Fragment cached: retrieving audio data from cache") # read data from file, whose path is in the cache file_handler, file_path = self.cache.get(fragment_info) self.log([u"Reading cached fragment at '%s'...", file_path]) succeeded, data = self._read_audio_data(file_path) if not succeeded: self.log_crit(u"An unexpected error occurred while reading cached audio file") return (False, None) self.log([u"Reading cached fragment at '%s'... done", file_path]) else: self.log(u"Fragment not cached: synthesizing and caching") # creating destination file file_info = gf.tmp_file(suffix=u".cache.wav", root=self.rconf[RuntimeConfiguration.TMP_PATH]) file_handler, file_path = file_info self.log([u"Synthesizing fragment to '%s'...", file_path]) # synthesize and get the duration of the output file voice_code = self._language_to_voice_code(fragment.language) self.log(u"Calling helper function") succeeded, data = helper_function( text=fragment.filtered_text, voice_code=voice_code, output_file_path=file_path, return_audio_data=True ) # check output if not succeeded: self.log_crit(u"An unexpected error occurred in helper_function") return (False, None) self.log([u"Synthesizing fragment to '%s'... done", file_path]) duration, sr_nu, enc_nu, samples = data if duration > 0: self.log(u"Fragment has > 0 duration, adding it to cache") self.cache.add(fragment_info, file_info) self.log(u"Added fragment to cache") else: self.log(u"Fragment has zero duration, not adding it to cache") self.log([u"Closing file handler for cached output file path '%s'", file_path]) gf.close_file_handler(file_handler) self.log([u"Examining fragment %d (cache)... done", num]) return (True, data)
[ "def", "_loop_use_cache", "(", "self", ",", "helper_function", ",", "num", ",", "fragment", ")", ":", "self", ".", "log", "(", "[", "u\"Examining fragment %d (cache)...\"", ",", "num", "]", ")", "fragment_info", "=", "(", "fragment", ".", "language", ",", "fragment", ".", "filtered_text", ")", "if", "self", ".", "cache", ".", "is_cached", "(", "fragment_info", ")", ":", "self", ".", "log", "(", "u\"Fragment cached: retrieving audio data from cache\"", ")", "# read data from file, whose path is in the cache", "file_handler", ",", "file_path", "=", "self", ".", "cache", ".", "get", "(", "fragment_info", ")", "self", ".", "log", "(", "[", "u\"Reading cached fragment at '%s'...\"", ",", "file_path", "]", ")", "succeeded", ",", "data", "=", "self", ".", "_read_audio_data", "(", "file_path", ")", "if", "not", "succeeded", ":", "self", ".", "log_crit", "(", "u\"An unexpected error occurred while reading cached audio file\"", ")", "return", "(", "False", ",", "None", ")", "self", ".", "log", "(", "[", "u\"Reading cached fragment at '%s'... done\"", ",", "file_path", "]", ")", "else", ":", "self", ".", "log", "(", "u\"Fragment not cached: synthesizing and caching\"", ")", "# creating destination file", "file_info", "=", "gf", ".", "tmp_file", "(", "suffix", "=", "u\".cache.wav\"", ",", "root", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "TMP_PATH", "]", ")", "file_handler", ",", "file_path", "=", "file_info", "self", ".", "log", "(", "[", "u\"Synthesizing fragment to '%s'...\"", ",", "file_path", "]", ")", "# synthesize and get the duration of the output file", "voice_code", "=", "self", ".", "_language_to_voice_code", "(", "fragment", ".", "language", ")", "self", ".", "log", "(", "u\"Calling helper function\"", ")", "succeeded", ",", "data", "=", "helper_function", "(", "text", "=", "fragment", ".", "filtered_text", ",", "voice_code", "=", "voice_code", ",", "output_file_path", "=", "file_path", ",", "return_audio_data", "=", "True", ")", "# check output", "if", "not", "succeeded", ":", "self", ".", "log_crit", "(", "u\"An unexpected error occurred in helper_function\"", ")", "return", "(", "False", ",", "None", ")", "self", ".", "log", "(", "[", "u\"Synthesizing fragment to '%s'... done\"", ",", "file_path", "]", ")", "duration", ",", "sr_nu", ",", "enc_nu", ",", "samples", "=", "data", "if", "duration", ">", "0", ":", "self", ".", "log", "(", "u\"Fragment has > 0 duration, adding it to cache\"", ")", "self", ".", "cache", ".", "add", "(", "fragment_info", ",", "file_info", ")", "self", ".", "log", "(", "u\"Added fragment to cache\"", ")", "else", ":", "self", ".", "log", "(", "u\"Fragment has zero duration, not adding it to cache\"", ")", "self", ".", "log", "(", "[", "u\"Closing file handler for cached output file path '%s'\"", ",", "file_path", "]", ")", "gf", ".", "close_file_handler", "(", "file_handler", ")", "self", ".", "log", "(", "[", "u\"Examining fragment %d (cache)... done\"", ",", "num", "]", ")", "return", "(", "True", ",", "data", ")" ]
Synthesize all fragments using the cache
[ "Synthesize", "all", "fragments", "using", "the", "cache" ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L788-L835
232,295
readbeyond/aeneas
aeneas/adjustboundaryalgorithm.py
AdjustBoundaryAlgorithm.adjust
def adjust( self, aba_parameters, boundary_indices, real_wave_mfcc, text_file, allow_arbitrary_shift=False ): """ Adjust the boundaries of the text map using the algorithm and parameters specified in the constructor, storing the sync map fragment list internally. :param dict aba_parameters: a dictionary containing the algorithm and its parameters, as produced by ``aba_parameters()`` in ``TaskConfiguration`` :param boundary_indices: the current boundary indices, with respect to the audio file full MFCCs :type boundary_indices: :class:`numpy.ndarray` (1D) :param real_wave_mfcc: the audio file MFCCs :type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC` :param text_file: the text file containing the text fragments associated :type text_file: :class:`~aeneas.textfile.TextFile` :param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length :rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList` """ self.log(u"Called adjust") if boundary_indices is None: self.log_exc(u"boundary_indices is None", None, True, TypeError) if not isinstance(real_wave_mfcc, AudioFileMFCC): self.log_exc(u"real_wave_mfcc is not an AudioFileMFCC object", None, True, TypeError) if not isinstance(text_file, TextFile): self.log_exc(u"text_file is not a TextFile object", None, True, TypeError) nozero = aba_parameters["nozero"] ns_min, ns_string = aba_parameters["nonspeech"] algorithm, algo_parameters = aba_parameters["algorithm"] self.log(u" Converting boundary indices to fragment list...") begin = real_wave_mfcc.middle_begin * real_wave_mfcc.rconf.mws end = real_wave_mfcc.middle_end * real_wave_mfcc.rconf.mws time_values = [begin] + list(boundary_indices * self.mws) + [end] self.intervals_to_fragment_list( text_file=text_file, time_values=time_values ) self.log(u" Converting boundary indices to fragment list... done") self.log(u" Processing fragments with zero length...") self._process_zero_length(nozero, allow_arbitrary_shift) self.log(u" Processing fragments with zero length... done") self.log(u" Processing nonspeech fragments...") self._process_long_nonspeech(ns_min, ns_string, real_wave_mfcc) self.log(u" Processing nonspeech fragments... done") self.log(u" Adjusting...") ALGORITHM_MAP = { self.AFTERCURRENT: self._adjust_aftercurrent, self.AUTO: self._adjust_auto, self.BEFORENEXT: self._adjust_beforenext, self.OFFSET: self._adjust_offset, self.PERCENT: self._adjust_percent, self.RATE: self._adjust_rate, self.RATEAGGRESSIVE: self._adjust_rate_aggressive, } ALGORITHM_MAP[algorithm](real_wave_mfcc, algo_parameters) self.log(u" Adjusting... done") self.log(u" Smoothing...") self._smooth_fragment_list(real_wave_mfcc.audio_length, ns_string) self.log(u" Smoothing... done") return self.smflist
python
def adjust( self, aba_parameters, boundary_indices, real_wave_mfcc, text_file, allow_arbitrary_shift=False ): """ Adjust the boundaries of the text map using the algorithm and parameters specified in the constructor, storing the sync map fragment list internally. :param dict aba_parameters: a dictionary containing the algorithm and its parameters, as produced by ``aba_parameters()`` in ``TaskConfiguration`` :param boundary_indices: the current boundary indices, with respect to the audio file full MFCCs :type boundary_indices: :class:`numpy.ndarray` (1D) :param real_wave_mfcc: the audio file MFCCs :type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC` :param text_file: the text file containing the text fragments associated :type text_file: :class:`~aeneas.textfile.TextFile` :param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length :rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList` """ self.log(u"Called adjust") if boundary_indices is None: self.log_exc(u"boundary_indices is None", None, True, TypeError) if not isinstance(real_wave_mfcc, AudioFileMFCC): self.log_exc(u"real_wave_mfcc is not an AudioFileMFCC object", None, True, TypeError) if not isinstance(text_file, TextFile): self.log_exc(u"text_file is not a TextFile object", None, True, TypeError) nozero = aba_parameters["nozero"] ns_min, ns_string = aba_parameters["nonspeech"] algorithm, algo_parameters = aba_parameters["algorithm"] self.log(u" Converting boundary indices to fragment list...") begin = real_wave_mfcc.middle_begin * real_wave_mfcc.rconf.mws end = real_wave_mfcc.middle_end * real_wave_mfcc.rconf.mws time_values = [begin] + list(boundary_indices * self.mws) + [end] self.intervals_to_fragment_list( text_file=text_file, time_values=time_values ) self.log(u" Converting boundary indices to fragment list... done") self.log(u" Processing fragments with zero length...") self._process_zero_length(nozero, allow_arbitrary_shift) self.log(u" Processing fragments with zero length... done") self.log(u" Processing nonspeech fragments...") self._process_long_nonspeech(ns_min, ns_string, real_wave_mfcc) self.log(u" Processing nonspeech fragments... done") self.log(u" Adjusting...") ALGORITHM_MAP = { self.AFTERCURRENT: self._adjust_aftercurrent, self.AUTO: self._adjust_auto, self.BEFORENEXT: self._adjust_beforenext, self.OFFSET: self._adjust_offset, self.PERCENT: self._adjust_percent, self.RATE: self._adjust_rate, self.RATEAGGRESSIVE: self._adjust_rate_aggressive, } ALGORITHM_MAP[algorithm](real_wave_mfcc, algo_parameters) self.log(u" Adjusting... done") self.log(u" Smoothing...") self._smooth_fragment_list(real_wave_mfcc.audio_length, ns_string) self.log(u" Smoothing... done") return self.smflist
[ "def", "adjust", "(", "self", ",", "aba_parameters", ",", "boundary_indices", ",", "real_wave_mfcc", ",", "text_file", ",", "allow_arbitrary_shift", "=", "False", ")", ":", "self", ".", "log", "(", "u\"Called adjust\"", ")", "if", "boundary_indices", "is", "None", ":", "self", ".", "log_exc", "(", "u\"boundary_indices is None\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "not", "isinstance", "(", "real_wave_mfcc", ",", "AudioFileMFCC", ")", ":", "self", ".", "log_exc", "(", "u\"real_wave_mfcc is not an AudioFileMFCC object\"", ",", "None", ",", "True", ",", "TypeError", ")", "if", "not", "isinstance", "(", "text_file", ",", "TextFile", ")", ":", "self", ".", "log_exc", "(", "u\"text_file is not a TextFile object\"", ",", "None", ",", "True", ",", "TypeError", ")", "nozero", "=", "aba_parameters", "[", "\"nozero\"", "]", "ns_min", ",", "ns_string", "=", "aba_parameters", "[", "\"nonspeech\"", "]", "algorithm", ",", "algo_parameters", "=", "aba_parameters", "[", "\"algorithm\"", "]", "self", ".", "log", "(", "u\" Converting boundary indices to fragment list...\"", ")", "begin", "=", "real_wave_mfcc", ".", "middle_begin", "*", "real_wave_mfcc", ".", "rconf", ".", "mws", "end", "=", "real_wave_mfcc", ".", "middle_end", "*", "real_wave_mfcc", ".", "rconf", ".", "mws", "time_values", "=", "[", "begin", "]", "+", "list", "(", "boundary_indices", "*", "self", ".", "mws", ")", "+", "[", "end", "]", "self", ".", "intervals_to_fragment_list", "(", "text_file", "=", "text_file", ",", "time_values", "=", "time_values", ")", "self", ".", "log", "(", "u\" Converting boundary indices to fragment list... done\"", ")", "self", ".", "log", "(", "u\" Processing fragments with zero length...\"", ")", "self", ".", "_process_zero_length", "(", "nozero", ",", "allow_arbitrary_shift", ")", "self", ".", "log", "(", "u\" Processing fragments with zero length... done\"", ")", "self", ".", "log", "(", "u\" Processing nonspeech fragments...\"", ")", "self", ".", "_process_long_nonspeech", "(", "ns_min", ",", "ns_string", ",", "real_wave_mfcc", ")", "self", ".", "log", "(", "u\" Processing nonspeech fragments... done\"", ")", "self", ".", "log", "(", "u\" Adjusting...\"", ")", "ALGORITHM_MAP", "=", "{", "self", ".", "AFTERCURRENT", ":", "self", ".", "_adjust_aftercurrent", ",", "self", ".", "AUTO", ":", "self", ".", "_adjust_auto", ",", "self", ".", "BEFORENEXT", ":", "self", ".", "_adjust_beforenext", ",", "self", ".", "OFFSET", ":", "self", ".", "_adjust_offset", ",", "self", ".", "PERCENT", ":", "self", ".", "_adjust_percent", ",", "self", ".", "RATE", ":", "self", ".", "_adjust_rate", ",", "self", ".", "RATEAGGRESSIVE", ":", "self", ".", "_adjust_rate_aggressive", ",", "}", "ALGORITHM_MAP", "[", "algorithm", "]", "(", "real_wave_mfcc", ",", "algo_parameters", ")", "self", ".", "log", "(", "u\" Adjusting... done\"", ")", "self", ".", "log", "(", "u\" Smoothing...\"", ")", "self", ".", "_smooth_fragment_list", "(", "real_wave_mfcc", ".", "audio_length", ",", "ns_string", ")", "self", ".", "log", "(", "u\" Smoothing... done\"", ")", "return", "self", ".", "smflist" ]
Adjust the boundaries of the text map using the algorithm and parameters specified in the constructor, storing the sync map fragment list internally. :param dict aba_parameters: a dictionary containing the algorithm and its parameters, as produced by ``aba_parameters()`` in ``TaskConfiguration`` :param boundary_indices: the current boundary indices, with respect to the audio file full MFCCs :type boundary_indices: :class:`numpy.ndarray` (1D) :param real_wave_mfcc: the audio file MFCCs :type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC` :param text_file: the text file containing the text fragments associated :type text_file: :class:`~aeneas.textfile.TextFile` :param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length :rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList`
[ "Adjust", "the", "boundaries", "of", "the", "text", "map", "using", "the", "algorithm", "and", "parameters", "specified", "in", "the", "constructor", "storing", "the", "sync", "map", "fragment", "list", "internally", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L236-L310
232,296
readbeyond/aeneas
aeneas/adjustboundaryalgorithm.py
AdjustBoundaryAlgorithm.append_fragment_list_to_sync_root
def append_fragment_list_to_sync_root(self, sync_root): """ Append the sync map fragment list to the given node from a sync map tree. :param sync_root: the root of the sync map tree to which the new nodes should be appended :type sync_root: :class:`~aeneas.tree.Tree` """ if not isinstance(sync_root, Tree): self.log_exc(u"sync_root is not a Tree object", None, True, TypeError) self.log(u"Appending fragment list to sync root...") for fragment in self.smflist: sync_root.add_child(Tree(value=fragment)) self.log(u"Appending fragment list to sync root... done")
python
def append_fragment_list_to_sync_root(self, sync_root): """ Append the sync map fragment list to the given node from a sync map tree. :param sync_root: the root of the sync map tree to which the new nodes should be appended :type sync_root: :class:`~aeneas.tree.Tree` """ if not isinstance(sync_root, Tree): self.log_exc(u"sync_root is not a Tree object", None, True, TypeError) self.log(u"Appending fragment list to sync root...") for fragment in self.smflist: sync_root.add_child(Tree(value=fragment)) self.log(u"Appending fragment list to sync root... done")
[ "def", "append_fragment_list_to_sync_root", "(", "self", ",", "sync_root", ")", ":", "if", "not", "isinstance", "(", "sync_root", ",", "Tree", ")", ":", "self", ".", "log_exc", "(", "u\"sync_root is not a Tree object\"", ",", "None", ",", "True", ",", "TypeError", ")", "self", ".", "log", "(", "u\"Appending fragment list to sync root...\"", ")", "for", "fragment", "in", "self", ".", "smflist", ":", "sync_root", ".", "add_child", "(", "Tree", "(", "value", "=", "fragment", ")", ")", "self", ".", "log", "(", "u\"Appending fragment list to sync root... done\"", ")" ]
Append the sync map fragment list to the given node from a sync map tree. :param sync_root: the root of the sync map tree to which the new nodes should be appended :type sync_root: :class:`~aeneas.tree.Tree`
[ "Append", "the", "sync", "map", "fragment", "list", "to", "the", "given", "node", "from", "a", "sync", "map", "tree", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L387-L401
232,297
readbeyond/aeneas
aeneas/adjustboundaryalgorithm.py
AdjustBoundaryAlgorithm._process_zero_length
def _process_zero_length(self, nozero, allow_arbitrary_shift): """ If ``nozero`` is ``True``, modify the sync map fragment list so that no fragment will have zero length. """ self.log(u"Called _process_zero_length") if not nozero: self.log(u"Processing zero length intervals not requested: returning") return self.log(u"Processing zero length intervals requested") self.log(u" Checking and fixing...") duration = self.rconf[RuntimeConfiguration.ABA_NO_ZERO_DURATION] self.log([u" Requested no zero duration: %.3f", duration]) if not allow_arbitrary_shift: self.log(u" No arbitrary shift => taking max with mws") duration = self.rconf.mws.geq_multiple(duration) self.log([u" Actual no zero duration: %.3f", duration]) # ignore HEAD and TAIL max_index = len(self.smflist) - 1 self.smflist.fix_zero_length_fragments( duration=duration, min_index=1, max_index=max_index ) self.log(u" Checking and fixing... done") if self.smflist.has_zero_length_fragments(1, max_index): self.log_warn(u" The fragment list still has fragments with zero length") else: self.log(u" The fragment list does not have fragments with zero length")
python
def _process_zero_length(self, nozero, allow_arbitrary_shift): """ If ``nozero`` is ``True``, modify the sync map fragment list so that no fragment will have zero length. """ self.log(u"Called _process_zero_length") if not nozero: self.log(u"Processing zero length intervals not requested: returning") return self.log(u"Processing zero length intervals requested") self.log(u" Checking and fixing...") duration = self.rconf[RuntimeConfiguration.ABA_NO_ZERO_DURATION] self.log([u" Requested no zero duration: %.3f", duration]) if not allow_arbitrary_shift: self.log(u" No arbitrary shift => taking max with mws") duration = self.rconf.mws.geq_multiple(duration) self.log([u" Actual no zero duration: %.3f", duration]) # ignore HEAD and TAIL max_index = len(self.smflist) - 1 self.smflist.fix_zero_length_fragments( duration=duration, min_index=1, max_index=max_index ) self.log(u" Checking and fixing... done") if self.smflist.has_zero_length_fragments(1, max_index): self.log_warn(u" The fragment list still has fragments with zero length") else: self.log(u" The fragment list does not have fragments with zero length")
[ "def", "_process_zero_length", "(", "self", ",", "nozero", ",", "allow_arbitrary_shift", ")", ":", "self", ".", "log", "(", "u\"Called _process_zero_length\"", ")", "if", "not", "nozero", ":", "self", ".", "log", "(", "u\"Processing zero length intervals not requested: returning\"", ")", "return", "self", ".", "log", "(", "u\"Processing zero length intervals requested\"", ")", "self", ".", "log", "(", "u\" Checking and fixing...\"", ")", "duration", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "ABA_NO_ZERO_DURATION", "]", "self", ".", "log", "(", "[", "u\" Requested no zero duration: %.3f\"", ",", "duration", "]", ")", "if", "not", "allow_arbitrary_shift", ":", "self", ".", "log", "(", "u\" No arbitrary shift => taking max with mws\"", ")", "duration", "=", "self", ".", "rconf", ".", "mws", ".", "geq_multiple", "(", "duration", ")", "self", ".", "log", "(", "[", "u\" Actual no zero duration: %.3f\"", ",", "duration", "]", ")", "# ignore HEAD and TAIL", "max_index", "=", "len", "(", "self", ".", "smflist", ")", "-", "1", "self", ".", "smflist", ".", "fix_zero_length_fragments", "(", "duration", "=", "duration", ",", "min_index", "=", "1", ",", "max_index", "=", "max_index", ")", "self", ".", "log", "(", "u\" Checking and fixing... done\"", ")", "if", "self", ".", "smflist", ".", "has_zero_length_fragments", "(", "1", ",", "max_index", ")", ":", "self", ".", "log_warn", "(", "u\" The fragment list still has fragments with zero length\"", ")", "else", ":", "self", ".", "log", "(", "u\" The fragment list does not have fragments with zero length\"", ")" ]
If ``nozero`` is ``True``, modify the sync map fragment list so that no fragment will have zero length.
[ "If", "nozero", "is", "True", "modify", "the", "sync", "map", "fragment", "list", "so", "that", "no", "fragment", "will", "have", "zero", "length", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L407-L435
232,298
readbeyond/aeneas
pyinstaller-aeneas-cli.py
main
def main(): """ This is the aeneas-cli "hydra" script, to be compiled by pyinstaller. """ if FROZEN: HydraCLI(invoke="aeneas-cli").run( arguments=sys.argv, show_help=False ) else: HydraCLI(invoke="pyinstaller-aeneas-cli.py").run( arguments=sys.argv, show_help=False )
python
def main(): """ This is the aeneas-cli "hydra" script, to be compiled by pyinstaller. """ if FROZEN: HydraCLI(invoke="aeneas-cli").run( arguments=sys.argv, show_help=False ) else: HydraCLI(invoke="pyinstaller-aeneas-cli.py").run( arguments=sys.argv, show_help=False )
[ "def", "main", "(", ")", ":", "if", "FROZEN", ":", "HydraCLI", "(", "invoke", "=", "\"aeneas-cli\"", ")", ".", "run", "(", "arguments", "=", "sys", ".", "argv", ",", "show_help", "=", "False", ")", "else", ":", "HydraCLI", "(", "invoke", "=", "\"pyinstaller-aeneas-cli.py\"", ")", ".", "run", "(", "arguments", "=", "sys", ".", "argv", ",", "show_help", "=", "False", ")" ]
This is the aeneas-cli "hydra" script, to be compiled by pyinstaller.
[ "This", "is", "the", "aeneas", "-", "cli", "hydra", "script", "to", "be", "compiled", "by", "pyinstaller", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/pyinstaller-aeneas-cli.py#L48-L62
232,299
readbeyond/aeneas
aeneas/vad.py
VAD.run_vad
def run_vad( self, wave_energy, log_energy_threshold=None, min_nonspeech_length=None, extend_before=None, extend_after=None ): """ Compute the time intervals containing speech and nonspeech, and return a boolean mask with speech frames set to ``True``, and nonspeech frames set to ``False``. The last four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param wave_energy: the energy vector of the audio file (0-th MFCC) :type wave_energy: :class:`numpy.ndarray` (1D) :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after) :rtype: :class:`numpy.ndarray` (1D) """ self.log(u"Computing VAD for wave") mfcc_window_shift = self.rconf.mws self.log([u"MFCC window shift (s): %.3f", mfcc_window_shift]) if log_energy_threshold is None: log_energy_threshold = self.rconf[RuntimeConfiguration.VAD_LOG_ENERGY_THRESHOLD] self.log([u"Log energy threshold: %.3f", log_energy_threshold]) if min_nonspeech_length is None: min_nonspeech_length = int(self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH] / mfcc_window_shift) self.log([u"Min nonspeech length (s): %.3f", self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH]]) if extend_before is None: extend_before = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE] / mfcc_window_shift) self.log([u"Extend speech before (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE]]) if extend_after is None: extend_after = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER] / mfcc_window_shift) self.log([u"Extend speech after (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER]]) energy_length = len(wave_energy) energy_threshold = numpy.min(wave_energy) + log_energy_threshold self.log([u"Min nonspeech length (frames): %d", min_nonspeech_length]) self.log([u"Extend speech before (frames): %d", extend_before]) self.log([u"Extend speech after (frames): %d", extend_after]) self.log([u"Energy vector length (frames): %d", energy_length]) self.log([u"Energy threshold (log): %.3f", energy_threshold]) # using windows to be sure we have at least # min_nonspeech_length consecutive frames with nonspeech self.log(u"Determining initial labels...") mask = wave_energy >= energy_threshold windows = self._rolling_window(mask, min_nonspeech_length) nonspeech_runs = self._compute_runs((numpy.where(numpy.sum(windows, axis=1) == 0))[0]) self.log(u"Determining initial labels... done") # initially, everything is marked as speech # we remove the nonspeech intervals as needed, # possibly extending the adjacent speech interval # if requested by the user self.log(u"Determining final labels...") mask = numpy.ones(energy_length, dtype="bool") for ns in nonspeech_runs: start = ns[0] if (extend_after > 0) and (start > 0): start += extend_after stop = ns[-1] + min_nonspeech_length if (extend_before > 0) and (stop < energy_length - 1): stop -= extend_before mask[start:stop] = 0 self.log(u"Determining final labels... done") return mask
python
def run_vad( self, wave_energy, log_energy_threshold=None, min_nonspeech_length=None, extend_before=None, extend_after=None ): """ Compute the time intervals containing speech and nonspeech, and return a boolean mask with speech frames set to ``True``, and nonspeech frames set to ``False``. The last four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param wave_energy: the energy vector of the audio file (0-th MFCC) :type wave_energy: :class:`numpy.ndarray` (1D) :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after) :rtype: :class:`numpy.ndarray` (1D) """ self.log(u"Computing VAD for wave") mfcc_window_shift = self.rconf.mws self.log([u"MFCC window shift (s): %.3f", mfcc_window_shift]) if log_energy_threshold is None: log_energy_threshold = self.rconf[RuntimeConfiguration.VAD_LOG_ENERGY_THRESHOLD] self.log([u"Log energy threshold: %.3f", log_energy_threshold]) if min_nonspeech_length is None: min_nonspeech_length = int(self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH] / mfcc_window_shift) self.log([u"Min nonspeech length (s): %.3f", self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH]]) if extend_before is None: extend_before = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE] / mfcc_window_shift) self.log([u"Extend speech before (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE]]) if extend_after is None: extend_after = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER] / mfcc_window_shift) self.log([u"Extend speech after (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER]]) energy_length = len(wave_energy) energy_threshold = numpy.min(wave_energy) + log_energy_threshold self.log([u"Min nonspeech length (frames): %d", min_nonspeech_length]) self.log([u"Extend speech before (frames): %d", extend_before]) self.log([u"Extend speech after (frames): %d", extend_after]) self.log([u"Energy vector length (frames): %d", energy_length]) self.log([u"Energy threshold (log): %.3f", energy_threshold]) # using windows to be sure we have at least # min_nonspeech_length consecutive frames with nonspeech self.log(u"Determining initial labels...") mask = wave_energy >= energy_threshold windows = self._rolling_window(mask, min_nonspeech_length) nonspeech_runs = self._compute_runs((numpy.where(numpy.sum(windows, axis=1) == 0))[0]) self.log(u"Determining initial labels... done") # initially, everything is marked as speech # we remove the nonspeech intervals as needed, # possibly extending the adjacent speech interval # if requested by the user self.log(u"Determining final labels...") mask = numpy.ones(energy_length, dtype="bool") for ns in nonspeech_runs: start = ns[0] if (extend_after > 0) and (start > 0): start += extend_after stop = ns[-1] + min_nonspeech_length if (extend_before > 0) and (stop < energy_length - 1): stop -= extend_before mask[start:stop] = 0 self.log(u"Determining final labels... done") return mask
[ "def", "run_vad", "(", "self", ",", "wave_energy", ",", "log_energy_threshold", "=", "None", ",", "min_nonspeech_length", "=", "None", ",", "extend_before", "=", "None", ",", "extend_after", "=", "None", ")", ":", "self", ".", "log", "(", "u\"Computing VAD for wave\"", ")", "mfcc_window_shift", "=", "self", ".", "rconf", ".", "mws", "self", ".", "log", "(", "[", "u\"MFCC window shift (s): %.3f\"", ",", "mfcc_window_shift", "]", ")", "if", "log_energy_threshold", "is", "None", ":", "log_energy_threshold", "=", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_LOG_ENERGY_THRESHOLD", "]", "self", ".", "log", "(", "[", "u\"Log energy threshold: %.3f\"", ",", "log_energy_threshold", "]", ")", "if", "min_nonspeech_length", "is", "None", ":", "min_nonspeech_length", "=", "int", "(", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_MIN_NONSPEECH_LENGTH", "]", "/", "mfcc_window_shift", ")", "self", ".", "log", "(", "[", "u\"Min nonspeech length (s): %.3f\"", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_MIN_NONSPEECH_LENGTH", "]", "]", ")", "if", "extend_before", "is", "None", ":", "extend_before", "=", "int", "(", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_EXTEND_SPEECH_INTERVAL_BEFORE", "]", "/", "mfcc_window_shift", ")", "self", ".", "log", "(", "[", "u\"Extend speech before (s): %.3f\"", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_EXTEND_SPEECH_INTERVAL_BEFORE", "]", "]", ")", "if", "extend_after", "is", "None", ":", "extend_after", "=", "int", "(", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_EXTEND_SPEECH_INTERVAL_AFTER", "]", "/", "mfcc_window_shift", ")", "self", ".", "log", "(", "[", "u\"Extend speech after (s): %.3f\"", ",", "self", ".", "rconf", "[", "RuntimeConfiguration", ".", "VAD_EXTEND_SPEECH_INTERVAL_AFTER", "]", "]", ")", "energy_length", "=", "len", "(", "wave_energy", ")", "energy_threshold", "=", "numpy", ".", "min", "(", "wave_energy", ")", "+", "log_energy_threshold", "self", ".", "log", "(", "[", "u\"Min nonspeech length (frames): %d\"", ",", "min_nonspeech_length", "]", ")", "self", ".", "log", "(", "[", "u\"Extend speech before (frames): %d\"", ",", "extend_before", "]", ")", "self", ".", "log", "(", "[", "u\"Extend speech after (frames): %d\"", ",", "extend_after", "]", ")", "self", ".", "log", "(", "[", "u\"Energy vector length (frames): %d\"", ",", "energy_length", "]", ")", "self", ".", "log", "(", "[", "u\"Energy threshold (log): %.3f\"", ",", "energy_threshold", "]", ")", "# using windows to be sure we have at least", "# min_nonspeech_length consecutive frames with nonspeech", "self", ".", "log", "(", "u\"Determining initial labels...\"", ")", "mask", "=", "wave_energy", ">=", "energy_threshold", "windows", "=", "self", ".", "_rolling_window", "(", "mask", ",", "min_nonspeech_length", ")", "nonspeech_runs", "=", "self", ".", "_compute_runs", "(", "(", "numpy", ".", "where", "(", "numpy", ".", "sum", "(", "windows", ",", "axis", "=", "1", ")", "==", "0", ")", ")", "[", "0", "]", ")", "self", ".", "log", "(", "u\"Determining initial labels... done\"", ")", "# initially, everything is marked as speech", "# we remove the nonspeech intervals as needed,", "# possibly extending the adjacent speech interval", "# if requested by the user", "self", ".", "log", "(", "u\"Determining final labels...\"", ")", "mask", "=", "numpy", ".", "ones", "(", "energy_length", ",", "dtype", "=", "\"bool\"", ")", "for", "ns", "in", "nonspeech_runs", ":", "start", "=", "ns", "[", "0", "]", "if", "(", "extend_after", ">", "0", ")", "and", "(", "start", ">", "0", ")", ":", "start", "+=", "extend_after", "stop", "=", "ns", "[", "-", "1", "]", "+", "min_nonspeech_length", "if", "(", "extend_before", ">", "0", ")", "and", "(", "stop", "<", "energy_length", "-", "1", ")", ":", "stop", "-=", "extend_before", "mask", "[", "start", ":", "stop", "]", "=", "0", "self", ".", "log", "(", "u\"Determining final labels... done\"", ")", "return", "mask" ]
Compute the time intervals containing speech and nonspeech, and return a boolean mask with speech frames set to ``True``, and nonspeech frames set to ``False``. The last four parameters might be ``None``: in this case, the corresponding RuntimeConfiguration values are applied. :param wave_energy: the energy vector of the audio file (0-th MFCC) :type wave_energy: :class:`numpy.ndarray` (1D) :param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech :param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval :param int extend_before: extend each speech interval by this number of frames to the left (before) :param int extend_after: extend each speech interval by this number of frames to the right (after) :rtype: :class:`numpy.ndarray` (1D)
[ "Compute", "the", "time", "intervals", "containing", "speech", "and", "nonspeech", "and", "return", "a", "boolean", "mask", "with", "speech", "frames", "set", "to", "True", "and", "nonspeech", "frames", "set", "to", "False", "." ]
9d95535ad63eef4a98530cfdff033b8c35315ee1
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L60-L131