INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields of ``node``.
:param node: the child node to be adde... | def add_child(self, node, as_last=True):
"""
Add the given child to the current list of children.
The new child is appended as the last child if ``as_last``
is ``True``, or as the first child if ``as_last`` is ``False``.
This call updates the ``__parent`` and ``__level`` fields... |
Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed | def remove_child(self, index):
"""
Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed
"""
if index < 0:
index = index + len(self)
self.__children = self.__children[0:index] + s... |
Remove this node from the list of children of its current parent,
if the current parent is not ``None``, otherwise do nothing.
.. versionadded:: 1.7.0 | def remove(self):
"""
Remove this node from the list of children of its current parent,
if the current parent is not ``None``, otherwise do nothing.
.. versionadded:: 1.7.0
"""
if self.parent is not None:
for i, child in enumerate(self.parent.children):
... |
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children | def remove_children(self, reset_parent=True):
"""
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
"""
if reset_parent:
for child in self.children:
... |
Return the list of leaves not empty
in the tree rooted at this node,
in DFS order.
:rtype: list of :class:`~aeneas.tree.Tree` | 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))] |
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 | 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
"""... |
Depth-first search of the tree rooted at this node.
(First visit children, then visit current node.)
:rtype: generator of :class:`~aeneas.tree.Tree` | def dfs(self):
"""
Depth-first search of the tree rooted at this node.
(First visit children, then visit current node.)
:rtype: generator of :class:`~aeneas.tree.Tree`
"""
for node in self.children:
for v in node.dfs:
yield v
yield sel... |
Pre-order search of the tree rooted at this node.
(First visit current node, then visit children.)
:rtype: generator of :class:`~aeneas.tree.Tree` | def pre(self):
"""
Pre-order search of the tree rooted at this node.
(First visit current node, then visit children.)
:rtype: generator of :class:`~aeneas.tree.Tree`
"""
yield self
for node in self.children:
for v in node.pre:
yield v |
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` | 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)]
... |
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 | 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, in... |
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: ValueErro... | 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 ``i... |
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 ... | 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 ... |
Return the 'legacy' not-quite-DCT matrix used by Sphinx | 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'))
melco... |
Convert log-power-spectrum bins to MFCC using the 'legacy'
Sphinx transform | 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 |
Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra. | def dctmat(N,K,freqstep,orthogonalize=True):
"""Return the orthogonal DCT-II/DCT-III matrix of size NxK.
For computing or inverting MFCCs, N is the number of
log-power-spectrum bins while K is the number of cepstra."""
cosmat = numpy.zeros((N, K), 'double')
for n in range(0,N):
for k in rang... |
Convert log-power-spectrum to MFCC using the orthogonal DCT-II | 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) |
Convert log-power-spectrum to MFCC using the normalized DCT-II | 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) |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
input_file_path = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... |
The audio audio_samples, that is, an array of ``float64`` values,
each representing an audio sample in ``[-1.0, 1.0]``.
Note that this function returns a view into the
first ``self.__samples_length`` elements of ``self.__samples``.
If you want to clone the values,
you must use e... | def audio_samples(self):
"""
The audio audio_samples, that is, an array of ``float64`` values,
each representing an audio sample in ``[-1.0, 1.0]``.
Note that this function returns a view into the
first ``self.__samples_length`` elements of ``self.__samples``.
If you wan... |
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 ``ffprob... | 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.Au... |
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... | 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 wil... |
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 ca... | 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`` z... |
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 | 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
"""
... |
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
... | 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.
... |
Reverse the audio data.
:raises: :class:`~aeneas.audiofile.AudioFileNotInitializedError`: if the audio file is not initialized yet
.. versionadded:: 1.2.0 | 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.l... |
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 secon... | 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.exacttim... |
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 | 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 initial... |
Clear the audio data, freeing memory. | 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 |
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``. | 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... |
Download an audio stream from a YouTube video,
and save it to file.
If ``download`` is ``False``, return the list
of available audiostreams but do not download.
Otherwise, download the audio stream best matching
the provided parameters, as follows.
If ``download_format`... | def audio_from_youtube(
self,
source_url,
download=True,
output_file_path=None,
download_format=None,
largest_audio=True,
):
"""
Download an audio stream from a YouTube video,
and save it to file.
If ``download`... |
Return the MFCC speech frames
in the MIDDLE portion of the wave.
:rtype: :class:`numpy.ndarray` (2D) | 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] |
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) | 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._... |
Return the begin and end indices w.r.t. ``self.__mfcc_mask_map``,
corresponding to indices in the MIDDLE portion of the wave,
that is, which fall between ``self.__middle_begin`` and
``self.__middle_end`` in ``self.__mfcc``.
:rtype: (int, int) | def _masked_middle_begin_end(self):
"""
Return the begin and end indices w.r.t. ``self.__mfcc_mask_map``,
corresponding to indices in the MIDDLE portion of the wave,
that is, which fall between ``self.__middle_begin`` and
``self.__middle_end`` in ``self.__mfcc``.
:rtype:... |
Return a list of intervals::
[(b_1, e_1), (b_2, e_2), ..., (b_k, e_k)]
where ``b_i`` is the time when the ``i``-th interval begins,
and ``e_i`` is the time when it ends.
:param bool speech: if ``True``, return speech intervals,
otherwise return nonspeech in... | def intervals(self, speech=True, time=True):
"""
Return a list of intervals::
[(b_1, e_1), (b_2, e_2), ..., (b_k, e_k)]
where ``b_i`` is the time when the ``i``-th interval begins,
and ``e_i`` is the time when it ends.
:param bool speech: if ``True``, return speech int... |
If ``index`` is contained in a nonspeech interval,
return a pair ``(interval_begin, interval_end)``
such that ``interval_begin <= index < interval_end``,
i.e., ``interval_end`` is assumed not to be included.
Otherwise, return ``None``.
:rtype: ``None`` or tuple | def inside_nonspeech(self, index):
"""
If ``index`` is contained in a nonspeech interval,
return a pair ``(interval_begin, interval_end)``
such that ``interval_begin <= index < interval_end``,
i.e., ``interval_end`` is assumed not to be included.
Otherwise, return ``None... |
Binary search for the interval containing index,
assuming there is such an interval.
This function should never return ``None``. | 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:
... |
Set the index where MIDDLE starts.
:param int index: the new index for 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 |
Set the index (+1) where MIDDLE ends.
:param int index: the new index for MIDDLE end | def middle_end(self, index):
"""
Set the index (+1) where MIDDLE ends.
:param int index: the new index for MIDDLE end
"""
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_end = index |
Compute MFCCs using the Python C extension cmfcc. | 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")... |
Compute MFCCs using the pure Python code. | 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(... |
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. | 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_... |
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 thresh... | 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 mig... |
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.exa... | 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.... |
Return the number of characters of the text fragment,
not including the line separators.
:rtype: int | 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]) |
Return the direct not empty children of the root of the fragments tree,
as ``TextFile`` objects.
:rtype: list of :class:`~aeneas.textfile.TextFile` | 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:
... |
The number of characters in this text file.
:rtype: int | 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 |
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 | 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: ... |
Return a new :class:`~aeneas.textfile.TextFile` object,
rooted at the given node ``root``.
:param root: the root node
:type root: :class:`~aeneas.tree.Tree`
:rtype: :class:`~aeneas.textfile.TextFile` | def get_subtree(self, root):
"""
Return a new :class:`~aeneas.textfile.TextFile` object,
rooted at the given node ``root``.
:param root: the root node
:type root: :class:`~aeneas.tree.Tree`
:rtype: :class:`~aeneas.textfile.TextFile`
"""
if not isinstance... |
Return a new list of text fragments,
indexed from start (included) to end (excluded).
:param int start: the start index, included
:param int end: the end index, excluded
:rtype: :class:`~aeneas.textfile.TextFile` | def get_slice(self, start=None, end=None):
"""
Return a new list of text fragments,
indexed from start (included) to end (excluded).
:param int start: the start index, included
:param int end: the end index, excluded
:rtype: :class:`~aeneas.textfile.TextFile`
"""... |
Set the given language for all the text fragments.
:param language: the language of the text fragments
:type language: :class:`~aeneas.language.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 se... |
Read text fragments from a given list of tuples::
[(id_1, text_1), (id_2, text_2), ..., (id_n, text_n)].
:param list lines: the list of ``[id, text]`` fragments (see above) | def read_from_list_with_ids(self, lines):
"""
Read text fragments from a given list of tuples::
[(id_1, text_1), (id_2, text_2), ..., (id_n, text_n)].
:param list lines: the list of ``[id, text]`` fragments (see above)
"""
self.log(u"Reading text fragments from list... |
Read text fragments 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 Tex... |
Get the word separator to split words in mplain format.
:rtype: string | 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"):
... |
Read text fragments from a multilevel format text file.
:param list lines: the lines of the subtitles text file | 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.lo... |
Read text fragments from an munparsed format text file.
:param list lines: the lines of the unparsed text file | def _read_munparsed(self, lines):
"""
Read text fragments from an munparsed format text file.
:param list lines: the lines of the unparsed text file
"""
from bs4 import BeautifulSoup
def nodes_at_level(root, level):
""" Return a dict with the bs4 filter para... |
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 | 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... |
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) | 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.l... |
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 | 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: ... |
Read text fragments from an unparsed format text file.
:param list lines: the lines of the unparsed text file | 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 """... |
Return the id regex from the parameters | 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
... |
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]) | 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()
... |
Build a suitable TextFilter object. | 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,
... |
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 | 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... |
Apply the text filter filter to the given list of strings.
:param list strings: the list of input strings | 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... |
Apply filter to single string | def _apply_single(self, string):
""" Apply filter to single string """
if string is None:
return None
result = self.regex.sub("", string)
result = self.SPACES_REGEX.sub(" ", result).strip()
return result |
Apply filter to single string | def _apply_single(self, string):
""" Apply filter to single string """
if string is None:
return None
result = self.trans_map.transliterate(string)
result = self.SPACES_REGEX.sub(u" ", result).strip()
return result |
Read the map file at path. | 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,... |
Process the line string containing a 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... |
Process the first group of a rule. | 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... |
Process the second group of a (replace) rule. | def _process_second_group(self, group):
"""
Process the second group of a (replace) rule.
"""
def _replace_codepoint(match):
"""
Replace the matched Unicode hex code
with the corresponding unicode character
"""
result = self._ma... |
Parse the given string, either a Unicode character or ``U+....``,
and return the corresponding Unicode code point as int. | def _parse_codepoint(self, string):
"""
Parse the given string, either a Unicode character or ``U+....``,
and return the corresponding Unicode code point as int.
"""
if len(string) > 1:
match = self.CODEPOINT_REGEX.match(string)
return self._match_to_int(m... |
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` | 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 n... |
Load the job from the given :class:`aeneas.container.Container` object.
If ``config_string`` is ``None``,
the container must contain a configuration file;
otherwise use the provided config string
(i.e., the wizard case).
:param string container_path: the path to the input conta... | def load_job_from_container(self, container_path, config_string=None):
"""
Load the job from the given :class:`aeneas.container.Container` object.
If ``config_string`` is ``None``,
the container must contain a configuration file;
otherwise use the provided config string
... |
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 | 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
"""
... |
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
... | 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_di... |
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 ... | 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
... |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
# if no actual arguments, print help
if len(self.actual_arguments) < 1:
return self.print_help(short=True)
# check if we have a recognized tool switc... |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
input_file_path = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... |
Read labels from a 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.fragmen... |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 1:
return self.print_help()
audio_file_path = self.actual_arguments[0]
if not self.check_input_file(audio_file_path):... |
The current list of sync map fragments
which are (the values of) the leaves
of the sync map tree.
:rtype: list of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
.. versionadded:: 1.7.0 | def leaves(self, fragment_type=None):
"""
The current list of sync map fragments
which are (the values of) the leaves
of the sync map tree.
:rtype: list of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
.. versionadded:: 1.7.0
"""
leaves = self.fragme... |
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 | 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):
... |
Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
(except for HEAD and TAIL leaves)
are all consistent, that is,
their intervals do not overlap in forbidden ways.
:rtype: bool
.. versionadded:: 1.7.0 | def leaves_are_consistent(self):
"""
Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
(except for HEAD and TAIL leaves)
are all consistent, that is,
their intervals do not overlap in forbidden ways.
:rtype: bool
.. vers... |
Return a JSON representation of the sync map.
:rtype: string
.. versionadded:: 1.3.1 | 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.childre... |
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 p... | 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`
... |
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 | 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 o... |
Read sync map fragments from the given file in the specified format,
and add them the current (this) sync map.
Return ``True`` if the call succeeded,
``False`` if an error occurred.
:param sync_map_format: the format of the sync map
:type sync_map_format: :class:`~aeneas.syncm... | def read(self, sync_map_format, input_file_path, parameters=None):
"""
Read sync map fragments from the given file in the specified format,
and add them the current (this) sync map.
Return ``True`` if the call succeeded,
``False`` if an error occurred.
:param sync_map_f... |
Write the current sync map to file in the requested format.
Return ``True`` if the call succeeded,
``False`` if an error occurred.
:param sync_map_format: the format of the sync map
:type sync_map_format: :class:`~aeneas.syncmap.SyncMapFormat`
:param string output_file_path: t... | def write(self, sync_map_format, output_file_path, parameters=None):
"""
Write the current sync map to file in the requested format.
Return ``True`` if the call succeeded,
``False`` if an error occurred.
:param sync_map_format: the format of the sync map
:type sync_map... |
Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```. | 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.fi... |
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`. | 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`.
... |
Pre-emphasize the entire signal at once by self.emphasis_factor,
overwriting ``self.data``. | 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]) |
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)
:para... | 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... |
Return the sample rate (in samples/sec) and data from a WAV file
Parameters
----------
filename : string or open file handle
Input wav file.
mmap : bool, optional
Whether to read data as memory mapped.
Only to be used on real files (Default: False)
.. versionadded:: 0.1... | def read(filename, mmap=False):
"""
Return the sample rate (in samples/sec) and data from a WAV file
Parameters
----------
filename : string or open file handle
Input wav file.
mmap : bool, optional
Whether to read data as memory mapped.
Only to be used on real files (De... |
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... | 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-typ... |
Perform command and return the appropriate exit code.
:rtype: int | def perform_command(self):
"""
Perform command and return the appropriate exit code.
:rtype: int
"""
if len(self.actual_arguments) < 2:
return self.print_help()
input_file_path = self.actual_arguments[0]
output_file_path = self.actual_arguments[1]
... |
Safely print a given Unicode string to stdout,
possibly replacing characters non-printable
in the current stdout encoding.
:param string msg: the message | 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... |
Print an error message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | 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)) |
Print a success message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | 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)) |
Print a warning message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | 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" % (m... |
Return a (handler, path) tuple
for a temporary file with given suffix created by ``tempfile``.
:param string suffix: the suffix (e.g., the extension) of the file
:param string root: path to the root temporary directory;
if ``None``, the default temporary directory
... | def tmp_file(suffix=u"", root=None):
"""
Return a (handler, path) tuple
for a temporary file with given suffix created by ``tempfile``.
:param string suffix: the suffix (e.g., the extension) of the file
:param string root: path to the root temporary directory;
if ``None``, t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.