INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Return the file extension.
Examples: ::
/foo/bar.baz => baz
None => None
:param string path: the file path
:rtype: string | 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.startsw... |
Return a mimetype from the file extension.
:param string path: the file path
:rtype: string | 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.M... |
Return the file name without extension.
Examples: ::
/foo/bar.baz => bar
/foo/bar => bar
None => None
:param string path: the file path
:rtype: string | 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... |
Return a string representing the current date and time,
in ``YYYY-MM-DDThh:mm:ss`` or ``YYYY-MM-DDThh:mm:ss+hh:mm`` format
:param boolean time_zone: if ``True``, add the time zone offset.
:rtype: string | def datetime_string(time_zone=False):
"""
Return a string representing the current date and time,
in ``YYYY-MM-DDThh:mm:ss`` or ``YYYY-MM-DDThh:mm:ss+hh:mm`` format
:param boolean time_zone: if ``True``, add the time zone offset.
:rtype: string
"""
time = datetime.datetime.now()
templa... |
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 | 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:
v... |
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 | 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)
i... |
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``;
... | 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
:par... |
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 | 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... |
Convert the contents of a TXT config file
into the corresponding configuration string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
Leading and trailing blank characters will be stripped
and empty lines (after stripping) will be ignored.
:param string string: the contents of a TXT config f... | def config_txt_to_string(string):
"""
Convert the contents of a TXT config file
into the corresponding configuration string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
Leading and trailing blank characters will be stripped
and empty lines (after stripping) will be ignored.
:param... |
Convert a given configuration string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
:param string string: the configuration string
:rtype... | def config_string_to_dict(string, result=None):
"""
Convert a given configuration string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
... |
Convert the contents of a XML config file
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
:param bytes contents: the XML configuration contents
:param bool parse_job: if ``True``, parse the job pro... | def config_xml_to_dict(contents, result, parse_job=True):
"""
Convert the contents of a XML config file
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
:param bytes contents: the XML configurat... |
Convert a given config dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
into the corresponding string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
:param dict dictionary: the config dictionary
:rtype: string | def config_dict_to_string(dictionary):
"""
Convert a given config dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
into the corresponding string ::
key_1=value_1|key_2=value_2|...|key_n=value_n
:param dict d... |
Convert a given list of ``key=value`` strings ::
["key_1=value_1", "key_2=value_2", ..., "key_n=value_n"]
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] = value_n
:param list pairs: the list of key=va... | def pairs_to_dict(pairs, result=None):
"""
Convert a given list of ``key=value`` strings ::
["key_1=value_1", "key_2=value_2", ..., "key_n=value_n"]
into the corresponding dictionary ::
dictionary[key_1] = value_1
dictionary[key_2] = value_2
...
dictionary[key_n] =... |
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 fo... | 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 `... |
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 | 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
:raise... |
Parse the given ``HH:MM:SS.mmm`` string and return a time value.
:param string string: the string to be parsed
:param string decimal_separator: the decimal separator to be used
:rtype: :class:`~aeneas.exacttiming.TimeValue` | def time_from_hhmmssmmm(string, decimal_separator="."):
"""
Parse the given ``HH:MM:SS.mmm`` string and return a time value.
:param string string: the string to be parsed
:param string decimal_separator: the decimal separator to be used
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if ... |
Format the given time value into a ``HH:MM:SS.mmm`` string.
Examples: ::
12 => 00:00:12.000
12.345 => 00:00:12.345
12.345432 => 00:00:12.345
12.345678 => 00:00:12.346
83 => 00:01:23.000
83.456 => 00:01:23.456
83.456789 => 00:01:23.456
... | def time_to_hhmmssmmm(time_value, decimal_separator="."):
"""
Format the given time value into a ``HH:MM:SS.mmm`` string.
Examples: ::
12 => 00:00:12.000
12.345 => 00:00:12.345
12.345432 => 00:00:12.345
12.345678 => 00:00:12.346
83 => 00:01:23.000
... |
Split the given URL ``base#anchor`` into ``(base, anchor)``,
or ``(base, None)`` if no anchor is present.
In case there are two or more ``#`` characters,
return only the first two tokens: ``a#b#c => (a, b)``.
:param string url: the url
:rtype: list of str | def split_url(url):
"""
Split the given URL ``base#anchor`` into ``(base, anchor)``,
or ``(base, None)`` if no anchor is present.
In case there are two or more ``#`` characters,
return only the first two tokens: ``a#b#c => (a, b)``.
:param string url: the url
:rtype: list of str
"""
... |
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_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
... |
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 p... | 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 fun... |
Return ``True`` if the file at the given ``path`` can be read.
:param string path: the file path
:rtype: bool
.. versionadded:: 1.4.0 | 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
r... |
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 | 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 ther... |
Return the relative path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
The returned path is relative to the current working directory.
If ``path`` is ``None``, return ``... | def relative_path(path, from_file):
"""
Return the relative path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
The returned path is relative to the current working di... |
Return the absolute path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
If ``path`` is ``None``, return ``None``.
Example: ::
path="res/foo.bar"
from_fil... | def absolute_path(path, from_file):
"""
Return the absolute path of a file or directory, specified
as ``path`` relative to (the parent directory of) ``from_file``.
This method is intented to be called with ``__file__``
as second argument.
If ``path`` is ``None``, return ``None``.
Example:... |
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 | 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") ... |
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 | 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 ["",... |
Safely return a Unicode string of length one,
containing the Unicode character with given codepoint.
:param int codepoint: the codepoint
:rtype: string | 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:... |
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 | 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
"""
... |
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()
mode = self.actual_arguments[0]
validator = Validator(rconf=self.rconf, logger=self.logge... |
Add the given ``(key, value)`` pair to the cache.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:param file_info: the path value
:type file_info: tuple ``(handler, path)``
:raises: ValueError if the key is already present in the cach... | def add(self, fragment_info, file_info):
"""
Add the given ``(key, value)`` pair to the cache.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:param file_info: the path value
:type file_info: tuple ``(handler, path)``
... |
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 | 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_i... |
Clear the cache and remove all the files from disk. | 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)
s... |
Clear the TTS cache, removing all cache files from disk.
.. versionadded:: 1.6.0 | 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() |
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 wi... | 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
``_synt... |
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... | 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 la... |
Synthesize multiple fragments via ``subprocess``.
:rtype: tuple (result, (anchors, current_time, num_chars)) | 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...")
... |
Synthesize multiple fragments via a Python call.
:rtype: tuple (result, (anchors, current_time, num_chars)) | 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...")
... |
This is an helper function to synthesize a single text fragment via ``subprocess``.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
If ``return_audio_data`` is ``True``,
return the audio data at the end of the function call;
... | def _synthesize_single_subprocess_helper(self, text, voice_code, output_file_path=None, return_audio_data=True):
"""
This is an helper function to synthesize a single text fragment via ``subprocess``.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the en... |
Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception | 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
... |
Synthesize multiple fragments, generic function.
The ``helper_function`` is a function that takes parameters
``(text, voice_code, output_file_path)``
and returns a tuple
``(result, (audio_length, audio_sample_rate, audio_format, audio_samples))``.
:rtype: tuple (result, (anchor... | def _synthesize_multiple_generic(self, helper_function, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple fragments, generic function.
The ``helper_function`` is a function that takes parameters
``(text, voice_code, output_file_path)``
and r... |
Synthesize all fragments without using the 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)
... |
Synthesize all fragments using the 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"Frag... |
Sort the given list of identifiers,
returning a new (sorted) list.
:param list ids: the list of identifiers to be sorted
:rtype: list | def sort(self, ids):
"""
Sort the given list of identifiers,
returning a new (sorted) list.
:param list ids: the list of identifiers to be sorted
:rtype: list
"""
def extract_int(string):
"""
Extract an integer from the given string.
... |
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 ... | 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... |
Transform a list of at least 4 time values
(corresponding to at least 3 intervals)
into a sync map fragment list and store it internally.
The first interval is a HEAD, the last is a TAIL.
For example:
time_values=[0.000, 1.000, 2.000, 3.456] => [(0.000, 1.000), (1.000, 2.00... | def intervals_to_fragment_list(self, text_file, time_values):
"""
Transform a list of at least 4 time values
(corresponding to at least 3 intervals)
into a sync map fragment list and store it internally.
The first interval is a HEAD, the last is a TAIL.
For example:
... |
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` | 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 ``nozero`` is ``True``, modify the sync map fragment list
so that no fragment will have 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 le... |
Remove NONSPEECH fragments from list if needed,
and set HEAD/TAIL begin/end. | def _smooth_fragment_list(self, real_wave_mfcc_audio_length, ns_string):
"""
Remove NONSPEECH fragments from list if needed,
and set HEAD/TAIL begin/end.
"""
self.log(u"Called _smooth_fragment_list")
self.smflist[0].begin = TimeValue("0.000")
self.smflist[-1].end ... |
AUTO (do not modify) | def _adjust_auto(self, real_wave_mfcc, algo_parameters):
"""
AUTO (do not modify)
"""
self.log(u"Called _adjust_auto")
self.log(u"Nothing to do, return unchanged") |
OFFSET | def _adjust_offset(self, real_wave_mfcc, algo_parameters):
"""
OFFSET
"""
self.log(u"Called _adjust_offset")
self._apply_offset(offset=algo_parameters[0]) |
PERCENT | def _adjust_percent(self, real_wave_mfcc, algo_parameters):
"""
PERCENT
"""
def new_time(nsi):
"""
The new boundary time value is ``percent``
of the nonspeech interval ``nsi``.
"""
percent = Decimal(algo_parameters[0])
... |
AFTERCURRENT | def _adjust_aftercurrent(self, real_wave_mfcc, algo_parameters):
"""
AFTERCURRENT
"""
def new_time(nsi):
"""
The new boundary time value is ``delay`` after
the begin of the nonspeech interval ``nsi``.
If ``nsi`` has length less than ``delay... |
BEFORENEXT | def _adjust_beforenext(self, real_wave_mfcc, algo_parameters):
"""
BEFORENEXT
"""
def new_time(nsi):
"""
The new boundary time value is ``delay`` before
the end of the nonspeech interval ``nsi``.
If ``nsi`` has length less than ``delay``,
... |
RATE | def _adjust_rate(self, real_wave_mfcc, algo_parameters):
"""
RATE
"""
self.log(u"Called _adjust_rate")
self._apply_rate(max_rate=algo_parameters[0], aggressive=False) |
RATEAGGRESSIVE | def _adjust_rate_aggressive(self, real_wave_mfcc, algo_parameters):
"""
RATEAGGRESSIVE
"""
self.log(u"Called _adjust_rate_aggressive")
self._apply_rate(max_rate=algo_parameters[0], aggressive=True) |
Apply the given offset (negative, zero, or positive)
to all time intervals.
:param offset: the offset, in seconds
:type offset: :class:`~aeneas.exacttiming.TimeValue` | def _apply_offset(self, offset):
"""
Apply the given offset (negative, zero, or positive)
to all time intervals.
:param offset: the offset, in seconds
:type offset: :class:`~aeneas.exacttiming.TimeValue`
"""
if not isinstance(offset, TimeValue):
self... |
Apply the adjust function to each boundary point
falling inside (extrema included) of a nonspeech interval.
The adjust function is not applied to a boundary index
if there are two or more boundary indices falling
inside the same nonspeech interval.
The adjust function is not ap... | def _adjust_on_nonspeech(self, real_wave_mfcc, adjust_function):
"""
Apply the adjust function to each boundary point
falling inside (extrema included) of a nonspeech interval.
The adjust function is not applied to a boundary index
if there are two or more boundary indices falli... |
Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
the faster current one.
If ``aggressive`` is ``True``,
... | def _apply_rate(self, max_rate, aggressive=False):
"""
Try to adjust the rate (characters/second)
of the fragments of the list,
so that it does not exceed the given ``max_rate``.
This is done by testing whether some slack
can be borrowed from the fragment before
... |
This is the aeneas-cli "hydra" script,
to be compiled by pyinstaller. | 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(
argume... |
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.
... | 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 `... |
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays | def _compute_runs(self, array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays
"""
if len(array) < 1:
return []
... |
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D ... | def _rolling_window(self, array, size):
"""
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param ... |
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]
try:
audiofile = AudioFile(audio_f... |
Returns the name of a distutils build directory
see: http://stackoverflow.com/questions/14320220/
testing-python-c-libraries-get-build-path | def distutils_dir_name(dname):
"""Returns the name of a distutils build directory
see: http://stackoverflow.com/questions/14320220/
testing-python-c-libraries-get-build-path
"""
f = "{dirname}.{platform}-{version[0]}.{version[1]}"
return f.format(dirname=dname,
pla... |
return the samtools usage information for this command | def usage(self):
'''return the samtools usage information for this command'''
retval, stderr, stdout = _pysam_dispatch(
self.collection,
self.dispatch,
is_usage=True,
catch_stdout=True)
# some tools write usage to stderr, such as mpileup
if... |
iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates | def iterate(infile):
'''iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coord... |
translate indel from vcf to pileup format. | def translateIndelGenotypeFromVCF(vcf_genotypes, ref):
'''translate indel from vcf to pileup format.'''
# indels
def getPrefix(s1, s2):
'''get common prefix of strings s1 and s2.'''
n = min(len(s1), len(s2))
for x in range(n):
if s1[x] != s2[x]:
return s1... |
convert vcf record to pileup record. | def vcf2pileup(vcf, sample):
'''convert vcf record to pileup record.'''
chromosome = vcf.contig
pos = vcf.pos
reference = vcf.ref
allelles = [reference] + vcf.alt
data = vcf[sample]
# get genotype
genotypes = data["GT"]
if len(genotypes) > 1:
raise ValueError("only single ... |
iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support sa... | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This... |
update pysam files applying redirection of ouput | def _update_pysam_files(cf, destdir):
'''update pysam files applying redirection of ouput'''
basename = os.path.basename(destdir)
for filename in cf:
if not filename:
continue
dest = filename + ".pysam.c"
with open(filename, encoding="utf-8") as infile:
lines ... |
return a list of include directories. | def get_include():
'''return a list of include directories.'''
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
#
# Header files may be stored in different relative locations
# depending on installation mode (e.g., `python setup.py install`,
# `python setup.py develop`. The fi... |
return a list of libraries to link against. | def get_libraries():
'''return a list of libraries to link against.'''
# Note that this list does not include libcsamtools.so as there are
# numerous name conflicts with libchtslib.so.
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
pysam_libs = ['libctabixproxies',
... |
Add given node to the graph.
@attention: While nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type node: node
@param node: Node identifier.
@type attrs: list
... | def add_node(self, node, attrs = None):
"""
Add given node to the graph.
@attention: While nodes can be of any type, it's strongly recommended to use only
numbers and single-line strings as node identifiers if you intend to use write().
@type node: node
@param ... |
Remove a node from the graph.
@type node: node
@param node: Node identifier. | def del_node(self, node):
"""
Remove a node from the graph.
@type node: node
@param node: Node identifier.
"""
for each in list(self.incidents(node)):
# Delete all the edges incident on this node
self.del_edge((each, node))
... |
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence. | def has_edge(self, edge):
"""
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence.
"""
u, v = edge
return (u, v) in self.edge_properties |
Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print. | def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
"""Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
... |
With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
eac... | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values ... |
Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary. | def _parse_makefile(filename, vars=None):
"""Parse a Makefile-style file.
A dictionary containing name/value pairs is returned. If an
optional dictionary is passed in as the second argument, it is
used instead of a new dictionary.
"""
# Regexes needed for parsing Makefile (and similar syntaxes... |
Return a string that identifies the current platform.
This is used mainly to distinguish platform-specific build directories and
platform-specific built distributions. Typically includes the OS name
and version and the architecture (as supplied by 'os.uname()'),
although the exact information included... | def get_platform():
"""Return a string that identifies the current platform.
This is used mainly to distinguish platform-specific build directories and
platform-specific built distributions. Typically includes the OS name
and version and the architecture (as supplied by 'os.uname()'),
although the... |
Add 'authors' attribute based on repo contributions | def set_authors(data):
"""Add 'authors' attribute based on repo contributions
"""
if "authors" in data:
return
shfile = os.path.join(os.path.dirname(__file__), "get_committers.sh")
p = subprocess.Popen(["bash", shfile], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returnco... |
Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does fo... | def make_package(name, path, make_base=None, make_root=None, skip_existing=True,
warn_on_skip=True):
"""Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo... |
Create the analogous package.
Returns:
`Package` object. | def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
... |
Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
... | def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseStrin... |
Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppresse... | def countedArray( expr, intExpr=None ):
"""Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens ... |
Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + seco... | def matchPreviousLiteral(expr):
"""Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
... |
DEPRECATED - use new helper method C{L{originalTextFor}}.
Helper parse action to preserve original parsed text,
overriding any nested parse actions. | def keepOriginalText(s,startLoc,t):
"""DEPRECATED - use new helper method C{L{originalTextFor}}.
Helper parse action to preserve original parsed text,
overriding any nested parse actions."""
try:
endloc = getTokensEndLoc()
except ParseException:
raise ParseFatalException... |
Method to be called from within a parse action to determine the end
location of the parsed tokens. | def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in... |
Internal helper to construct opening and closing tag expressions, given a tag name | def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas,alphan... |
Returns the parse results as a nested list of matching tokens, all converted to strings. | def asList( self ):
"""Returns the parse results as a nested list of matching tokens, all converted to strings."""
out = []
for res in self.__toklist:
if isinstance(res,ParseResults):
out.append( res.asList() )
else:
out.append( res ... |
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data. | def dump(self,indent='',depth=0):
"""Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data."""
out = []
out.append( indent+_ustr(self.asList()) )... |
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
... | def setParseAction( self, *fns, **kwargs ):
"""Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = t... |
Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring}) | def schema_keys(schema):
"""Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring})
"""
... |
Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied... | def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None):
"""Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom ite... |
Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used. | def enter_diff_mode(self, context_model=None):
"""Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used.
"""
assert not self.diff_mode
self.diff_mode = True
if context_model... |
Leave diff mode. | def leave_diff_mode(self):
"""Leave diff mode."""
assert self.diff_mode
self.diff_mode = False
self.diff_context_model = None
self.diff_from_source = False
self.setColumnCount(2)
self.refresh() |
Returns a string suitable for titling a window containing this table. | def get_title(self):
"""Returns a string suitable for titling a window containing this table."""
def _title(context_model):
context = context_model.context()
if context is None:
return "new context*"
title = os.path.basename(context.load_path) if conte... |
Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
... | def _color_level(str_, level):
""" Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
... |
Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ ... | def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (s... |
Emit a record.
If the stream associated with this handler provides tty then the record
that is emitted with be formatted to include escape sequences for
appropriate styling. | def emit(self, record):
"""Emit a record.
If the stream associated with this handler provides tty then the record
that is emitted with be formatted to include escape sequences for
appropriate styling.
"""
try:
message = self.format(record)
if not... |
Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is u... | def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.