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,100 | readbeyond/aeneas | aeneas/container.py | Container.entries | def entries(self):
"""
Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.)
"""
self.log(u"Getting entries")
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
return self.actual_container.entries | python | def entries(self):
"""
Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.)
"""
self.log(u"Getting entries")
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
return self.actual_container.entries | [
"def",
"entries",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Getting entries\"",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"This container does not exist. Wrong path?\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"self",
".",
"actual_container",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The actual container object has not been set\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"return",
"self",
".",
"actual_container",
".",
"entries"
] | Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.) | [
"Return",
"the",
"sorted",
"list",
"of",
"entries",
"in",
"this",
"container",
"each",
"represented",
"by",
"its",
"full",
"path",
"inside",
"the",
"container",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L218-L233 |
232,101 | readbeyond/aeneas | aeneas/container.py | Container.find_entry | def find_entry(self, entry, exact=True):
"""
Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if exact:
self.log([u"Finding entry '%s' with exact=True", entry])
if entry in self.entries:
self.log([u"Found entry '%s'", entry])
return entry
else:
self.log([u"Finding entry '%s' with exact=False", entry])
for ent in self.entries:
if os.path.basename(ent) == entry:
self.log([u"Found entry '%s'", ent])
return ent
self.log([u"Entry '%s' not found", entry])
return None | python | def find_entry(self, entry, exact=True):
"""
Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if exact:
self.log([u"Finding entry '%s' with exact=True", entry])
if entry in self.entries:
self.log([u"Found entry '%s'", entry])
return entry
else:
self.log([u"Finding entry '%s' with exact=False", entry])
for ent in self.entries:
if os.path.basename(ent) == entry:
self.log([u"Found entry '%s'", ent])
return ent
self.log([u"Entry '%s' not found", entry])
return None | [
"def",
"find_entry",
"(",
"self",
",",
"entry",
",",
"exact",
"=",
"True",
")",
":",
"if",
"exact",
":",
"self",
".",
"log",
"(",
"[",
"u\"Finding entry '%s' with exact=True\"",
",",
"entry",
"]",
")",
"if",
"entry",
"in",
"self",
".",
"entries",
":",
"self",
".",
"log",
"(",
"[",
"u\"Found entry '%s'\"",
",",
"entry",
"]",
")",
"return",
"entry",
"else",
":",
"self",
".",
"log",
"(",
"[",
"u\"Finding entry '%s' with exact=False\"",
",",
"entry",
"]",
")",
"for",
"ent",
"in",
"self",
".",
"entries",
":",
"if",
"os",
".",
"path",
".",
"basename",
"(",
"ent",
")",
"==",
"entry",
":",
"self",
".",
"log",
"(",
"[",
"u\"Found entry '%s'\"",
",",
"ent",
"]",
")",
"return",
"ent",
"self",
".",
"log",
"(",
"[",
"u\"Entry '%s' not found\"",
",",
"entry",
"]",
")",
"return",
"None"
] | Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries` | [
"Return",
"the",
"full",
"path",
"to",
"the",
"first",
"entry",
"whose",
"file",
"name",
"equals",
"the",
"given",
"entry",
"path",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L235-L272 |
232,102 | readbeyond/aeneas | aeneas/container.py | Container.read_entry | def read_entry(self, entry):
"""
Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if not self.is_entry_safe(entry):
self.log([u"Accessing entry '%s' is not safe", entry])
return None
if entry not in self.entries:
self.log([u"Entry '%s' not found in this container", entry])
return None
self.log([u"Reading contents of entry '%s'", entry])
try:
return self.actual_container.read_entry(entry)
except:
self.log([u"An error occurred while reading the contents of '%s'", entry])
return None | python | def read_entry(self, entry):
"""
Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if not self.is_entry_safe(entry):
self.log([u"Accessing entry '%s' is not safe", entry])
return None
if entry not in self.entries:
self.log([u"Entry '%s' not found in this container", entry])
return None
self.log([u"Reading contents of entry '%s'", entry])
try:
return self.actual_container.read_entry(entry)
except:
self.log([u"An error occurred while reading the contents of '%s'", entry])
return None | [
"def",
"read_entry",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"self",
".",
"is_entry_safe",
"(",
"entry",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Accessing entry '%s' is not safe\"",
",",
"entry",
"]",
")",
"return",
"None",
"if",
"entry",
"not",
"in",
"self",
".",
"entries",
":",
"self",
".",
"log",
"(",
"[",
"u\"Entry '%s' not found in this container\"",
",",
"entry",
"]",
")",
"return",
"None",
"self",
".",
"log",
"(",
"[",
"u\"Reading contents of entry '%s'\"",
",",
"entry",
"]",
")",
"try",
":",
"return",
"self",
".",
"actual_container",
".",
"read_entry",
"(",
"entry",
")",
"except",
":",
"self",
".",
"log",
"(",
"[",
"u\"An error occurred while reading the contents of '%s'\"",
",",
"entry",
"]",
")",
"return",
"None"
] | Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries` | [
"Read",
"the",
"contents",
"of",
"an",
"entry",
"in",
"this",
"container",
"and",
"return",
"them",
"as",
"a",
"byte",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L274-L298 |
232,103 | readbeyond/aeneas | aeneas/container.py | Container.decompress | def decompress(self, output_path):
"""
Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Decompressing the container into '%s'", output_path])
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(output_path):
self.log_exc(u"The output path is not an existing directory", None, True, ValueError)
if not self.is_safe:
self.log_exc(u"This container contains unsafe entries", None, True, ValueError)
self.actual_container.decompress(output_path) | python | def decompress(self, output_path):
"""
Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Decompressing the container into '%s'", output_path])
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(output_path):
self.log_exc(u"The output path is not an existing directory", None, True, ValueError)
if not self.is_safe:
self.log_exc(u"This container contains unsafe entries", None, True, ValueError)
self.actual_container.decompress(output_path) | [
"def",
"decompress",
"(",
"self",
",",
"output_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Decompressing the container into '%s'\"",
",",
"output_path",
"]",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"This container does not exist. Wrong path?\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"self",
".",
"actual_container",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The actual container object has not been set\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"not",
"gf",
".",
"directory_exists",
"(",
"output_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The output path is not an existing directory\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"if",
"not",
"self",
".",
"is_safe",
":",
"self",
".",
"log_exc",
"(",
"u\"This container contains unsafe entries\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"self",
".",
"actual_container",
".",
"decompress",
"(",
"output_path",
")"
] | Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.) | [
"Decompress",
"the",
"entire",
"container",
"into",
"the",
"given",
"directory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L300-L320 |
232,104 | readbeyond/aeneas | aeneas/container.py | Container.compress | def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Compressing '%s' into this container", input_path])
if self.file_path is None:
self.log_exc(u"The container path has not been set", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(input_path):
self.log_exc(u"The input path is not an existing directory", None, True, ValueError)
gf.ensure_parent_directory(input_path)
self.actual_container.compress(input_path) | python | def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Compressing '%s' into this container", input_path])
if self.file_path is None:
self.log_exc(u"The container path has not been set", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(input_path):
self.log_exc(u"The input path is not an existing directory", None, True, ValueError)
gf.ensure_parent_directory(input_path)
self.actual_container.compress(input_path) | [
"def",
"compress",
"(",
"self",
",",
"input_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Compressing '%s' into this container\"",
",",
"input_path",
"]",
")",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The container path has not been set\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"self",
".",
"actual_container",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The actual container object has not been set\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"not",
"gf",
".",
"directory_exists",
"(",
"input_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The input path is not an existing directory\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"gf",
".",
"ensure_parent_directory",
"(",
"input_path",
")",
"self",
".",
"actual_container",
".",
"compress",
"(",
"input_path",
")"
] | Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.) | [
"Compress",
"the",
"contents",
"of",
"the",
"given",
"directory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L322-L341 |
232,105 | readbeyond/aeneas | aeneas/container.py | Container.exists | def exists(self):
"""
Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean
"""
return gf.file_exists(self.file_path) or gf.directory_exists(self.file_path) | python | def exists(self):
"""
Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean
"""
return gf.file_exists(self.file_path) or gf.directory_exists(self.file_path) | [
"def",
"exists",
"(",
"self",
")",
":",
"return",
"gf",
".",
"file_exists",
"(",
"self",
".",
"file_path",
")",
"or",
"gf",
".",
"directory_exists",
"(",
"self",
".",
"file_path",
")"
] | Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean | [
"Return",
"True",
"if",
"the",
"container",
"has",
"its",
"path",
"set",
"and",
"it",
"exists",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L343-L350 |
232,106 | readbeyond/aeneas | aeneas/container.py | Container._set_actual_container | def _set_actual_container(self):
"""
Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory).
"""
# infer container format
if self.container_format is None:
self.log(u"Inferring actual container format...")
path_lowercased = self.file_path.lower()
self.log([u"Lowercased file path: '%s'", path_lowercased])
self.container_format = ContainerFormat.UNPACKED
for fmt in ContainerFormat.ALLOWED_FILE_VALUES:
if path_lowercased.endswith(fmt):
self.container_format = fmt
break
self.log(u"Inferring actual container format... done")
self.log([u"Inferred format: '%s'", self.container_format])
# set the actual container
self.log(u"Setting actual container...")
class_map = {
ContainerFormat.ZIP: (_ContainerZIP, None),
ContainerFormat.EPUB: (_ContainerZIP, None),
ContainerFormat.TAR: (_ContainerTAR, ""),
ContainerFormat.TAR_GZ: (_ContainerTAR, ":gz"),
ContainerFormat.TAR_BZ2: (_ContainerTAR, ":bz2"),
ContainerFormat.UNPACKED: (_ContainerUnpacked, None)
}
actual_class, variant = class_map[self.container_format]
self.actual_container = actual_class(
file_path=self.file_path,
variant=variant,
rconf=self.rconf,
logger=self.logger
)
self.log([u"Actual container format: '%s'", self.container_format])
self.log(u"Setting actual container... done") | python | def _set_actual_container(self):
"""
Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory).
"""
# infer container format
if self.container_format is None:
self.log(u"Inferring actual container format...")
path_lowercased = self.file_path.lower()
self.log([u"Lowercased file path: '%s'", path_lowercased])
self.container_format = ContainerFormat.UNPACKED
for fmt in ContainerFormat.ALLOWED_FILE_VALUES:
if path_lowercased.endswith(fmt):
self.container_format = fmt
break
self.log(u"Inferring actual container format... done")
self.log([u"Inferred format: '%s'", self.container_format])
# set the actual container
self.log(u"Setting actual container...")
class_map = {
ContainerFormat.ZIP: (_ContainerZIP, None),
ContainerFormat.EPUB: (_ContainerZIP, None),
ContainerFormat.TAR: (_ContainerTAR, ""),
ContainerFormat.TAR_GZ: (_ContainerTAR, ":gz"),
ContainerFormat.TAR_BZ2: (_ContainerTAR, ":bz2"),
ContainerFormat.UNPACKED: (_ContainerUnpacked, None)
}
actual_class, variant = class_map[self.container_format]
self.actual_container = actual_class(
file_path=self.file_path,
variant=variant,
rconf=self.rconf,
logger=self.logger
)
self.log([u"Actual container format: '%s'", self.container_format])
self.log(u"Setting actual container... done") | [
"def",
"_set_actual_container",
"(",
"self",
")",
":",
"# infer container format",
"if",
"self",
".",
"container_format",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inferring actual container format...\"",
")",
"path_lowercased",
"=",
"self",
".",
"file_path",
".",
"lower",
"(",
")",
"self",
".",
"log",
"(",
"[",
"u\"Lowercased file path: '%s'\"",
",",
"path_lowercased",
"]",
")",
"self",
".",
"container_format",
"=",
"ContainerFormat",
".",
"UNPACKED",
"for",
"fmt",
"in",
"ContainerFormat",
".",
"ALLOWED_FILE_VALUES",
":",
"if",
"path_lowercased",
".",
"endswith",
"(",
"fmt",
")",
":",
"self",
".",
"container_format",
"=",
"fmt",
"break",
"self",
".",
"log",
"(",
"u\"Inferring actual container format... done\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Inferred format: '%s'\"",
",",
"self",
".",
"container_format",
"]",
")",
"# set the actual container",
"self",
".",
"log",
"(",
"u\"Setting actual container...\"",
")",
"class_map",
"=",
"{",
"ContainerFormat",
".",
"ZIP",
":",
"(",
"_ContainerZIP",
",",
"None",
")",
",",
"ContainerFormat",
".",
"EPUB",
":",
"(",
"_ContainerZIP",
",",
"None",
")",
",",
"ContainerFormat",
".",
"TAR",
":",
"(",
"_ContainerTAR",
",",
"\"\"",
")",
",",
"ContainerFormat",
".",
"TAR_GZ",
":",
"(",
"_ContainerTAR",
",",
"\":gz\"",
")",
",",
"ContainerFormat",
".",
"TAR_BZ2",
":",
"(",
"_ContainerTAR",
",",
"\":bz2\"",
")",
",",
"ContainerFormat",
".",
"UNPACKED",
":",
"(",
"_ContainerUnpacked",
",",
"None",
")",
"}",
"actual_class",
",",
"variant",
"=",
"class_map",
"[",
"self",
".",
"container_format",
"]",
"self",
".",
"actual_container",
"=",
"actual_class",
"(",
"file_path",
"=",
"self",
".",
"file_path",
",",
"variant",
"=",
"variant",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"log",
"(",
"[",
"u\"Actual container format: '%s'\"",
",",
"self",
".",
"container_format",
"]",
")",
"self",
".",
"log",
"(",
"u\"Setting actual container... done\"",
")"
] | Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory). | [
"Set",
"the",
"actual",
"container",
"based",
"on",
"the",
"specified",
"container",
"format",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L352-L393 |
232,107 | readbeyond/aeneas | aeneas/extra/ctw_speect.py | CustomTTSWrapper._synthesize_single_python_helper | def _synthesize_single_python_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 a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data))
"""
# return zero if text is the empty string
if len(text) == 0:
#
# NOTE values of sample_rate, encoding, data
# do not matter if the duration is 0.000,
# so set them to None instead of the more precise:
# return (True, (TimeValue("0.000"), 16000, "pcm_s16le", numpy.array([])))
#
self.log(u"len(text) is zero: returning 0.000")
return (True, (TimeValue("0.000"), None, None, None))
#
# NOTE in this example, we assume that the Speect voice data files
# are located in the same directory of this .py source file
# and that the voice JSON file is called "voice.json"
#
# NOTE the voice_code value is ignored in this example,
# since we have only one TTS voice,
# but in general one might select a voice file to load,
# depending on voice_code;
# in fact, we could have created the ``voice`` object
# only once, in the constructor, instead of creating it
# each time this function is invoked,
# achieving slightly faster synthesis
#
voice_json_path = gf.safe_str(gf.absolute_path("voice.json", __file__))
voice = speect.SVoice(voice_json_path)
utt = voice.synth(text)
audio = utt.features["audio"]
if output_file_path is None:
self.log(u"output_file_path is None => not saving to file")
else:
self.log(u"output_file_path is not None => saving to file...")
# NOTE apparently, save_riff needs the path to be a byte string
audio.save_riff(gf.safe_str(output_file_path))
self.log(u"output_file_path is not None => saving to file... done")
# return immediately if returning audio data is not needed
if not return_audio_data:
self.log(u"return_audio_data is True => return immediately")
return (True, None)
# get length and data using speect Python API
self.log(u"return_audio_data is True => read and return audio data")
waveform = audio.get_audio_waveform()
audio_sample_rate = int(waveform["samplerate"])
audio_length = TimeValue(audio.num_samples() / audio_sample_rate)
audio_format = "pcm16"
audio_samples = numpy.fromstring(
waveform["samples"],
dtype=numpy.int16
).astype("float64") / 32768
return (True, (
audio_length,
audio_sample_rate,
audio_format,
audio_samples
)) | python | def _synthesize_single_python_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 a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data))
"""
# return zero if text is the empty string
if len(text) == 0:
#
# NOTE values of sample_rate, encoding, data
# do not matter if the duration is 0.000,
# so set them to None instead of the more precise:
# return (True, (TimeValue("0.000"), 16000, "pcm_s16le", numpy.array([])))
#
self.log(u"len(text) is zero: returning 0.000")
return (True, (TimeValue("0.000"), None, None, None))
#
# NOTE in this example, we assume that the Speect voice data files
# are located in the same directory of this .py source file
# and that the voice JSON file is called "voice.json"
#
# NOTE the voice_code value is ignored in this example,
# since we have only one TTS voice,
# but in general one might select a voice file to load,
# depending on voice_code;
# in fact, we could have created the ``voice`` object
# only once, in the constructor, instead of creating it
# each time this function is invoked,
# achieving slightly faster synthesis
#
voice_json_path = gf.safe_str(gf.absolute_path("voice.json", __file__))
voice = speect.SVoice(voice_json_path)
utt = voice.synth(text)
audio = utt.features["audio"]
if output_file_path is None:
self.log(u"output_file_path is None => not saving to file")
else:
self.log(u"output_file_path is not None => saving to file...")
# NOTE apparently, save_riff needs the path to be a byte string
audio.save_riff(gf.safe_str(output_file_path))
self.log(u"output_file_path is not None => saving to file... done")
# return immediately if returning audio data is not needed
if not return_audio_data:
self.log(u"return_audio_data is True => return immediately")
return (True, None)
# get length and data using speect Python API
self.log(u"return_audio_data is True => read and return audio data")
waveform = audio.get_audio_waveform()
audio_sample_rate = int(waveform["samplerate"])
audio_length = TimeValue(audio.num_samples() / audio_sample_rate)
audio_format = "pcm16"
audio_samples = numpy.fromstring(
waveform["samples"],
dtype=numpy.int16
).astype("float64") / 32768
return (True, (
audio_length,
audio_sample_rate,
audio_format,
audio_samples
)) | [
"def",
"_synthesize_single_python_helper",
"(",
"self",
",",
"text",
",",
"voice_code",
",",
"output_file_path",
"=",
"None",
",",
"return_audio_data",
"=",
"True",
")",
":",
"# return zero if text is the empty string",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":",
"#",
"# NOTE values of sample_rate, encoding, data",
"# do not matter if the duration is 0.000,",
"# so set them to None instead of the more precise:",
"# return (True, (TimeValue(\"0.000\"), 16000, \"pcm_s16le\", numpy.array([])))",
"#",
"self",
".",
"log",
"(",
"u\"len(text) is zero: returning 0.000\"",
")",
"return",
"(",
"True",
",",
"(",
"TimeValue",
"(",
"\"0.000\"",
")",
",",
"None",
",",
"None",
",",
"None",
")",
")",
"#",
"# NOTE in this example, we assume that the Speect voice data files",
"# are located in the same directory of this .py source file",
"# and that the voice JSON file is called \"voice.json\"",
"#",
"# NOTE the voice_code value is ignored in this example,",
"# since we have only one TTS voice,",
"# but in general one might select a voice file to load,",
"# depending on voice_code;",
"# in fact, we could have created the ``voice`` object",
"# only once, in the constructor, instead of creating it",
"# each time this function is invoked,",
"# achieving slightly faster synthesis",
"#",
"voice_json_path",
"=",
"gf",
".",
"safe_str",
"(",
"gf",
".",
"absolute_path",
"(",
"\"voice.json\"",
",",
"__file__",
")",
")",
"voice",
"=",
"speect",
".",
"SVoice",
"(",
"voice_json_path",
")",
"utt",
"=",
"voice",
".",
"synth",
"(",
"text",
")",
"audio",
"=",
"utt",
".",
"features",
"[",
"\"audio\"",
"]",
"if",
"output_file_path",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"output_file_path is None => not saving to file\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"output_file_path is not None => saving to file...\"",
")",
"# NOTE apparently, save_riff needs the path to be a byte string",
"audio",
".",
"save_riff",
"(",
"gf",
".",
"safe_str",
"(",
"output_file_path",
")",
")",
"self",
".",
"log",
"(",
"u\"output_file_path is not None => saving to file... done\"",
")",
"# return immediately if returning audio data is not needed",
"if",
"not",
"return_audio_data",
":",
"self",
".",
"log",
"(",
"u\"return_audio_data is True => return immediately\"",
")",
"return",
"(",
"True",
",",
"None",
")",
"# get length and data using speect Python API",
"self",
".",
"log",
"(",
"u\"return_audio_data is True => read and return audio data\"",
")",
"waveform",
"=",
"audio",
".",
"get_audio_waveform",
"(",
")",
"audio_sample_rate",
"=",
"int",
"(",
"waveform",
"[",
"\"samplerate\"",
"]",
")",
"audio_length",
"=",
"TimeValue",
"(",
"audio",
".",
"num_samples",
"(",
")",
"/",
"audio_sample_rate",
")",
"audio_format",
"=",
"\"pcm16\"",
"audio_samples",
"=",
"numpy",
".",
"fromstring",
"(",
"waveform",
"[",
"\"samples\"",
"]",
",",
"dtype",
"=",
"numpy",
".",
"int16",
")",
".",
"astype",
"(",
"\"float64\"",
")",
"/",
"32768",
"return",
"(",
"True",
",",
"(",
"audio_length",
",",
"audio_sample_rate",
",",
"audio_format",
",",
"audio_samples",
")",
")"
] | This is an helper function to synthesize a single text fragment via a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data)) | [
"This",
"is",
"an",
"helper",
"function",
"to",
"synthesize",
"a",
"single",
"text",
"fragment",
"via",
"a",
"Python",
"call",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/extra/ctw_speect.py#L91-L163 |
232,108 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer.analyze | def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
"""
try:
if config_string is not None:
self.log(u"Analyzing container with the given config string")
return self._analyze_txt_config(config_string=config_string)
elif self.container.has_config_xml:
self.log(u"Analyzing container with XML config file")
return self._analyze_xml_config(config_contents=None)
elif self.container.has_config_txt:
self.log(u"Analyzing container with TXT config file")
return self._analyze_txt_config(config_string=None)
else:
self.log(u"No configuration file in this container, returning None")
except (OSError, KeyError, TypeError) as exc:
self.log_exc(u"An unexpected error occurred while analyzing", exc, True, None)
return None | python | def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
"""
try:
if config_string is not None:
self.log(u"Analyzing container with the given config string")
return self._analyze_txt_config(config_string=config_string)
elif self.container.has_config_xml:
self.log(u"Analyzing container with XML config file")
return self._analyze_xml_config(config_contents=None)
elif self.container.has_config_txt:
self.log(u"Analyzing container with TXT config file")
return self._analyze_txt_config(config_string=None)
else:
self.log(u"No configuration file in this container, returning None")
except (OSError, KeyError, TypeError) as exc:
self.log_exc(u"An unexpected error occurred while analyzing", exc, True, None)
return None | [
"def",
"analyze",
"(",
"self",
",",
"config_string",
"=",
"None",
")",
":",
"try",
":",
"if",
"config_string",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with the given config string\"",
")",
"return",
"self",
".",
"_analyze_txt_config",
"(",
"config_string",
"=",
"config_string",
")",
"elif",
"self",
".",
"container",
".",
"has_config_xml",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with XML config file\"",
")",
"return",
"self",
".",
"_analyze_xml_config",
"(",
"config_contents",
"=",
"None",
")",
"elif",
"self",
".",
"container",
".",
"has_config_txt",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with TXT config file\"",
")",
"return",
"self",
".",
"_analyze_txt_config",
"(",
"config_string",
"=",
"None",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"No configuration file in this container, returning None\"",
")",
"except",
"(",
"OSError",
",",
"KeyError",
",",
"TypeError",
")",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"An unexpected error occurred while analyzing\"",
",",
"exc",
",",
"True",
",",
"None",
")",
"return",
"None"
] | Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None`` | [
"Analyze",
"the",
"given",
"container",
"and",
"return",
"the",
"corresponding",
"job",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L72-L96 |
232,109 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._create_task | def _create_task(
self,
task_info,
config_string,
sync_map_root_directory,
job_os_hierarchy_type
):
"""
Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task`
"""
self.log(u"Converting config string to config dict")
parameters = gf.config_string_to_dict(config_string)
self.log(u"Creating task")
task = Task(config_string, logger=self.logger)
task.configuration["description"] = "Task %s" % task_info[0]
self.log([u"Task description: %s", task.configuration["description"]])
try:
task.configuration["language"] = parameters[gc.PPN_TASK_LANGUAGE]
self.log([u"Set language from task: '%s'", task.configuration["language"]])
except KeyError:
task.configuration["language"] = parameters[gc.PPN_JOB_LANGUAGE]
self.log([u"Set language from job: '%s'", task.configuration["language"]])
custom_id = task_info[0]
task.configuration["custom_id"] = custom_id
self.log([u"Task custom_id: %s", task.configuration["custom_id"]])
task.text_file_path = task_info[1]
self.log([u"Task text file path: %s", task.text_file_path])
task.audio_file_path = task_info[2]
self.log([u"Task audio file path: %s", task.audio_file_path])
task.sync_map_file_path = self._compute_sync_map_file_path(
sync_map_root_directory,
job_os_hierarchy_type,
custom_id,
task.configuration["o_name"]
)
self.log([u"Task sync map file path: %s", task.sync_map_file_path])
self.log(u"Replacing placeholder in os_file_smil_audio_ref")
task.configuration["o_smil_audio_ref"] = self._replace_placeholder(
task.configuration["o_smil_audio_ref"],
custom_id
)
self.log(u"Replacing placeholder in os_file_smil_page_ref")
task.configuration["o_smil_page_ref"] = self._replace_placeholder(
task.configuration["o_smil_page_ref"],
custom_id
)
self.log(u"Returning task")
return task | python | def _create_task(
self,
task_info,
config_string,
sync_map_root_directory,
job_os_hierarchy_type
):
"""
Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task`
"""
self.log(u"Converting config string to config dict")
parameters = gf.config_string_to_dict(config_string)
self.log(u"Creating task")
task = Task(config_string, logger=self.logger)
task.configuration["description"] = "Task %s" % task_info[0]
self.log([u"Task description: %s", task.configuration["description"]])
try:
task.configuration["language"] = parameters[gc.PPN_TASK_LANGUAGE]
self.log([u"Set language from task: '%s'", task.configuration["language"]])
except KeyError:
task.configuration["language"] = parameters[gc.PPN_JOB_LANGUAGE]
self.log([u"Set language from job: '%s'", task.configuration["language"]])
custom_id = task_info[0]
task.configuration["custom_id"] = custom_id
self.log([u"Task custom_id: %s", task.configuration["custom_id"]])
task.text_file_path = task_info[1]
self.log([u"Task text file path: %s", task.text_file_path])
task.audio_file_path = task_info[2]
self.log([u"Task audio file path: %s", task.audio_file_path])
task.sync_map_file_path = self._compute_sync_map_file_path(
sync_map_root_directory,
job_os_hierarchy_type,
custom_id,
task.configuration["o_name"]
)
self.log([u"Task sync map file path: %s", task.sync_map_file_path])
self.log(u"Replacing placeholder in os_file_smil_audio_ref")
task.configuration["o_smil_audio_ref"] = self._replace_placeholder(
task.configuration["o_smil_audio_ref"],
custom_id
)
self.log(u"Replacing placeholder in os_file_smil_page_ref")
task.configuration["o_smil_page_ref"] = self._replace_placeholder(
task.configuration["o_smil_page_ref"],
custom_id
)
self.log(u"Returning task")
return task | [
"def",
"_create_task",
"(",
"self",
",",
"task_info",
",",
"config_string",
",",
"sync_map_root_directory",
",",
"job_os_hierarchy_type",
")",
":",
"self",
".",
"log",
"(",
"u\"Converting config string to config dict\"",
")",
"parameters",
"=",
"gf",
".",
"config_string_to_dict",
"(",
"config_string",
")",
"self",
".",
"log",
"(",
"u\"Creating task\"",
")",
"task",
"=",
"Task",
"(",
"config_string",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"task",
".",
"configuration",
"[",
"\"description\"",
"]",
"=",
"\"Task %s\"",
"%",
"task_info",
"[",
"0",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Task description: %s\"",
",",
"task",
".",
"configuration",
"[",
"\"description\"",
"]",
"]",
")",
"try",
":",
"task",
".",
"configuration",
"[",
"\"language\"",
"]",
"=",
"parameters",
"[",
"gc",
".",
"PPN_TASK_LANGUAGE",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Set language from task: '%s'\"",
",",
"task",
".",
"configuration",
"[",
"\"language\"",
"]",
"]",
")",
"except",
"KeyError",
":",
"task",
".",
"configuration",
"[",
"\"language\"",
"]",
"=",
"parameters",
"[",
"gc",
".",
"PPN_JOB_LANGUAGE",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Set language from job: '%s'\"",
",",
"task",
".",
"configuration",
"[",
"\"language\"",
"]",
"]",
")",
"custom_id",
"=",
"task_info",
"[",
"0",
"]",
"task",
".",
"configuration",
"[",
"\"custom_id\"",
"]",
"=",
"custom_id",
"self",
".",
"log",
"(",
"[",
"u\"Task custom_id: %s\"",
",",
"task",
".",
"configuration",
"[",
"\"custom_id\"",
"]",
"]",
")",
"task",
".",
"text_file_path",
"=",
"task_info",
"[",
"1",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Task text file path: %s\"",
",",
"task",
".",
"text_file_path",
"]",
")",
"task",
".",
"audio_file_path",
"=",
"task_info",
"[",
"2",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Task audio file path: %s\"",
",",
"task",
".",
"audio_file_path",
"]",
")",
"task",
".",
"sync_map_file_path",
"=",
"self",
".",
"_compute_sync_map_file_path",
"(",
"sync_map_root_directory",
",",
"job_os_hierarchy_type",
",",
"custom_id",
",",
"task",
".",
"configuration",
"[",
"\"o_name\"",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Task sync map file path: %s\"",
",",
"task",
".",
"sync_map_file_path",
"]",
")",
"self",
".",
"log",
"(",
"u\"Replacing placeholder in os_file_smil_audio_ref\"",
")",
"task",
".",
"configuration",
"[",
"\"o_smil_audio_ref\"",
"]",
"=",
"self",
".",
"_replace_placeholder",
"(",
"task",
".",
"configuration",
"[",
"\"o_smil_audio_ref\"",
"]",
",",
"custom_id",
")",
"self",
".",
"log",
"(",
"u\"Replacing placeholder in os_file_smil_page_ref\"",
")",
"task",
".",
"configuration",
"[",
"\"o_smil_page_ref\"",
"]",
"=",
"self",
".",
"_replace_placeholder",
"(",
"task",
".",
"configuration",
"[",
"\"o_smil_page_ref\"",
"]",
",",
"custom_id",
")",
"self",
".",
"log",
"(",
"u\"Returning task\"",
")",
"return",
"task"
] | Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task` | [
"Create",
"a",
"task",
"object",
"from"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L330-L388 |
232,110 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._compute_sync_map_file_path | def _compute_sync_map_file_path(
self,
root,
hierarchy_type,
custom_id,
file_name
):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string
"""
prefix = root
if hierarchy_type == HierarchyType.PAGED:
prefix = gf.norm_join(prefix, custom_id)
file_name_joined = gf.norm_join(prefix, file_name)
return self._replace_placeholder(file_name_joined, custom_id) | python | def _compute_sync_map_file_path(
self,
root,
hierarchy_type,
custom_id,
file_name
):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string
"""
prefix = root
if hierarchy_type == HierarchyType.PAGED:
prefix = gf.norm_join(prefix, custom_id)
file_name_joined = gf.norm_join(prefix, file_name)
return self._replace_placeholder(file_name_joined, custom_id) | [
"def",
"_compute_sync_map_file_path",
"(",
"self",
",",
"root",
",",
"hierarchy_type",
",",
"custom_id",
",",
"file_name",
")",
":",
"prefix",
"=",
"root",
"if",
"hierarchy_type",
"==",
"HierarchyType",
".",
"PAGED",
":",
"prefix",
"=",
"gf",
".",
"norm_join",
"(",
"prefix",
",",
"custom_id",
")",
"file_name_joined",
"=",
"gf",
".",
"norm_join",
"(",
"prefix",
",",
"file_name",
")",
"return",
"self",
".",
"_replace_placeholder",
"(",
"file_name_joined",
",",
"custom_id",
")"
] | Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string | [
"Compute",
"the",
"sync",
"map",
"file",
"path",
"inside",
"the",
"output",
"container",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L403-L425 |
232,111 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._find_files | def _find_files(self, entries, root, relative_path, file_name_regex):
"""
Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path)
"""
self.log([u"Finding files within root: '%s'", root])
target = root
if relative_path is not None:
self.log([u"Joining relative path: '%s'", relative_path])
target = gf.norm_join(root, relative_path)
self.log([u"Finding files within target: '%s'", target])
files = []
target_len = len(target)
for entry in entries:
if entry.startswith(target):
self.log([u"Examining entry: '%s'", entry])
entry_suffix = entry[target_len + 1:]
self.log([u"Examining entry suffix: '%s'", entry_suffix])
if re.search(file_name_regex, entry_suffix) is not None:
self.log([u"Match: '%s'", entry])
files.append(entry)
else:
self.log([u"No match: '%s'", entry])
return sorted(files) | python | def _find_files(self, entries, root, relative_path, file_name_regex):
"""
Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path)
"""
self.log([u"Finding files within root: '%s'", root])
target = root
if relative_path is not None:
self.log([u"Joining relative path: '%s'", relative_path])
target = gf.norm_join(root, relative_path)
self.log([u"Finding files within target: '%s'", target])
files = []
target_len = len(target)
for entry in entries:
if entry.startswith(target):
self.log([u"Examining entry: '%s'", entry])
entry_suffix = entry[target_len + 1:]
self.log([u"Examining entry suffix: '%s'", entry_suffix])
if re.search(file_name_regex, entry_suffix) is not None:
self.log([u"Match: '%s'", entry])
files.append(entry)
else:
self.log([u"No match: '%s'", entry])
return sorted(files) | [
"def",
"_find_files",
"(",
"self",
",",
"entries",
",",
"root",
",",
"relative_path",
",",
"file_name_regex",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Finding files within root: '%s'\"",
",",
"root",
"]",
")",
"target",
"=",
"root",
"if",
"relative_path",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"[",
"u\"Joining relative path: '%s'\"",
",",
"relative_path",
"]",
")",
"target",
"=",
"gf",
".",
"norm_join",
"(",
"root",
",",
"relative_path",
")",
"self",
".",
"log",
"(",
"[",
"u\"Finding files within target: '%s'\"",
",",
"target",
"]",
")",
"files",
"=",
"[",
"]",
"target_len",
"=",
"len",
"(",
"target",
")",
"for",
"entry",
"in",
"entries",
":",
"if",
"entry",
".",
"startswith",
"(",
"target",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Examining entry: '%s'\"",
",",
"entry",
"]",
")",
"entry_suffix",
"=",
"entry",
"[",
"target_len",
"+",
"1",
":",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Examining entry suffix: '%s'\"",
",",
"entry_suffix",
"]",
")",
"if",
"re",
".",
"search",
"(",
"file_name_regex",
",",
"entry_suffix",
")",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"[",
"u\"Match: '%s'\"",
",",
"entry",
"]",
")",
"files",
".",
"append",
"(",
"entry",
")",
"else",
":",
"self",
".",
"log",
"(",
"[",
"u\"No match: '%s'\"",
",",
"entry",
"]",
")",
"return",
"sorted",
"(",
"files",
")"
] | Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path) | [
"Return",
"the",
"elements",
"in",
"entries",
"that"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L427-L458 |
232,112 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._match_files_flat_hierarchy | def _match_files_flat_hierarchy(self, text_files, audio_files):
"""
Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above)
"""
self.log(u"Matching files in flat hierarchy")
self.log([u"Text files: '%s'", text_files])
self.log([u"Audio files: '%s'", audio_files])
d_text = {}
d_audio = {}
for text_file in text_files:
text_file_no_ext = gf.file_name_without_extension(text_file)
d_text[text_file_no_ext] = text_file
self.log([u"Added text file '%s' to key '%s'", text_file, text_file_no_ext])
for audio_file in audio_files:
audio_file_no_ext = gf.file_name_without_extension(audio_file)
d_audio[audio_file_no_ext] = audio_file
self.log([u"Added audio file '%s' to key '%s'", audio_file, audio_file_no_ext])
tasks = []
for key in d_text.keys():
self.log([u"Examining text key '%s'", key])
if key in d_audio:
self.log([u"Key '%s' is also in audio", key])
tasks.append([key, d_text[key], d_audio[key]])
self.log([u"Added pair ('%s', '%s')", d_text[key], d_audio[key]])
return tasks | python | def _match_files_flat_hierarchy(self, text_files, audio_files):
"""
Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above)
"""
self.log(u"Matching files in flat hierarchy")
self.log([u"Text files: '%s'", text_files])
self.log([u"Audio files: '%s'", audio_files])
d_text = {}
d_audio = {}
for text_file in text_files:
text_file_no_ext = gf.file_name_without_extension(text_file)
d_text[text_file_no_ext] = text_file
self.log([u"Added text file '%s' to key '%s'", text_file, text_file_no_ext])
for audio_file in audio_files:
audio_file_no_ext = gf.file_name_without_extension(audio_file)
d_audio[audio_file_no_ext] = audio_file
self.log([u"Added audio file '%s' to key '%s'", audio_file, audio_file_no_ext])
tasks = []
for key in d_text.keys():
self.log([u"Examining text key '%s'", key])
if key in d_audio:
self.log([u"Key '%s' is also in audio", key])
tasks.append([key, d_text[key], d_audio[key]])
self.log([u"Added pair ('%s', '%s')", d_text[key], d_audio[key]])
return tasks | [
"def",
"_match_files_flat_hierarchy",
"(",
"self",
",",
"text_files",
",",
"audio_files",
")",
":",
"self",
".",
"log",
"(",
"u\"Matching files in flat hierarchy\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Text files: '%s'\"",
",",
"text_files",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Audio files: '%s'\"",
",",
"audio_files",
"]",
")",
"d_text",
"=",
"{",
"}",
"d_audio",
"=",
"{",
"}",
"for",
"text_file",
"in",
"text_files",
":",
"text_file_no_ext",
"=",
"gf",
".",
"file_name_without_extension",
"(",
"text_file",
")",
"d_text",
"[",
"text_file_no_ext",
"]",
"=",
"text_file",
"self",
".",
"log",
"(",
"[",
"u\"Added text file '%s' to key '%s'\"",
",",
"text_file",
",",
"text_file_no_ext",
"]",
")",
"for",
"audio_file",
"in",
"audio_files",
":",
"audio_file_no_ext",
"=",
"gf",
".",
"file_name_without_extension",
"(",
"audio_file",
")",
"d_audio",
"[",
"audio_file_no_ext",
"]",
"=",
"audio_file",
"self",
".",
"log",
"(",
"[",
"u\"Added audio file '%s' to key '%s'\"",
",",
"audio_file",
",",
"audio_file_no_ext",
"]",
")",
"tasks",
"=",
"[",
"]",
"for",
"key",
"in",
"d_text",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Examining text key '%s'\"",
",",
"key",
"]",
")",
"if",
"key",
"in",
"d_audio",
":",
"self",
".",
"log",
"(",
"[",
"u\"Key '%s' is also in audio\"",
",",
"key",
"]",
")",
"tasks",
".",
"append",
"(",
"[",
"key",
",",
"d_text",
"[",
"key",
"]",
",",
"d_audio",
"[",
"key",
"]",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Added pair ('%s', '%s')\"",
",",
"d_text",
"[",
"key",
"]",
",",
"d_audio",
"[",
"key",
"]",
"]",
")",
"return",
"tasks"
] | Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above) | [
"Match",
"audio",
"and",
"text",
"files",
"in",
"flat",
"hierarchies",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L460-L499 |
232,113 | readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._match_directories | def _match_directories(self, entries, root, regex_string):
"""
Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories
"""
self.log(u"Matching directory names in paged hierarchy")
self.log([u"Matching within '%s'", root])
self.log([u"Matching regex '%s'", regex_string])
regex = re.compile(r"" + regex_string)
directories = set()
root_len = len(root)
for entry in entries:
# look only inside root dir
if entry.startswith(root):
self.log([u"Examining '%s'", entry])
# remove common prefix root/
entry = entry[root_len + 1:]
# split path
entry_splitted = entry.split(os.sep)
# match regex
if ((len(entry_splitted) >= 2) and
(re.match(regex, entry_splitted[0]) is not None)):
directories.add(entry_splitted[0])
self.log([u"Match: '%s'", entry_splitted[0]])
else:
self.log([u"No match: '%s'", entry])
return sorted(directories) | python | def _match_directories(self, entries, root, regex_string):
"""
Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories
"""
self.log(u"Matching directory names in paged hierarchy")
self.log([u"Matching within '%s'", root])
self.log([u"Matching regex '%s'", regex_string])
regex = re.compile(r"" + regex_string)
directories = set()
root_len = len(root)
for entry in entries:
# look only inside root dir
if entry.startswith(root):
self.log([u"Examining '%s'", entry])
# remove common prefix root/
entry = entry[root_len + 1:]
# split path
entry_splitted = entry.split(os.sep)
# match regex
if ((len(entry_splitted) >= 2) and
(re.match(regex, entry_splitted[0]) is not None)):
directories.add(entry_splitted[0])
self.log([u"Match: '%s'", entry_splitted[0]])
else:
self.log([u"No match: '%s'", entry])
return sorted(directories) | [
"def",
"_match_directories",
"(",
"self",
",",
"entries",
",",
"root",
",",
"regex_string",
")",
":",
"self",
".",
"log",
"(",
"u\"Matching directory names in paged hierarchy\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Matching within '%s'\"",
",",
"root",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Matching regex '%s'\"",
",",
"regex_string",
"]",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"\"",
"+",
"regex_string",
")",
"directories",
"=",
"set",
"(",
")",
"root_len",
"=",
"len",
"(",
"root",
")",
"for",
"entry",
"in",
"entries",
":",
"# look only inside root dir",
"if",
"entry",
".",
"startswith",
"(",
"root",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Examining '%s'\"",
",",
"entry",
"]",
")",
"# remove common prefix root/",
"entry",
"=",
"entry",
"[",
"root_len",
"+",
"1",
":",
"]",
"# split path",
"entry_splitted",
"=",
"entry",
".",
"split",
"(",
"os",
".",
"sep",
")",
"# match regex",
"if",
"(",
"(",
"len",
"(",
"entry_splitted",
")",
">=",
"2",
")",
"and",
"(",
"re",
".",
"match",
"(",
"regex",
",",
"entry_splitted",
"[",
"0",
"]",
")",
"is",
"not",
"None",
")",
")",
":",
"directories",
".",
"add",
"(",
"entry_splitted",
"[",
"0",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Match: '%s'\"",
",",
"entry_splitted",
"[",
"0",
"]",
"]",
")",
"else",
":",
"self",
".",
"log",
"(",
"[",
"u\"No match: '%s'\"",
",",
"entry",
"]",
")",
"return",
"sorted",
"(",
"directories",
")"
] | Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories | [
"Match",
"directory",
"names",
"in",
"paged",
"hierarchies",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L501-L547 |
232,114 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask.load_task | def load_task(self, task):
"""
Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task`
"""
if not isinstance(task, Task):
self.log_exc(u"task is not an instance of Task", None, True, ExecuteTaskInputError)
self.task = task | python | def load_task(self, task):
"""
Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task`
"""
if not isinstance(task, Task):
self.log_exc(u"task is not an instance of Task", None, True, ExecuteTaskInputError)
self.task = task | [
"def",
"load_task",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"isinstance",
"(",
"task",
",",
"Task",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"task is not an instance of Task\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"self",
".",
"task",
"=",
"task"
] | Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task` | [
"Load",
"the",
"task",
"from",
"the",
"given",
"Task",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L97-L107 |
232,115 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_begin | def _step_begin(self, label, log=True):
""" Log begin of a step """
if log:
self.step_label = label
self.step_begin_time = self.log(u"STEP %d BEGIN (%s)" % (self.step_index, label)) | python | def _step_begin(self, label, log=True):
""" Log begin of a step """
if log:
self.step_label = label
self.step_begin_time = self.log(u"STEP %d BEGIN (%s)" % (self.step_index, label)) | [
"def",
"_step_begin",
"(",
"self",
",",
"label",
",",
"log",
"=",
"True",
")",
":",
"if",
"log",
":",
"self",
".",
"step_label",
"=",
"label",
"self",
".",
"step_begin_time",
"=",
"self",
".",
"log",
"(",
"u\"STEP %d BEGIN (%s)\"",
"%",
"(",
"self",
".",
"step_index",
",",
"label",
")",
")"
] | Log begin of a step | [
"Log",
"begin",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L109-L113 |
232,116 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_end | def _step_end(self, log=True):
""" Log end of a step """
if log:
step_end_time = self.log(u"STEP %d END (%s)" % (self.step_index, self.step_label))
diff = (step_end_time - self.step_begin_time)
diff = float(diff.seconds + diff.microseconds / 1000000.0)
self.step_total += diff
self.log(u"STEP %d DURATION %.3f (%s)" % (self.step_index, diff, self.step_label))
self.step_index += 1 | python | def _step_end(self, log=True):
""" Log end of a step """
if log:
step_end_time = self.log(u"STEP %d END (%s)" % (self.step_index, self.step_label))
diff = (step_end_time - self.step_begin_time)
diff = float(diff.seconds + diff.microseconds / 1000000.0)
self.step_total += diff
self.log(u"STEP %d DURATION %.3f (%s)" % (self.step_index, diff, self.step_label))
self.step_index += 1 | [
"def",
"_step_end",
"(",
"self",
",",
"log",
"=",
"True",
")",
":",
"if",
"log",
":",
"step_end_time",
"=",
"self",
".",
"log",
"(",
"u\"STEP %d END (%s)\"",
"%",
"(",
"self",
".",
"step_index",
",",
"self",
".",
"step_label",
")",
")",
"diff",
"=",
"(",
"step_end_time",
"-",
"self",
".",
"step_begin_time",
")",
"diff",
"=",
"float",
"(",
"diff",
".",
"seconds",
"+",
"diff",
".",
"microseconds",
"/",
"1000000.0",
")",
"self",
".",
"step_total",
"+=",
"diff",
"self",
".",
"log",
"(",
"u\"STEP %d DURATION %.3f (%s)\"",
"%",
"(",
"self",
".",
"step_index",
",",
"diff",
",",
"self",
".",
"step_label",
")",
")",
"self",
".",
"step_index",
"+=",
"1"
] | Log end of a step | [
"Log",
"end",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L115-L123 |
232,117 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_failure | def _step_failure(self, exc):
""" Log failure of a step """
self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
self.step_index += 1
self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError) | python | def _step_failure(self, exc):
""" Log failure of a step """
self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
self.step_index += 1
self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError) | [
"def",
"_step_failure",
"(",
"self",
",",
"exc",
")",
":",
"self",
".",
"log_crit",
"(",
"u\"STEP %d (%s) FAILURE\"",
"%",
"(",
"self",
".",
"step_index",
",",
"self",
".",
"step_label",
")",
")",
"self",
".",
"step_index",
"+=",
"1",
"self",
".",
"log_exc",
"(",
"u\"Unexpected error while executing task\"",
",",
"exc",
",",
"True",
",",
"ExecuteTaskExecutionError",
")"
] | Log failure of a step | [
"Log",
"failure",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L125-L129 |
232,118 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask.execute | def execute(self):
"""
Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution
"""
self.log(u"Executing task...")
# check that we have the AudioFile object
if self.task.audio_file is None:
self.log_exc(u"The task does not seem to have its audio file set", None, True, ExecuteTaskInputError)
if (
(self.task.audio_file.audio_length is None) or
(self.task.audio_file.audio_length <= 0)
):
self.log_exc(u"The task seems to have an invalid audio file", None, True, ExecuteTaskInputError)
task_max_audio_length = self.rconf[RuntimeConfiguration.TASK_MAX_AUDIO_LENGTH]
if (
(task_max_audio_length > 0) and
(self.task.audio_file.audio_length > task_max_audio_length)
):
self.log_exc(u"The audio file of the task has length %.3f, more than the maximum allowed (%.3f)." % (self.task.audio_file.audio_length, task_max_audio_length), None, True, ExecuteTaskInputError)
# check that we have the TextFile object
if self.task.text_file is None:
self.log_exc(u"The task does not seem to have its text file set", None, True, ExecuteTaskInputError)
if len(self.task.text_file) == 0:
self.log_exc(u"The task text file seems to have no text fragments", None, True, ExecuteTaskInputError)
task_max_text_length = self.rconf[RuntimeConfiguration.TASK_MAX_TEXT_LENGTH]
if (
(task_max_text_length > 0) and
(len(self.task.text_file) > task_max_text_length)
):
self.log_exc(u"The text file of the task has %d fragments, more than the maximum allowed (%d)." % (len(self.task.text_file), task_max_text_length), None, True, ExecuteTaskInputError)
if self.task.text_file.chars == 0:
self.log_exc(u"The task text file seems to have empty text", None, True, ExecuteTaskInputError)
self.log(u"Both audio and text input file are present")
# execute
self.step_index = 1
self.step_total = 0.000
if self.task.text_file.file_format in TextFileFormat.MULTILEVEL_VALUES:
self._execute_multi_level_task()
else:
self._execute_single_level_task()
self.log(u"Executing task... done") | python | def execute(self):
"""
Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution
"""
self.log(u"Executing task...")
# check that we have the AudioFile object
if self.task.audio_file is None:
self.log_exc(u"The task does not seem to have its audio file set", None, True, ExecuteTaskInputError)
if (
(self.task.audio_file.audio_length is None) or
(self.task.audio_file.audio_length <= 0)
):
self.log_exc(u"The task seems to have an invalid audio file", None, True, ExecuteTaskInputError)
task_max_audio_length = self.rconf[RuntimeConfiguration.TASK_MAX_AUDIO_LENGTH]
if (
(task_max_audio_length > 0) and
(self.task.audio_file.audio_length > task_max_audio_length)
):
self.log_exc(u"The audio file of the task has length %.3f, more than the maximum allowed (%.3f)." % (self.task.audio_file.audio_length, task_max_audio_length), None, True, ExecuteTaskInputError)
# check that we have the TextFile object
if self.task.text_file is None:
self.log_exc(u"The task does not seem to have its text file set", None, True, ExecuteTaskInputError)
if len(self.task.text_file) == 0:
self.log_exc(u"The task text file seems to have no text fragments", None, True, ExecuteTaskInputError)
task_max_text_length = self.rconf[RuntimeConfiguration.TASK_MAX_TEXT_LENGTH]
if (
(task_max_text_length > 0) and
(len(self.task.text_file) > task_max_text_length)
):
self.log_exc(u"The text file of the task has %d fragments, more than the maximum allowed (%d)." % (len(self.task.text_file), task_max_text_length), None, True, ExecuteTaskInputError)
if self.task.text_file.chars == 0:
self.log_exc(u"The task text file seems to have empty text", None, True, ExecuteTaskInputError)
self.log(u"Both audio and text input file are present")
# execute
self.step_index = 1
self.step_total = 0.000
if self.task.text_file.file_format in TextFileFormat.MULTILEVEL_VALUES:
self._execute_multi_level_task()
else:
self._execute_single_level_task()
self.log(u"Executing task... done") | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing task...\"",
")",
"# check that we have the AudioFile object",
"if",
"self",
".",
"task",
".",
"audio_file",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The task does not seem to have its audio file set\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"if",
"(",
"(",
"self",
".",
"task",
".",
"audio_file",
".",
"audio_length",
"is",
"None",
")",
"or",
"(",
"self",
".",
"task",
".",
"audio_file",
".",
"audio_length",
"<=",
"0",
")",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The task seems to have an invalid audio file\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"task_max_audio_length",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TASK_MAX_AUDIO_LENGTH",
"]",
"if",
"(",
"(",
"task_max_audio_length",
">",
"0",
")",
"and",
"(",
"self",
".",
"task",
".",
"audio_file",
".",
"audio_length",
">",
"task_max_audio_length",
")",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The audio file of the task has length %.3f, more than the maximum allowed (%.3f).\"",
"%",
"(",
"self",
".",
"task",
".",
"audio_file",
".",
"audio_length",
",",
"task_max_audio_length",
")",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"# check that we have the TextFile object",
"if",
"self",
".",
"task",
".",
"text_file",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The task does not seem to have its text file set\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"if",
"len",
"(",
"self",
".",
"task",
".",
"text_file",
")",
"==",
"0",
":",
"self",
".",
"log_exc",
"(",
"u\"The task text file seems to have no text fragments\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"task_max_text_length",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TASK_MAX_TEXT_LENGTH",
"]",
"if",
"(",
"(",
"task_max_text_length",
">",
"0",
")",
"and",
"(",
"len",
"(",
"self",
".",
"task",
".",
"text_file",
")",
">",
"task_max_text_length",
")",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The text file of the task has %d fragments, more than the maximum allowed (%d).\"",
"%",
"(",
"len",
"(",
"self",
".",
"task",
".",
"text_file",
")",
",",
"task_max_text_length",
")",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"if",
"self",
".",
"task",
".",
"text_file",
".",
"chars",
"==",
"0",
":",
"self",
".",
"log_exc",
"(",
"u\"The task text file seems to have empty text\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"self",
".",
"log",
"(",
"u\"Both audio and text input file are present\"",
")",
"# execute",
"self",
".",
"step_index",
"=",
"1",
"self",
".",
"step_total",
"=",
"0.000",
"if",
"self",
".",
"task",
".",
"text_file",
".",
"file_format",
"in",
"TextFileFormat",
".",
"MULTILEVEL_VALUES",
":",
"self",
".",
"_execute_multi_level_task",
"(",
")",
"else",
":",
"self",
".",
"_execute_single_level_task",
"(",
")",
"self",
".",
"log",
"(",
"u\"Executing task... done\"",
")"
] | Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution | [
"Execute",
"the",
"task",
".",
"The",
"sync",
"map",
"produced",
"will",
"be",
"stored",
"inside",
"the",
"task",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L135-L183 |
232,119 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_single_level_task | def _execute_single_level_task(self):
""" Execute a single-level task """
self.log(u"Executing single level task...")
try:
# load audio file, extract MFCCs from real wave, clear audio file
self._step_begin(u"extract MFCC real wave")
real_wave_mfcc = self._extract_mfcc(
file_path=self.task.audio_file_path_absolute,
file_format=None,
)
self._step_end()
# compute head and/or tail and set it
self._step_begin(u"compute head tail")
(head_length, process_length, tail_length) = self._compute_head_process_tail(real_wave_mfcc)
real_wave_mfcc.set_head_middle_tail(head_length, process_length, tail_length)
self._step_end()
# compute alignment, outputting a tree of time intervals
self._set_synthesizer()
sync_root = Tree()
self._execute_inner(
real_wave_mfcc,
self.task.text_file,
sync_root=sync_root,
force_aba_auto=False,
log=True,
leaf_level=True
)
self._clear_cache_synthesizer()
# create syncmap and add it to task
self._step_begin(u"create sync map")
self._create_sync_map(sync_root=sync_root)
self._step_end()
# log total
self._step_total()
self.log(u"Executing single level task... done")
except Exception as exc:
self._step_failure(exc) | python | def _execute_single_level_task(self):
""" Execute a single-level task """
self.log(u"Executing single level task...")
try:
# load audio file, extract MFCCs from real wave, clear audio file
self._step_begin(u"extract MFCC real wave")
real_wave_mfcc = self._extract_mfcc(
file_path=self.task.audio_file_path_absolute,
file_format=None,
)
self._step_end()
# compute head and/or tail and set it
self._step_begin(u"compute head tail")
(head_length, process_length, tail_length) = self._compute_head_process_tail(real_wave_mfcc)
real_wave_mfcc.set_head_middle_tail(head_length, process_length, tail_length)
self._step_end()
# compute alignment, outputting a tree of time intervals
self._set_synthesizer()
sync_root = Tree()
self._execute_inner(
real_wave_mfcc,
self.task.text_file,
sync_root=sync_root,
force_aba_auto=False,
log=True,
leaf_level=True
)
self._clear_cache_synthesizer()
# create syncmap and add it to task
self._step_begin(u"create sync map")
self._create_sync_map(sync_root=sync_root)
self._step_end()
# log total
self._step_total()
self.log(u"Executing single level task... done")
except Exception as exc:
self._step_failure(exc) | [
"def",
"_execute_single_level_task",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing single level task...\"",
")",
"try",
":",
"# load audio file, extract MFCCs from real wave, clear audio file",
"self",
".",
"_step_begin",
"(",
"u\"extract MFCC real wave\"",
")",
"real_wave_mfcc",
"=",
"self",
".",
"_extract_mfcc",
"(",
"file_path",
"=",
"self",
".",
"task",
".",
"audio_file_path_absolute",
",",
"file_format",
"=",
"None",
",",
")",
"self",
".",
"_step_end",
"(",
")",
"# compute head and/or tail and set it",
"self",
".",
"_step_begin",
"(",
"u\"compute head tail\"",
")",
"(",
"head_length",
",",
"process_length",
",",
"tail_length",
")",
"=",
"self",
".",
"_compute_head_process_tail",
"(",
"real_wave_mfcc",
")",
"real_wave_mfcc",
".",
"set_head_middle_tail",
"(",
"head_length",
",",
"process_length",
",",
"tail_length",
")",
"self",
".",
"_step_end",
"(",
")",
"# compute alignment, outputting a tree of time intervals",
"self",
".",
"_set_synthesizer",
"(",
")",
"sync_root",
"=",
"Tree",
"(",
")",
"self",
".",
"_execute_inner",
"(",
"real_wave_mfcc",
",",
"self",
".",
"task",
".",
"text_file",
",",
"sync_root",
"=",
"sync_root",
",",
"force_aba_auto",
"=",
"False",
",",
"log",
"=",
"True",
",",
"leaf_level",
"=",
"True",
")",
"self",
".",
"_clear_cache_synthesizer",
"(",
")",
"# create syncmap and add it to task",
"self",
".",
"_step_begin",
"(",
"u\"create sync map\"",
")",
"self",
".",
"_create_sync_map",
"(",
"sync_root",
"=",
"sync_root",
")",
"self",
".",
"_step_end",
"(",
")",
"# log total",
"self",
".",
"_step_total",
"(",
")",
"self",
".",
"log",
"(",
"u\"Executing single level task... done\"",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"_step_failure",
"(",
"exc",
")"
] | Execute a single-level task | [
"Execute",
"a",
"single",
"-",
"level",
"task"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L185-L225 |
232,120 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_level | def _execute_level(self, level, audio_file_mfcc, text_files, sync_roots, force_aba_auto=False):
"""
Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list)
"""
self._set_synthesizer()
next_level_text_files = []
next_level_sync_roots = []
for text_file_index, text_file in enumerate(text_files):
self.log([u"Text level %d, fragment %d", level, text_file_index])
self.log([u" Len: %d", len(text_file)])
sync_root = sync_roots[text_file_index]
if (level > 1) and (len(text_file) == 1):
self.log(u"Level > 1 and only one text fragment => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
elif (level > 1) and (sync_root.value.begin == sync_root.value.end):
self.log(u"Level > 1 and parent has begin == end => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
else:
self.log(u"Level == 1 or more than one text fragment with non-zero parent => compute tree")
if not sync_root.is_empty:
begin = sync_root.value.begin
end = sync_root.value.end
self.log([u" Setting begin: %.3f", begin])
self.log([u" Setting end: %.3f", end])
audio_file_mfcc.set_head_middle_tail(head_length=begin, middle_length=(end - begin))
else:
self.log(u" No begin or end to set")
self._execute_inner(
audio_file_mfcc,
text_file,
sync_root=sync_root,
force_aba_auto=force_aba_auto,
log=False,
leaf_level=(level == 3)
)
# store next level roots
next_level_text_files.extend(text_file.children_not_empty)
# we added head and tail, we must not pass them to the next level
next_level_sync_roots.extend(sync_root.children[1:-1])
self._clear_cache_synthesizer()
return (next_level_text_files, next_level_sync_roots) | python | def _execute_level(self, level, audio_file_mfcc, text_files, sync_roots, force_aba_auto=False):
"""
Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list)
"""
self._set_synthesizer()
next_level_text_files = []
next_level_sync_roots = []
for text_file_index, text_file in enumerate(text_files):
self.log([u"Text level %d, fragment %d", level, text_file_index])
self.log([u" Len: %d", len(text_file)])
sync_root = sync_roots[text_file_index]
if (level > 1) and (len(text_file) == 1):
self.log(u"Level > 1 and only one text fragment => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
elif (level > 1) and (sync_root.value.begin == sync_root.value.end):
self.log(u"Level > 1 and parent has begin == end => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
else:
self.log(u"Level == 1 or more than one text fragment with non-zero parent => compute tree")
if not sync_root.is_empty:
begin = sync_root.value.begin
end = sync_root.value.end
self.log([u" Setting begin: %.3f", begin])
self.log([u" Setting end: %.3f", end])
audio_file_mfcc.set_head_middle_tail(head_length=begin, middle_length=(end - begin))
else:
self.log(u" No begin or end to set")
self._execute_inner(
audio_file_mfcc,
text_file,
sync_root=sync_root,
force_aba_auto=force_aba_auto,
log=False,
leaf_level=(level == 3)
)
# store next level roots
next_level_text_files.extend(text_file.children_not_empty)
# we added head and tail, we must not pass them to the next level
next_level_sync_roots.extend(sync_root.children[1:-1])
self._clear_cache_synthesizer()
return (next_level_text_files, next_level_sync_roots) | [
"def",
"_execute_level",
"(",
"self",
",",
"level",
",",
"audio_file_mfcc",
",",
"text_files",
",",
"sync_roots",
",",
"force_aba_auto",
"=",
"False",
")",
":",
"self",
".",
"_set_synthesizer",
"(",
")",
"next_level_text_files",
"=",
"[",
"]",
"next_level_sync_roots",
"=",
"[",
"]",
"for",
"text_file_index",
",",
"text_file",
"in",
"enumerate",
"(",
"text_files",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Text level %d, fragment %d\"",
",",
"level",
",",
"text_file_index",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" Len: %d\"",
",",
"len",
"(",
"text_file",
")",
"]",
")",
"sync_root",
"=",
"sync_roots",
"[",
"text_file_index",
"]",
"if",
"(",
"level",
">",
"1",
")",
"and",
"(",
"len",
"(",
"text_file",
")",
"==",
"1",
")",
":",
"self",
".",
"log",
"(",
"u\"Level > 1 and only one text fragment => return trivial tree\"",
")",
"self",
".",
"_append_trivial_tree",
"(",
"text_file",
",",
"sync_root",
")",
"elif",
"(",
"level",
">",
"1",
")",
"and",
"(",
"sync_root",
".",
"value",
".",
"begin",
"==",
"sync_root",
".",
"value",
".",
"end",
")",
":",
"self",
".",
"log",
"(",
"u\"Level > 1 and parent has begin == end => return trivial tree\"",
")",
"self",
".",
"_append_trivial_tree",
"(",
"text_file",
",",
"sync_root",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Level == 1 or more than one text fragment with non-zero parent => compute tree\"",
")",
"if",
"not",
"sync_root",
".",
"is_empty",
":",
"begin",
"=",
"sync_root",
".",
"value",
".",
"begin",
"end",
"=",
"sync_root",
".",
"value",
".",
"end",
"self",
".",
"log",
"(",
"[",
"u\" Setting begin: %.3f\"",
",",
"begin",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" Setting end: %.3f\"",
",",
"end",
"]",
")",
"audio_file_mfcc",
".",
"set_head_middle_tail",
"(",
"head_length",
"=",
"begin",
",",
"middle_length",
"=",
"(",
"end",
"-",
"begin",
")",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\" No begin or end to set\"",
")",
"self",
".",
"_execute_inner",
"(",
"audio_file_mfcc",
",",
"text_file",
",",
"sync_root",
"=",
"sync_root",
",",
"force_aba_auto",
"=",
"force_aba_auto",
",",
"log",
"=",
"False",
",",
"leaf_level",
"=",
"(",
"level",
"==",
"3",
")",
")",
"# store next level roots",
"next_level_text_files",
".",
"extend",
"(",
"text_file",
".",
"children_not_empty",
")",
"# we added head and tail, we must not pass them to the next level",
"next_level_sync_roots",
".",
"extend",
"(",
"sync_root",
".",
"children",
"[",
"1",
":",
"-",
"1",
"]",
")",
"self",
".",
"_clear_cache_synthesizer",
"(",
")",
"return",
"(",
"next_level_text_files",
",",
"next_level_sync_roots",
")"
] | Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list) | [
"Compute",
"the",
"alignment",
"for",
"all",
"the",
"nodes",
"in",
"the",
"given",
"level",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L303-L358 |
232,121 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_inner | def _execute_inner(self, audio_file_mfcc, text_file, sync_root=None, force_aba_auto=False, log=True, leaf_level=False):
"""
Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree`
"""
self._step_begin(u"synthesize text", log=log)
synt_handler, synt_path, synt_anchors, synt_format = self._synthesize(text_file)
self._step_end(log=log)
self._step_begin(u"extract MFCC synt wave", log=log)
synt_wave_mfcc = self._extract_mfcc(
file_path=synt_path,
file_format=synt_format,
)
gf.delete_file(synt_handler, synt_path)
self._step_end(log=log)
self._step_begin(u"align waves", log=log)
indices = self._align_waves(audio_file_mfcc, synt_wave_mfcc, synt_anchors)
self._step_end(log=log)
self._step_begin(u"adjust boundaries", log=log)
self._adjust_boundaries(indices, text_file, audio_file_mfcc, sync_root, force_aba_auto, leaf_level)
self._step_end(log=log) | python | def _execute_inner(self, audio_file_mfcc, text_file, sync_root=None, force_aba_auto=False, log=True, leaf_level=False):
"""
Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree`
"""
self._step_begin(u"synthesize text", log=log)
synt_handler, synt_path, synt_anchors, synt_format = self._synthesize(text_file)
self._step_end(log=log)
self._step_begin(u"extract MFCC synt wave", log=log)
synt_wave_mfcc = self._extract_mfcc(
file_path=synt_path,
file_format=synt_format,
)
gf.delete_file(synt_handler, synt_path)
self._step_end(log=log)
self._step_begin(u"align waves", log=log)
indices = self._align_waves(audio_file_mfcc, synt_wave_mfcc, synt_anchors)
self._step_end(log=log)
self._step_begin(u"adjust boundaries", log=log)
self._adjust_boundaries(indices, text_file, audio_file_mfcc, sync_root, force_aba_auto, leaf_level)
self._step_end(log=log) | [
"def",
"_execute_inner",
"(",
"self",
",",
"audio_file_mfcc",
",",
"text_file",
",",
"sync_root",
"=",
"None",
",",
"force_aba_auto",
"=",
"False",
",",
"log",
"=",
"True",
",",
"leaf_level",
"=",
"False",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"synthesize text\"",
",",
"log",
"=",
"log",
")",
"synt_handler",
",",
"synt_path",
",",
"synt_anchors",
",",
"synt_format",
"=",
"self",
".",
"_synthesize",
"(",
"text_file",
")",
"self",
".",
"_step_end",
"(",
"log",
"=",
"log",
")",
"self",
".",
"_step_begin",
"(",
"u\"extract MFCC synt wave\"",
",",
"log",
"=",
"log",
")",
"synt_wave_mfcc",
"=",
"self",
".",
"_extract_mfcc",
"(",
"file_path",
"=",
"synt_path",
",",
"file_format",
"=",
"synt_format",
",",
")",
"gf",
".",
"delete_file",
"(",
"synt_handler",
",",
"synt_path",
")",
"self",
".",
"_step_end",
"(",
"log",
"=",
"log",
")",
"self",
".",
"_step_begin",
"(",
"u\"align waves\"",
",",
"log",
"=",
"log",
")",
"indices",
"=",
"self",
".",
"_align_waves",
"(",
"audio_file_mfcc",
",",
"synt_wave_mfcc",
",",
"synt_anchors",
")",
"self",
".",
"_step_end",
"(",
"log",
"=",
"log",
")",
"self",
".",
"_step_begin",
"(",
"u\"adjust boundaries\"",
",",
"log",
"=",
"log",
")",
"self",
".",
"_adjust_boundaries",
"(",
"indices",
",",
"text_file",
",",
"audio_file_mfcc",
",",
"sync_root",
",",
"force_aba_auto",
",",
"leaf_level",
")",
"self",
".",
"_step_end",
"(",
"log",
"=",
"log",
")"
] | Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree` | [
"Align",
"a",
"subinterval",
"of",
"the",
"given",
"AudioFileMFCC",
"with",
"the",
"given",
"TextFile",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L360-L403 |
232,122 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._load_audio_file | def _load_audio_file(self):
"""
Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"load audio file")
# NOTE file_format=None forces conversion to
# PCM16 mono WAVE with default sample rate
audio_file = AudioFile(
file_path=self.task.audio_file_path_absolute,
file_format=None,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self._step_end()
return audio_file | python | def _load_audio_file(self):
"""
Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"load audio file")
# NOTE file_format=None forces conversion to
# PCM16 mono WAVE with default sample rate
audio_file = AudioFile(
file_path=self.task.audio_file_path_absolute,
file_format=None,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self._step_end()
return audio_file | [
"def",
"_load_audio_file",
"(",
"self",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"load audio file\"",
")",
"# NOTE file_format=None forces conversion to",
"# PCM16 mono WAVE with default sample rate",
"audio_file",
"=",
"AudioFile",
"(",
"file_path",
"=",
"self",
".",
"task",
".",
"audio_file_path_absolute",
",",
"file_format",
"=",
"None",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"audio_file",
".",
"read_samples_from_file",
"(",
")",
"self",
".",
"_step_end",
"(",
")",
"return",
"audio_file"
] | Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile` | [
"Load",
"audio",
"in",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L405-L422 |
232,123 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._clear_audio_file | def _clear_audio_file(self, audio_file):
"""
Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"clear audio file")
audio_file.clear_data()
audio_file = None
self._step_end() | python | def _clear_audio_file(self, audio_file):
"""
Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"clear audio file")
audio_file.clear_data()
audio_file = None
self._step_end() | [
"def",
"_clear_audio_file",
"(",
"self",
",",
"audio_file",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"clear audio file\"",
")",
"audio_file",
".",
"clear_data",
"(",
")",
"audio_file",
"=",
"None",
"self",
".",
"_step_end",
"(",
")"
] | Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile` | [
"Clear",
"audio",
"from",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L424-L434 |
232,124 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._extract_mfcc | def _extract_mfcc(self, file_path=None, file_format=None, audio_file=None):
"""
Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
"""
audio_file_mfcc = AudioFileMFCC(
file_path=file_path,
file_format=file_format,
audio_file=audio_file,
rconf=self.rconf,
logger=self.logger
)
if self.rconf.mmn:
self.log(u"Running VAD inside _extract_mfcc...")
audio_file_mfcc.run_vad(
log_energy_threshold=self.rconf[RuntimeConfiguration.MFCC_MASK_LOG_ENERGY_THRESHOLD],
min_nonspeech_length=self.rconf[RuntimeConfiguration.MFCC_MASK_MIN_NONSPEECH_LENGTH],
extend_before=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_BEFORE],
extend_after=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_AFTER]
)
self.log(u"Running VAD inside _extract_mfcc... done")
return audio_file_mfcc | python | def _extract_mfcc(self, file_path=None, file_format=None, audio_file=None):
"""
Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
"""
audio_file_mfcc = AudioFileMFCC(
file_path=file_path,
file_format=file_format,
audio_file=audio_file,
rconf=self.rconf,
logger=self.logger
)
if self.rconf.mmn:
self.log(u"Running VAD inside _extract_mfcc...")
audio_file_mfcc.run_vad(
log_energy_threshold=self.rconf[RuntimeConfiguration.MFCC_MASK_LOG_ENERGY_THRESHOLD],
min_nonspeech_length=self.rconf[RuntimeConfiguration.MFCC_MASK_MIN_NONSPEECH_LENGTH],
extend_before=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_BEFORE],
extend_after=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_AFTER]
)
self.log(u"Running VAD inside _extract_mfcc... done")
return audio_file_mfcc | [
"def",
"_extract_mfcc",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"file_format",
"=",
"None",
",",
"audio_file",
"=",
"None",
")",
":",
"audio_file_mfcc",
"=",
"AudioFileMFCC",
"(",
"file_path",
"=",
"file_path",
",",
"file_format",
"=",
"file_format",
",",
"audio_file",
"=",
"audio_file",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"if",
"self",
".",
"rconf",
".",
"mmn",
":",
"self",
".",
"log",
"(",
"u\"Running VAD inside _extract_mfcc...\"",
")",
"audio_file_mfcc",
".",
"run_vad",
"(",
"log_energy_threshold",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"MFCC_MASK_LOG_ENERGY_THRESHOLD",
"]",
",",
"min_nonspeech_length",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"MFCC_MASK_MIN_NONSPEECH_LENGTH",
"]",
",",
"extend_before",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"MFCC_MASK_EXTEND_SPEECH_INTERVAL_BEFORE",
"]",
",",
"extend_after",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"MFCC_MASK_EXTEND_SPEECH_INTERVAL_AFTER",
"]",
")",
"self",
".",
"log",
"(",
"u\"Running VAD inside _extract_mfcc... done\"",
")",
"return",
"audio_file_mfcc"
] | Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC` | [
"Extract",
"the",
"MFCCs",
"from",
"the",
"given",
"audio",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L436-L458 |
232,125 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._compute_head_process_tail | def _compute_head_process_tail(self, audio_file_mfcc):
"""
Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float)
"""
head_length = self.task.configuration["i_a_head"]
process_length = self.task.configuration["i_a_process"]
tail_length = self.task.configuration["i_a_tail"]
head_max = self.task.configuration["i_a_head_max"]
head_min = self.task.configuration["i_a_head_min"]
tail_max = self.task.configuration["i_a_tail_max"]
tail_min = self.task.configuration["i_a_tail_min"]
if (
(head_length is not None) or
(process_length is not None) or
(tail_length is not None)
):
self.log(u"Setting explicit head process tail")
else:
self.log(u"Detecting head tail...")
sd = SD(audio_file_mfcc, self.task.text_file, rconf=self.rconf, logger=self.logger)
head_length = TimeValue("0.000")
process_length = None
tail_length = TimeValue("0.000")
if (head_min is not None) or (head_max is not None):
self.log(u"Detecting HEAD...")
head_length = sd.detect_head(head_min, head_max)
self.log([u"Detected HEAD: %.3f", head_length])
self.log(u"Detecting HEAD... done")
if (tail_min is not None) or (tail_max is not None):
self.log(u"Detecting TAIL...")
tail_length = sd.detect_tail(tail_min, tail_max)
self.log([u"Detected TAIL: %.3f", tail_length])
self.log(u"Detecting TAIL... done")
self.log(u"Detecting head tail... done")
self.log([u"Head: %s", gf.safe_float(head_length, None)])
self.log([u"Process: %s", gf.safe_float(process_length, None)])
self.log([u"Tail: %s", gf.safe_float(tail_length, None)])
return (head_length, process_length, tail_length) | python | def _compute_head_process_tail(self, audio_file_mfcc):
"""
Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float)
"""
head_length = self.task.configuration["i_a_head"]
process_length = self.task.configuration["i_a_process"]
tail_length = self.task.configuration["i_a_tail"]
head_max = self.task.configuration["i_a_head_max"]
head_min = self.task.configuration["i_a_head_min"]
tail_max = self.task.configuration["i_a_tail_max"]
tail_min = self.task.configuration["i_a_tail_min"]
if (
(head_length is not None) or
(process_length is not None) or
(tail_length is not None)
):
self.log(u"Setting explicit head process tail")
else:
self.log(u"Detecting head tail...")
sd = SD(audio_file_mfcc, self.task.text_file, rconf=self.rconf, logger=self.logger)
head_length = TimeValue("0.000")
process_length = None
tail_length = TimeValue("0.000")
if (head_min is not None) or (head_max is not None):
self.log(u"Detecting HEAD...")
head_length = sd.detect_head(head_min, head_max)
self.log([u"Detected HEAD: %.3f", head_length])
self.log(u"Detecting HEAD... done")
if (tail_min is not None) or (tail_max is not None):
self.log(u"Detecting TAIL...")
tail_length = sd.detect_tail(tail_min, tail_max)
self.log([u"Detected TAIL: %.3f", tail_length])
self.log(u"Detecting TAIL... done")
self.log(u"Detecting head tail... done")
self.log([u"Head: %s", gf.safe_float(head_length, None)])
self.log([u"Process: %s", gf.safe_float(process_length, None)])
self.log([u"Tail: %s", gf.safe_float(tail_length, None)])
return (head_length, process_length, tail_length) | [
"def",
"_compute_head_process_tail",
"(",
"self",
",",
"audio_file_mfcc",
")",
":",
"head_length",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_head\"",
"]",
"process_length",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_process\"",
"]",
"tail_length",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_tail\"",
"]",
"head_max",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_head_max\"",
"]",
"head_min",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_head_min\"",
"]",
"tail_max",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_tail_max\"",
"]",
"tail_min",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_tail_min\"",
"]",
"if",
"(",
"(",
"head_length",
"is",
"not",
"None",
")",
"or",
"(",
"process_length",
"is",
"not",
"None",
")",
"or",
"(",
"tail_length",
"is",
"not",
"None",
")",
")",
":",
"self",
".",
"log",
"(",
"u\"Setting explicit head process tail\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Detecting head tail...\"",
")",
"sd",
"=",
"SD",
"(",
"audio_file_mfcc",
",",
"self",
".",
"task",
".",
"text_file",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"head_length",
"=",
"TimeValue",
"(",
"\"0.000\"",
")",
"process_length",
"=",
"None",
"tail_length",
"=",
"TimeValue",
"(",
"\"0.000\"",
")",
"if",
"(",
"head_min",
"is",
"not",
"None",
")",
"or",
"(",
"head_max",
"is",
"not",
"None",
")",
":",
"self",
".",
"log",
"(",
"u\"Detecting HEAD...\"",
")",
"head_length",
"=",
"sd",
".",
"detect_head",
"(",
"head_min",
",",
"head_max",
")",
"self",
".",
"log",
"(",
"[",
"u\"Detected HEAD: %.3f\"",
",",
"head_length",
"]",
")",
"self",
".",
"log",
"(",
"u\"Detecting HEAD... done\"",
")",
"if",
"(",
"tail_min",
"is",
"not",
"None",
")",
"or",
"(",
"tail_max",
"is",
"not",
"None",
")",
":",
"self",
".",
"log",
"(",
"u\"Detecting TAIL...\"",
")",
"tail_length",
"=",
"sd",
".",
"detect_tail",
"(",
"tail_min",
",",
"tail_max",
")",
"self",
".",
"log",
"(",
"[",
"u\"Detected TAIL: %.3f\"",
",",
"tail_length",
"]",
")",
"self",
".",
"log",
"(",
"u\"Detecting TAIL... done\"",
")",
"self",
".",
"log",
"(",
"u\"Detecting head tail... done\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Head: %s\"",
",",
"gf",
".",
"safe_float",
"(",
"head_length",
",",
"None",
")",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Process: %s\"",
",",
"gf",
".",
"safe_float",
"(",
"process_length",
",",
"None",
")",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Tail: %s\"",
",",
"gf",
".",
"safe_float",
"(",
"tail_length",
",",
"None",
")",
"]",
")",
"return",
"(",
"head_length",
",",
"process_length",
",",
"tail_length",
")"
] | Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float) | [
"Set",
"the",
"audio",
"file",
"head",
"or",
"tail",
"by",
"either",
"reading",
"the",
"explicit",
"values",
"from",
"the",
"Task",
"configuration",
"or",
"using",
"SD",
"to",
"determine",
"them",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L460-L505 |
232,126 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._clear_cache_synthesizer | def _clear_cache_synthesizer(self):
""" Clear the cache of the synthesizer """
self.log(u"Clearing synthesizer...")
self.synthesizer.clear_cache()
self.log(u"Clearing synthesizer... done") | python | def _clear_cache_synthesizer(self):
""" Clear the cache of the synthesizer """
self.log(u"Clearing synthesizer...")
self.synthesizer.clear_cache()
self.log(u"Clearing synthesizer... done") | [
"def",
"_clear_cache_synthesizer",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Clearing synthesizer...\"",
")",
"self",
".",
"synthesizer",
".",
"clear_cache",
"(",
")",
"self",
".",
"log",
"(",
"u\"Clearing synthesizer... done\"",
")"
] | Clear the cache of the synthesizer | [
"Clear",
"the",
"cache",
"of",
"the",
"synthesizer"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L513-L517 |
232,127 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._synthesize | def _synthesize(self, text_file):
"""
Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list)
"""
handler, path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
result = self.synthesizer.synthesize(text_file, path)
return (handler, path, result[0], self.synthesizer.output_audio_format) | python | def _synthesize(self, text_file):
"""
Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list)
"""
handler, path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
result = self.synthesizer.synthesize(text_file, path)
return (handler, path, result[0], self.synthesizer.output_audio_format) | [
"def",
"_synthesize",
"(",
"self",
",",
"text_file",
")",
":",
"handler",
",",
"path",
"=",
"gf",
".",
"tmp_file",
"(",
"suffix",
"=",
"u\".wav\"",
",",
"root",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TMP_PATH",
"]",
")",
"result",
"=",
"self",
".",
"synthesizer",
".",
"synthesize",
"(",
"text_file",
",",
"path",
")",
"return",
"(",
"handler",
",",
"path",
",",
"result",
"[",
"0",
"]",
",",
"self",
".",
"synthesizer",
".",
"output_audio_format",
")"
] | Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list) | [
"Synthesize",
"text",
"into",
"a",
"WAVE",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L519-L539 |
232,128 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._align_waves | def _align_waves(self, real_wave_mfcc, synt_wave_mfcc, synt_anchors):
"""
Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices.
"""
self.log(u"Creating DTWAligner...")
aligner = DTWAligner(
real_wave_mfcc,
synt_wave_mfcc,
rconf=self.rconf,
logger=self.logger
)
self.log(u"Creating DTWAligner... done")
self.log(u"Computing boundary indices...")
boundary_indices = aligner.compute_boundaries(synt_anchors)
self.log(u"Computing boundary indices... done")
return boundary_indices | python | def _align_waves(self, real_wave_mfcc, synt_wave_mfcc, synt_anchors):
"""
Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices.
"""
self.log(u"Creating DTWAligner...")
aligner = DTWAligner(
real_wave_mfcc,
synt_wave_mfcc,
rconf=self.rconf,
logger=self.logger
)
self.log(u"Creating DTWAligner... done")
self.log(u"Computing boundary indices...")
boundary_indices = aligner.compute_boundaries(synt_anchors)
self.log(u"Computing boundary indices... done")
return boundary_indices | [
"def",
"_align_waves",
"(",
"self",
",",
"real_wave_mfcc",
",",
"synt_wave_mfcc",
",",
"synt_anchors",
")",
":",
"self",
".",
"log",
"(",
"u\"Creating DTWAligner...\"",
")",
"aligner",
"=",
"DTWAligner",
"(",
"real_wave_mfcc",
",",
"synt_wave_mfcc",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"log",
"(",
"u\"Creating DTWAligner... done\"",
")",
"self",
".",
"log",
"(",
"u\"Computing boundary indices...\"",
")",
"boundary_indices",
"=",
"aligner",
".",
"compute_boundaries",
"(",
"synt_anchors",
")",
"self",
".",
"log",
"(",
"u\"Computing boundary indices... done\"",
")",
"return",
"boundary_indices"
] | Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices. | [
"Align",
"two",
"AudioFileMFCC",
"objects",
"representing",
"WAVE",
"files",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L541-L559 |
232,129 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._adjust_boundaries | def _adjust_boundaries(self, boundary_indices, text_file, real_wave_mfcc, sync_root, force_aba_auto=False, leaf_level=False):
"""
Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last).
"""
# boundary_indices contains the boundary indices in the all_mfcc of real_wave_mfcc
# starting with the (head-1st fragment) and ending with (-1th fragment-tail)
aba_parameters = self.task.configuration.aba_parameters()
if force_aba_auto:
self.log(u"Forced running algorithm: 'auto'")
aba_parameters["algorithm"] = (AdjustBoundaryAlgorithm.AUTO, [])
# note that the other aba settings (nonspeech and nozero)
# remain as specified by the user
self.log([u"ABA parameters: %s", aba_parameters])
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.adjust(
aba_parameters=aba_parameters,
real_wave_mfcc=real_wave_mfcc,
boundary_indices=boundary_indices,
text_file=text_file,
allow_arbitrary_shift=leaf_level
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | python | def _adjust_boundaries(self, boundary_indices, text_file, real_wave_mfcc, sync_root, force_aba_auto=False, leaf_level=False):
"""
Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last).
"""
# boundary_indices contains the boundary indices in the all_mfcc of real_wave_mfcc
# starting with the (head-1st fragment) and ending with (-1th fragment-tail)
aba_parameters = self.task.configuration.aba_parameters()
if force_aba_auto:
self.log(u"Forced running algorithm: 'auto'")
aba_parameters["algorithm"] = (AdjustBoundaryAlgorithm.AUTO, [])
# note that the other aba settings (nonspeech and nozero)
# remain as specified by the user
self.log([u"ABA parameters: %s", aba_parameters])
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.adjust(
aba_parameters=aba_parameters,
real_wave_mfcc=real_wave_mfcc,
boundary_indices=boundary_indices,
text_file=text_file,
allow_arbitrary_shift=leaf_level
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | [
"def",
"_adjust_boundaries",
"(",
"self",
",",
"boundary_indices",
",",
"text_file",
",",
"real_wave_mfcc",
",",
"sync_root",
",",
"force_aba_auto",
"=",
"False",
",",
"leaf_level",
"=",
"False",
")",
":",
"# boundary_indices contains the boundary indices in the all_mfcc of real_wave_mfcc",
"# starting with the (head-1st fragment) and ending with (-1th fragment-tail)",
"aba_parameters",
"=",
"self",
".",
"task",
".",
"configuration",
".",
"aba_parameters",
"(",
")",
"if",
"force_aba_auto",
":",
"self",
".",
"log",
"(",
"u\"Forced running algorithm: 'auto'\"",
")",
"aba_parameters",
"[",
"\"algorithm\"",
"]",
"=",
"(",
"AdjustBoundaryAlgorithm",
".",
"AUTO",
",",
"[",
"]",
")",
"# note that the other aba settings (nonspeech and nozero)",
"# remain as specified by the user",
"self",
".",
"log",
"(",
"[",
"u\"ABA parameters: %s\"",
",",
"aba_parameters",
"]",
")",
"aba",
"=",
"AdjustBoundaryAlgorithm",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"aba",
".",
"adjust",
"(",
"aba_parameters",
"=",
"aba_parameters",
",",
"real_wave_mfcc",
"=",
"real_wave_mfcc",
",",
"boundary_indices",
"=",
"boundary_indices",
",",
"text_file",
"=",
"text_file",
",",
"allow_arbitrary_shift",
"=",
"leaf_level",
")",
"aba",
".",
"append_fragment_list_to_sync_root",
"(",
"sync_root",
"=",
"sync_root",
")"
] | Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last). | [
"Adjust",
"boundaries",
"as",
"requested",
"by",
"the",
"user",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L561-L588 |
232,130 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._append_trivial_tree | def _append_trivial_tree(self, text_file, sync_root):
"""
Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``).
"""
interval = sync_root.value
#
# NOTE the following is correct, but it is a bit obscure
# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2
#
if len(text_file) == 1:
time_values = [interval.begin, interval.begin, interval.end, interval.end]
else:
# interval.begin == interval.end
time_values = [interval.begin] * (3 + len(text_file))
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | python | def _append_trivial_tree(self, text_file, sync_root):
"""
Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``).
"""
interval = sync_root.value
#
# NOTE the following is correct, but it is a bit obscure
# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2
#
if len(text_file) == 1:
time_values = [interval.begin, interval.begin, interval.end, interval.end]
else:
# interval.begin == interval.end
time_values = [interval.begin] * (3 + len(text_file))
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | [
"def",
"_append_trivial_tree",
"(",
"self",
",",
"text_file",
",",
"sync_root",
")",
":",
"interval",
"=",
"sync_root",
".",
"value",
"#",
"# NOTE the following is correct, but it is a bit obscure",
"# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2",
"#",
"if",
"len",
"(",
"text_file",
")",
"==",
"1",
":",
"time_values",
"=",
"[",
"interval",
".",
"begin",
",",
"interval",
".",
"begin",
",",
"interval",
".",
"end",
",",
"interval",
".",
"end",
"]",
"else",
":",
"# interval.begin == interval.end",
"time_values",
"=",
"[",
"interval",
".",
"begin",
"]",
"*",
"(",
"3",
"+",
"len",
"(",
"text_file",
")",
")",
"aba",
"=",
"AdjustBoundaryAlgorithm",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"aba",
".",
"intervals_to_fragment_list",
"(",
"text_file",
"=",
"text_file",
",",
"time_values",
"=",
"time_values",
")",
"aba",
".",
"append_fragment_list_to_sync_root",
"(",
"sync_root",
"=",
"sync_root",
")"
] | Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``). | [
"Append",
"trivial",
"tree",
"made",
"by",
"one",
"HEAD",
"one",
"sync",
"map",
"fragment",
"for",
"each",
"element",
"of",
"text_file",
"and",
"one",
"TAIL",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L590-L615 |
232,131 | readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._create_sync_map | def _create_sync_map(self, sync_root):
"""
If requested, check that the computed sync map is consistent.
Then, add it to the Task.
"""
sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
if self.rconf.safety_checks:
self.log(u"Running sanity check on computed sync map...")
if not sync_map.leaves_are_consistent:
self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
self.log(u"Running sanity check on computed sync map... passed")
else:
self.log(u"Not running sanity check on computed sync map")
self.task.sync_map = sync_map | python | def _create_sync_map(self, sync_root):
"""
If requested, check that the computed sync map is consistent.
Then, add it to the Task.
"""
sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
if self.rconf.safety_checks:
self.log(u"Running sanity check on computed sync map...")
if not sync_map.leaves_are_consistent:
self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
self.log(u"Running sanity check on computed sync map... passed")
else:
self.log(u"Not running sanity check on computed sync map")
self.task.sync_map = sync_map | [
"def",
"_create_sync_map",
"(",
"self",
",",
"sync_root",
")",
":",
"sync_map",
"=",
"SyncMap",
"(",
"tree",
"=",
"sync_root",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"if",
"self",
".",
"rconf",
".",
"safety_checks",
":",
"self",
".",
"log",
"(",
"u\"Running sanity check on computed sync map...\"",
")",
"if",
"not",
"sync_map",
".",
"leaves_are_consistent",
":",
"self",
".",
"_step_failure",
"(",
"ValueError",
"(",
"u\"The computed sync map contains inconsistent fragments\"",
")",
")",
"self",
".",
"log",
"(",
"u\"Running sanity check on computed sync map... passed\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Not running sanity check on computed sync map\"",
")",
"self",
".",
"task",
".",
"sync_map",
"=",
"sync_map"
] | If requested, check that the computed sync map is consistent.
Then, add it to the Task. | [
"If",
"requested",
"check",
"that",
"the",
"computed",
"sync",
"map",
"is",
"consistent",
".",
"Then",
"add",
"it",
"to",
"the",
"Task",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L617-L630 |
232,132 | readbeyond/aeneas | aeneas/sd.py | SD.detect_interval | def detect_interval(
self,
min_head_length=None,
max_head_length=None,
min_tail_length=None,
max_tail_length=None
):
"""
Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
head = self.detect_head(min_head_length, max_head_length)
tail = self.detect_tail(min_tail_length, max_tail_length)
begin = head
end = self.real_wave_mfcc.audio_length - tail
self.log([u"Audio length: %.3f", self.real_wave_mfcc.audio_length])
self.log([u"Head length: %.3f", head])
self.log([u"Tail length: %.3f", tail])
self.log([u"Begin: %.3f", begin])
self.log([u"End: %.3f", end])
if (begin >= TimeValue("0.000")) and (end > begin):
self.log([u"Returning %.3f %.3f", begin, end])
return (begin, end)
self.log(u"Returning (0.000, 0.000)")
return (TimeValue("0.000"), TimeValue("0.000")) | python | def detect_interval(
self,
min_head_length=None,
max_head_length=None,
min_tail_length=None,
max_tail_length=None
):
"""
Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
head = self.detect_head(min_head_length, max_head_length)
tail = self.detect_tail(min_tail_length, max_tail_length)
begin = head
end = self.real_wave_mfcc.audio_length - tail
self.log([u"Audio length: %.3f", self.real_wave_mfcc.audio_length])
self.log([u"Head length: %.3f", head])
self.log([u"Tail length: %.3f", tail])
self.log([u"Begin: %.3f", begin])
self.log([u"End: %.3f", end])
if (begin >= TimeValue("0.000")) and (end > begin):
self.log([u"Returning %.3f %.3f", begin, end])
return (begin, end)
self.log(u"Returning (0.000, 0.000)")
return (TimeValue("0.000"), TimeValue("0.000")) | [
"def",
"detect_interval",
"(",
"self",
",",
"min_head_length",
"=",
"None",
",",
"max_head_length",
"=",
"None",
",",
"min_tail_length",
"=",
"None",
",",
"max_tail_length",
"=",
"None",
")",
":",
"head",
"=",
"self",
".",
"detect_head",
"(",
"min_head_length",
",",
"max_head_length",
")",
"tail",
"=",
"self",
".",
"detect_tail",
"(",
"min_tail_length",
",",
"max_tail_length",
")",
"begin",
"=",
"head",
"end",
"=",
"self",
".",
"real_wave_mfcc",
".",
"audio_length",
"-",
"tail",
"self",
".",
"log",
"(",
"[",
"u\"Audio length: %.3f\"",
",",
"self",
".",
"real_wave_mfcc",
".",
"audio_length",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Head length: %.3f\"",
",",
"head",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Tail length: %.3f\"",
",",
"tail",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Begin: %.3f\"",
",",
"begin",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"End: %.3f\"",
",",
"end",
"]",
")",
"if",
"(",
"begin",
">=",
"TimeValue",
"(",
"\"0.000\"",
")",
")",
"and",
"(",
"end",
">",
"begin",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Returning %.3f %.3f\"",
",",
"begin",
",",
"end",
"]",
")",
"return",
"(",
"begin",
",",
"end",
")",
"self",
".",
"log",
"(",
"u\"Returning (0.000, 0.000)\"",
")",
"return",
"(",
"TimeValue",
"(",
"\"0.000\"",
")",
",",
"TimeValue",
"(",
"\"0.000\"",
")",
")"
] | Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"interval",
"of",
"the",
"audio",
"file",
"containing",
"the",
"fragments",
"in",
"the",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L126-L170 |
232,133 | readbeyond/aeneas | aeneas/sd.py | SD.detect_head | def detect_head(self, min_head_length=None, max_head_length=None):
"""
Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_head_length, max_head_length, tail=False) | python | def detect_head(self, min_head_length=None, max_head_length=None):
"""
Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_head_length, max_head_length, tail=False) | [
"def",
"detect_head",
"(",
"self",
",",
"min_head_length",
"=",
"None",
",",
"max_head_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_detect",
"(",
"min_head_length",
",",
"max_head_length",
",",
"tail",
"=",
"False",
")"
] | Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"audio",
"head",
"returning",
"its",
"duration",
"in",
"seconds",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L172-L184 |
232,134 | readbeyond/aeneas | aeneas/sd.py | SD.detect_tail | def detect_tail(self, min_tail_length=None, max_tail_length=None):
"""
Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_tail_length, max_tail_length, tail=True) | python | def detect_tail(self, min_tail_length=None, max_tail_length=None):
"""
Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_tail_length, max_tail_length, tail=True) | [
"def",
"detect_tail",
"(",
"self",
",",
"min_tail_length",
"=",
"None",
",",
"max_tail_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_detect",
"(",
"min_tail_length",
",",
"max_tail_length",
",",
"tail",
"=",
"True",
")"
] | Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"audio",
"tail",
"returning",
"its",
"duration",
"in",
"seconds",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L186-L198 |
232,135 | readbeyond/aeneas | aeneas/synthesizer.py | Synthesizer._select_tts_engine | def _select_tts_engine(self):
"""
Select the TTS engine to be used by looking at the rconf object.
"""
self.log(u"Selecting TTS engine...")
requested_tts_engine = self.rconf[RuntimeConfiguration.TTS]
if requested_tts_engine == self.CUSTOM:
self.log(u"TTS engine: custom")
tts_path = self.rconf[RuntimeConfiguration.TTS_PATH]
if tts_path is None:
self.log_exc(u"You must specify a value for tts_path", None, True, ValueError)
if not gf.file_can_be_read(tts_path):
self.log_exc(u"Cannot read tts_path", None, True, OSError)
try:
import imp
self.log([u"Loading CustomTTSWrapper module from '%s'...", tts_path])
imp.load_source("CustomTTSWrapperModule", tts_path)
self.log([u"Loading CustomTTSWrapper module from '%s'... done", tts_path])
self.log(u"Importing CustomTTSWrapper...")
from CustomTTSWrapperModule import CustomTTSWrapper
self.log(u"Importing CustomTTSWrapper... done")
self.log(u"Creating CustomTTSWrapper instance...")
self.tts_engine = CustomTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Creating CustomTTSWrapper instance... done")
except Exception as exc:
self.log_exc(u"Unable to load custom TTS wrapper", exc, True, OSError)
elif requested_tts_engine == self.AWS:
try:
import boto3
except ImportError as exc:
self.log_exc(u"Unable to import boto3 for AWS Polly TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: AWS Polly TTS API")
self.tts_engine = AWSTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.NUANCE:
try:
import requests
except ImportError as exc:
self.log_exc(u"Unable to import requests for Nuance TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: Nuance TTS API")
self.tts_engine = NuanceTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.ESPEAKNG:
self.log(u"TTS engine: eSpeak-ng")
self.tts_engine = ESPEAKNGTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.FESTIVAL:
self.log(u"TTS engine: Festival")
self.tts_engine = FESTIVALTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.MACOS:
self.log(u"TTS engine: macOS")
self.tts_engine = MacOSTTSWrapper(rconf=self.rconf, logger=self.logger)
else:
self.log(u"TTS engine: eSpeak")
self.tts_engine = ESPEAKTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Selecting TTS engine... done") | python | def _select_tts_engine(self):
"""
Select the TTS engine to be used by looking at the rconf object.
"""
self.log(u"Selecting TTS engine...")
requested_tts_engine = self.rconf[RuntimeConfiguration.TTS]
if requested_tts_engine == self.CUSTOM:
self.log(u"TTS engine: custom")
tts_path = self.rconf[RuntimeConfiguration.TTS_PATH]
if tts_path is None:
self.log_exc(u"You must specify a value for tts_path", None, True, ValueError)
if not gf.file_can_be_read(tts_path):
self.log_exc(u"Cannot read tts_path", None, True, OSError)
try:
import imp
self.log([u"Loading CustomTTSWrapper module from '%s'...", tts_path])
imp.load_source("CustomTTSWrapperModule", tts_path)
self.log([u"Loading CustomTTSWrapper module from '%s'... done", tts_path])
self.log(u"Importing CustomTTSWrapper...")
from CustomTTSWrapperModule import CustomTTSWrapper
self.log(u"Importing CustomTTSWrapper... done")
self.log(u"Creating CustomTTSWrapper instance...")
self.tts_engine = CustomTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Creating CustomTTSWrapper instance... done")
except Exception as exc:
self.log_exc(u"Unable to load custom TTS wrapper", exc, True, OSError)
elif requested_tts_engine == self.AWS:
try:
import boto3
except ImportError as exc:
self.log_exc(u"Unable to import boto3 for AWS Polly TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: AWS Polly TTS API")
self.tts_engine = AWSTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.NUANCE:
try:
import requests
except ImportError as exc:
self.log_exc(u"Unable to import requests for Nuance TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: Nuance TTS API")
self.tts_engine = NuanceTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.ESPEAKNG:
self.log(u"TTS engine: eSpeak-ng")
self.tts_engine = ESPEAKNGTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.FESTIVAL:
self.log(u"TTS engine: Festival")
self.tts_engine = FESTIVALTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.MACOS:
self.log(u"TTS engine: macOS")
self.tts_engine = MacOSTTSWrapper(rconf=self.rconf, logger=self.logger)
else:
self.log(u"TTS engine: eSpeak")
self.tts_engine = ESPEAKTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Selecting TTS engine... done") | [
"def",
"_select_tts_engine",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Selecting TTS engine...\"",
")",
"requested_tts_engine",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TTS",
"]",
"if",
"requested_tts_engine",
"==",
"self",
".",
"CUSTOM",
":",
"self",
".",
"log",
"(",
"u\"TTS engine: custom\"",
")",
"tts_path",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TTS_PATH",
"]",
"if",
"tts_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"You must specify a value for tts_path\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"tts_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Cannot read tts_path\"",
",",
"None",
",",
"True",
",",
"OSError",
")",
"try",
":",
"import",
"imp",
"self",
".",
"log",
"(",
"[",
"u\"Loading CustomTTSWrapper module from '%s'...\"",
",",
"tts_path",
"]",
")",
"imp",
".",
"load_source",
"(",
"\"CustomTTSWrapperModule\"",
",",
"tts_path",
")",
"self",
".",
"log",
"(",
"[",
"u\"Loading CustomTTSWrapper module from '%s'... done\"",
",",
"tts_path",
"]",
")",
"self",
".",
"log",
"(",
"u\"Importing CustomTTSWrapper...\"",
")",
"from",
"CustomTTSWrapperModule",
"import",
"CustomTTSWrapper",
"self",
".",
"log",
"(",
"u\"Importing CustomTTSWrapper... done\"",
")",
"self",
".",
"log",
"(",
"u\"Creating CustomTTSWrapper instance...\"",
")",
"self",
".",
"tts_engine",
"=",
"CustomTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"log",
"(",
"u\"Creating CustomTTSWrapper instance... done\"",
")",
"except",
"Exception",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"Unable to load custom TTS wrapper\"",
",",
"exc",
",",
"True",
",",
"OSError",
")",
"elif",
"requested_tts_engine",
"==",
"self",
".",
"AWS",
":",
"try",
":",
"import",
"boto3",
"except",
"ImportError",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"Unable to import boto3 for AWS Polly TTS API wrapper\"",
",",
"exc",
",",
"True",
",",
"ImportError",
")",
"self",
".",
"log",
"(",
"u\"TTS engine: AWS Polly TTS API\"",
")",
"self",
".",
"tts_engine",
"=",
"AWSTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"elif",
"requested_tts_engine",
"==",
"self",
".",
"NUANCE",
":",
"try",
":",
"import",
"requests",
"except",
"ImportError",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"Unable to import requests for Nuance TTS API wrapper\"",
",",
"exc",
",",
"True",
",",
"ImportError",
")",
"self",
".",
"log",
"(",
"u\"TTS engine: Nuance TTS API\"",
")",
"self",
".",
"tts_engine",
"=",
"NuanceTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"elif",
"requested_tts_engine",
"==",
"self",
".",
"ESPEAKNG",
":",
"self",
".",
"log",
"(",
"u\"TTS engine: eSpeak-ng\"",
")",
"self",
".",
"tts_engine",
"=",
"ESPEAKNGTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"elif",
"requested_tts_engine",
"==",
"self",
".",
"FESTIVAL",
":",
"self",
".",
"log",
"(",
"u\"TTS engine: Festival\"",
")",
"self",
".",
"tts_engine",
"=",
"FESTIVALTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"elif",
"requested_tts_engine",
"==",
"self",
".",
"MACOS",
":",
"self",
".",
"log",
"(",
"u\"TTS engine: macOS\"",
")",
"self",
".",
"tts_engine",
"=",
"MacOSTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"TTS engine: eSpeak\"",
")",
"self",
".",
"tts_engine",
"=",
"ESPEAKTTSWrapper",
"(",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"self",
".",
"log",
"(",
"u\"Selecting TTS engine... done\"",
")"
] | Select the TTS engine to be used by looking at the rconf object. | [
"Select",
"the",
"TTS",
"engine",
"to",
"be",
"used",
"by",
"looking",
"at",
"the",
"rconf",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/synthesizer.py#L98-L150 |
232,136 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_shell_encoding | def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
is_in_utf8 = True
is_out_utf8 = True
if sys.stdin.encoding not in ["UTF-8", "UTF8"]:
is_in_utf8 = False
if sys.stdout.encoding not in ["UTF-8", "UTF8"]:
is_out_utf8 = False
if (is_in_utf8) and (is_out_utf8):
gf.print_success(u"shell encoding OK")
else:
gf.print_warning(u"shell encoding WARNING")
if not is_in_utf8:
gf.print_warning(u" The default input encoding of your shell is not UTF-8")
if not is_out_utf8:
gf.print_warning(u" The default output encoding of your shell is not UTF-8")
gf.print_info(u" If you plan to use aeneas on the command line,")
if gf.is_posix():
gf.print_info(u" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell")
else:
gf.print_info(u" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell")
return True
return False | python | def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
is_in_utf8 = True
is_out_utf8 = True
if sys.stdin.encoding not in ["UTF-8", "UTF8"]:
is_in_utf8 = False
if sys.stdout.encoding not in ["UTF-8", "UTF8"]:
is_out_utf8 = False
if (is_in_utf8) and (is_out_utf8):
gf.print_success(u"shell encoding OK")
else:
gf.print_warning(u"shell encoding WARNING")
if not is_in_utf8:
gf.print_warning(u" The default input encoding of your shell is not UTF-8")
if not is_out_utf8:
gf.print_warning(u" The default output encoding of your shell is not UTF-8")
gf.print_info(u" If you plan to use aeneas on the command line,")
if gf.is_posix():
gf.print_info(u" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell")
else:
gf.print_info(u" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell")
return True
return False | [
"def",
"check_shell_encoding",
"(",
"cls",
")",
":",
"is_in_utf8",
"=",
"True",
"is_out_utf8",
"=",
"True",
"if",
"sys",
".",
"stdin",
".",
"encoding",
"not",
"in",
"[",
"\"UTF-8\"",
",",
"\"UTF8\"",
"]",
":",
"is_in_utf8",
"=",
"False",
"if",
"sys",
".",
"stdout",
".",
"encoding",
"not",
"in",
"[",
"\"UTF-8\"",
",",
"\"UTF8\"",
"]",
":",
"is_out_utf8",
"=",
"False",
"if",
"(",
"is_in_utf8",
")",
"and",
"(",
"is_out_utf8",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"shell encoding OK\"",
")",
"else",
":",
"gf",
".",
"print_warning",
"(",
"u\"shell encoding WARNING\"",
")",
"if",
"not",
"is_in_utf8",
":",
"gf",
".",
"print_warning",
"(",
"u\" The default input encoding of your shell is not UTF-8\"",
")",
"if",
"not",
"is_out_utf8",
":",
"gf",
".",
"print_warning",
"(",
"u\" The default output encoding of your shell is not UTF-8\"",
")",
"gf",
".",
"print_info",
"(",
"u\" If you plan to use aeneas on the command line,\"",
")",
"if",
"gf",
".",
"is_posix",
"(",
")",
":",
"gf",
".",
"print_info",
"(",
"u\" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell\"",
")",
"else",
":",
"gf",
".",
"print_info",
"(",
"u\" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell\"",
")",
"return",
"True",
"return",
"False"
] | Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"sys",
".",
"stdin",
"and",
"sys",
".",
"stdout",
"are",
"UTF",
"-",
"8",
"encoded",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L49-L77 |
232,137 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_ffprobe | def check_ffprobe(cls):
"""
Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffprobewrapper import FFPROBEWrapper
file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
prober = FFPROBEWrapper()
properties = prober.read_properties(file_path)
gf.print_success(u"ffprobe OK")
return False
except:
pass
gf.print_error(u"ffprobe ERROR")
gf.print_info(u" Please make sure you have ffprobe installed correctly")
gf.print_info(u" (usually it is provided by the ffmpeg installer)")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | python | def check_ffprobe(cls):
"""
Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffprobewrapper import FFPROBEWrapper
file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
prober = FFPROBEWrapper()
properties = prober.read_properties(file_path)
gf.print_success(u"ffprobe OK")
return False
except:
pass
gf.print_error(u"ffprobe ERROR")
gf.print_info(u" Please make sure you have ffprobe installed correctly")
gf.print_info(u" (usually it is provided by the ffmpeg installer)")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | [
"def",
"check_ffprobe",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"ffprobewrapper",
"import",
"FFPROBEWrapper",
"file_path",
"=",
"gf",
".",
"absolute_path",
"(",
"u\"tools/res/audio.mp3\"",
",",
"__file__",
")",
"prober",
"=",
"FFPROBEWrapper",
"(",
")",
"properties",
"=",
"prober",
".",
"read_properties",
"(",
"file_path",
")",
"gf",
".",
"print_success",
"(",
"u\"ffprobe OK\"",
")",
"return",
"False",
"except",
":",
"pass",
"gf",
".",
"print_error",
"(",
"u\"ffprobe ERROR\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please make sure you have ffprobe installed correctly\"",
")",
"gf",
".",
"print_info",
"(",
"u\" (usually it is provided by the ffmpeg installer)\"",
")",
"gf",
".",
"print_info",
"(",
"u\" and that its path is in your PATH environment variable\"",
")",
"return",
"True"
] | Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"ffprobe",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L80-L101 |
232,138 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_ffmpeg | def check_ffmpeg(cls):
"""
Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffmpegwrapper import FFMPEGWrapper
input_file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
handler, output_file_path = gf.tmp_file(suffix=u".wav")
converter = FFMPEGWrapper()
result = converter.convert(input_file_path, output_file_path)
gf.delete_file(handler, output_file_path)
if result:
gf.print_success(u"ffmpeg OK")
return False
except:
pass
gf.print_error(u"ffmpeg ERROR")
gf.print_info(u" Please make sure you have ffmpeg installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | python | def check_ffmpeg(cls):
"""
Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffmpegwrapper import FFMPEGWrapper
input_file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
handler, output_file_path = gf.tmp_file(suffix=u".wav")
converter = FFMPEGWrapper()
result = converter.convert(input_file_path, output_file_path)
gf.delete_file(handler, output_file_path)
if result:
gf.print_success(u"ffmpeg OK")
return False
except:
pass
gf.print_error(u"ffmpeg ERROR")
gf.print_info(u" Please make sure you have ffmpeg installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | [
"def",
"check_ffmpeg",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"ffmpegwrapper",
"import",
"FFMPEGWrapper",
"input_file_path",
"=",
"gf",
".",
"absolute_path",
"(",
"u\"tools/res/audio.mp3\"",
",",
"__file__",
")",
"handler",
",",
"output_file_path",
"=",
"gf",
".",
"tmp_file",
"(",
"suffix",
"=",
"u\".wav\"",
")",
"converter",
"=",
"FFMPEGWrapper",
"(",
")",
"result",
"=",
"converter",
".",
"convert",
"(",
"input_file_path",
",",
"output_file_path",
")",
"gf",
".",
"delete_file",
"(",
"handler",
",",
"output_file_path",
")",
"if",
"result",
":",
"gf",
".",
"print_success",
"(",
"u\"ffmpeg OK\"",
")",
"return",
"False",
"except",
":",
"pass",
"gf",
".",
"print_error",
"(",
"u\"ffmpeg ERROR\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please make sure you have ffmpeg installed correctly\"",
")",
"gf",
".",
"print_info",
"(",
"u\" and that its path is in your PATH environment variable\"",
")",
"return",
"True"
] | Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"ffmpeg",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L104-L127 |
232,139 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_espeak | def check_espeak(cls):
"""
Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.textfile import TextFile
from aeneas.textfile import TextFragment
from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper
text = u"From fairest creatures we desire increase,"
text_file = TextFile()
text_file.add_fragment(TextFragment(language=u"eng", lines=[text], filtered_lines=[text]))
handler, output_file_path = gf.tmp_file(suffix=u".wav")
ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path)
gf.delete_file(handler, output_file_path)
gf.print_success(u"espeak OK")
return False
except:
pass
gf.print_error(u"espeak ERROR")
gf.print_info(u" Please make sure you have espeak installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
gf.print_info(u" You might also want to check that the espeak-data directory")
gf.print_info(u" is set up correctly, for example, it has the correct permissions")
return True | python | def check_espeak(cls):
"""
Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.textfile import TextFile
from aeneas.textfile import TextFragment
from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper
text = u"From fairest creatures we desire increase,"
text_file = TextFile()
text_file.add_fragment(TextFragment(language=u"eng", lines=[text], filtered_lines=[text]))
handler, output_file_path = gf.tmp_file(suffix=u".wav")
ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path)
gf.delete_file(handler, output_file_path)
gf.print_success(u"espeak OK")
return False
except:
pass
gf.print_error(u"espeak ERROR")
gf.print_info(u" Please make sure you have espeak installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
gf.print_info(u" You might also want to check that the espeak-data directory")
gf.print_info(u" is set up correctly, for example, it has the correct permissions")
return True | [
"def",
"check_espeak",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"textfile",
"import",
"TextFile",
"from",
"aeneas",
".",
"textfile",
"import",
"TextFragment",
"from",
"aeneas",
".",
"ttswrappers",
".",
"espeakttswrapper",
"import",
"ESPEAKTTSWrapper",
"text",
"=",
"u\"From fairest creatures we desire increase,\"",
"text_file",
"=",
"TextFile",
"(",
")",
"text_file",
".",
"add_fragment",
"(",
"TextFragment",
"(",
"language",
"=",
"u\"eng\"",
",",
"lines",
"=",
"[",
"text",
"]",
",",
"filtered_lines",
"=",
"[",
"text",
"]",
")",
")",
"handler",
",",
"output_file_path",
"=",
"gf",
".",
"tmp_file",
"(",
"suffix",
"=",
"u\".wav\"",
")",
"ESPEAKTTSWrapper",
"(",
")",
".",
"synthesize_multiple",
"(",
"text_file",
",",
"output_file_path",
")",
"gf",
".",
"delete_file",
"(",
"handler",
",",
"output_file_path",
")",
"gf",
".",
"print_success",
"(",
"u\"espeak OK\"",
")",
"return",
"False",
"except",
":",
"pass",
"gf",
".",
"print_error",
"(",
"u\"espeak ERROR\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please make sure you have espeak installed correctly\"",
")",
"gf",
".",
"print_info",
"(",
"u\" and that its path is in your PATH environment variable\"",
")",
"gf",
".",
"print_info",
"(",
"u\" You might also want to check that the espeak-data directory\"",
")",
"gf",
".",
"print_info",
"(",
"u\" is set up correctly, for example, it has the correct permissions\"",
")",
"return",
"True"
] | Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"espeak",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L130-L157 |
232,140 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cdtw | def check_cdtw(cls):
"""
Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cdtw"):
gf.print_success(u"aeneas.cdtw AVAILABLE")
return False
gf.print_warning(u"aeneas.cdtw NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cdtw(cls):
"""
Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cdtw"):
gf.print_success(u"aeneas.cdtw AVAILABLE")
return False
gf.print_warning(u"aeneas.cdtw NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cdtw",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cdtw\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cdtw AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cdtw NOT AVAILABLE\"",
")",
"gf",
".",
"print_info",
"(",
"u\" You can still run aeneas but it will be significantly slower\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please refer to the installation documentation for details\"",
")",
"return",
"True"
] | Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cdtw",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L195-L209 |
232,141 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cmfcc | def check_cmfcc(cls):
"""
Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cmfcc"):
gf.print_success(u"aeneas.cmfcc AVAILABLE")
return False
gf.print_warning(u"aeneas.cmfcc NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cmfcc(cls):
"""
Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cmfcc"):
gf.print_success(u"aeneas.cmfcc AVAILABLE")
return False
gf.print_warning(u"aeneas.cmfcc NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cmfcc",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cmfcc\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cmfcc AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cmfcc NOT AVAILABLE\"",
")",
"gf",
".",
"print_info",
"(",
"u\" You can still run aeneas but it will be significantly slower\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please refer to the installation documentation for details\"",
")",
"return",
"True"
] | Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cmfcc",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L212-L226 |
232,142 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cew | def check_cew(cls):
"""
Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cew"):
gf.print_success(u"aeneas.cew AVAILABLE")
return False
gf.print_warning(u"aeneas.cew NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be a bit slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cew(cls):
"""
Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cew"):
gf.print_success(u"aeneas.cew AVAILABLE")
return False
gf.print_warning(u"aeneas.cew NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be a bit slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cew",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cew\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cew AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cew NOT AVAILABLE\"",
")",
"gf",
".",
"print_info",
"(",
"u\" You can still run aeneas but it will be a bit slower\"",
")",
"gf",
".",
"print_info",
"(",
"u\" Please refer to the installation documentation for details\"",
")",
"return",
"True"
] | Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cew",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L229-L243 |
232,143 | readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_all | def check_all(cls, tools=True, encoding=True, c_ext=True):
"""
Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool)
"""
# errors are fatal
if cls.check_ffprobe():
return (True, False, False)
if cls.check_ffmpeg():
return (True, False, False)
if cls.check_espeak():
return (True, False, False)
if (tools) and (cls.check_tools()):
return (True, False, False)
# warnings are non-fatal
warnings = False
c_ext_warnings = False
if encoding:
warnings = cls.check_shell_encoding()
if c_ext:
# we do not want lazy evaluation
c_ext_warnings = cls.check_cdtw() or c_ext_warnings
c_ext_warnings = cls.check_cmfcc() or c_ext_warnings
c_ext_warnings = cls.check_cew() or c_ext_warnings
# return results
return (False, warnings, c_ext_warnings) | python | def check_all(cls, tools=True, encoding=True, c_ext=True):
"""
Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool)
"""
# errors are fatal
if cls.check_ffprobe():
return (True, False, False)
if cls.check_ffmpeg():
return (True, False, False)
if cls.check_espeak():
return (True, False, False)
if (tools) and (cls.check_tools()):
return (True, False, False)
# warnings are non-fatal
warnings = False
c_ext_warnings = False
if encoding:
warnings = cls.check_shell_encoding()
if c_ext:
# we do not want lazy evaluation
c_ext_warnings = cls.check_cdtw() or c_ext_warnings
c_ext_warnings = cls.check_cmfcc() or c_ext_warnings
c_ext_warnings = cls.check_cew() or c_ext_warnings
# return results
return (False, warnings, c_ext_warnings) | [
"def",
"check_all",
"(",
"cls",
",",
"tools",
"=",
"True",
",",
"encoding",
"=",
"True",
",",
"c_ext",
"=",
"True",
")",
":",
"# errors are fatal",
"if",
"cls",
".",
"check_ffprobe",
"(",
")",
":",
"return",
"(",
"True",
",",
"False",
",",
"False",
")",
"if",
"cls",
".",
"check_ffmpeg",
"(",
")",
":",
"return",
"(",
"True",
",",
"False",
",",
"False",
")",
"if",
"cls",
".",
"check_espeak",
"(",
")",
":",
"return",
"(",
"True",
",",
"False",
",",
"False",
")",
"if",
"(",
"tools",
")",
"and",
"(",
"cls",
".",
"check_tools",
"(",
")",
")",
":",
"return",
"(",
"True",
",",
"False",
",",
"False",
")",
"# warnings are non-fatal",
"warnings",
"=",
"False",
"c_ext_warnings",
"=",
"False",
"if",
"encoding",
":",
"warnings",
"=",
"cls",
".",
"check_shell_encoding",
"(",
")",
"if",
"c_ext",
":",
"# we do not want lazy evaluation",
"c_ext_warnings",
"=",
"cls",
".",
"check_cdtw",
"(",
")",
"or",
"c_ext_warnings",
"c_ext_warnings",
"=",
"cls",
".",
"check_cmfcc",
"(",
")",
"or",
"c_ext_warnings",
"c_ext_warnings",
"=",
"cls",
".",
"check_cew",
"(",
")",
"or",
"c_ext_warnings",
"# return results",
"return",
"(",
"False",
",",
"warnings",
",",
"c_ext_warnings",
")"
] | Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool) | [
"Perform",
"all",
"checks",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L246-L277 |
232,144 | readbeyond/aeneas | aeneas/configuration.py | Configuration.config_string | def config_string(self):
"""
Build the storable string corresponding
to this configuration object.
:rtype: string
"""
return (gc.CONFIG_STRING_SEPARATOR_SYMBOL).join(
[u"%s%s%s" % (fn, gc.CONFIG_STRING_ASSIGNMENT_SYMBOL, self.data[fn]) for fn in sorted(self.data.keys()) if self.data[fn] is not None]
) | python | def config_string(self):
"""
Build the storable string corresponding
to this configuration object.
:rtype: string
"""
return (gc.CONFIG_STRING_SEPARATOR_SYMBOL).join(
[u"%s%s%s" % (fn, gc.CONFIG_STRING_ASSIGNMENT_SYMBOL, self.data[fn]) for fn in sorted(self.data.keys()) if self.data[fn] is not None]
) | [
"def",
"config_string",
"(",
"self",
")",
":",
"return",
"(",
"gc",
".",
"CONFIG_STRING_SEPARATOR_SYMBOL",
")",
".",
"join",
"(",
"[",
"u\"%s%s%s\"",
"%",
"(",
"fn",
",",
"gc",
".",
"CONFIG_STRING_ASSIGNMENT_SYMBOL",
",",
"self",
".",
"data",
"[",
"fn",
"]",
")",
"for",
"fn",
"in",
"sorted",
"(",
"self",
".",
"data",
".",
"keys",
"(",
")",
")",
"if",
"self",
".",
"data",
"[",
"fn",
"]",
"is",
"not",
"None",
"]",
")"
] | Build the storable string corresponding
to this configuration object.
:rtype: string | [
"Build",
"the",
"storable",
"string",
"corresponding",
"to",
"this",
"configuration",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/configuration.py#L169-L178 |
232,145 | readbeyond/aeneas | aeneas/exacttiming.py | TimeValue.geq_multiple | def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return self
return int(math.ceil(other / self)) * self | python | def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return self
return int(math.ceil(other / self)) * self | [
"def",
"geq_multiple",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"==",
"TimeValue",
"(",
"\"0.000\"",
")",
":",
"return",
"self",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"other",
"/",
"self",
")",
")",
"*",
"self"
] | Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue` | [
"Return",
"the",
"next",
"multiple",
"of",
"this",
"time",
"value",
"greater",
"than",
"or",
"equal",
"to",
"other",
".",
"If",
"other",
"is",
"zero",
"return",
"this",
"time",
"value",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L67-L77 |
232,146 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.starts_at | def starts_at(self, time_point):
"""
Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.begin == time_point | python | def starts_at(self, time_point):
"""
Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.begin == time_point | [
"def",
"starts_at",
"(",
"self",
",",
"time_point",
")",
":",
"if",
"not",
"isinstance",
"(",
"time_point",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
"(",
"u\"time_point is not an instance of TimeValue\"",
")",
"return",
"self",
".",
"begin",
"==",
"time_point"
] | Returns ``True`` if this interval starts at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool | [
"Returns",
"True",
"if",
"this",
"interval",
"starts",
"at",
"the",
"given",
"time",
"point",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L371-L382 |
232,147 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.ends_at | def ends_at(self, time_point):
"""
Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.end == time_point | python | def ends_at(self, time_point):
"""
Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool
"""
if not isinstance(time_point, TimeValue):
raise TypeError(u"time_point is not an instance of TimeValue")
return self.end == time_point | [
"def",
"ends_at",
"(",
"self",
",",
"time_point",
")",
":",
"if",
"not",
"isinstance",
"(",
"time_point",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
"(",
"u\"time_point is not an instance of TimeValue\"",
")",
"return",
"self",
".",
"end",
"==",
"time_point"
] | Returns ``True`` if this interval ends at the given time point.
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: bool | [
"Returns",
"True",
"if",
"this",
"interval",
"ends",
"at",
"the",
"given",
"time",
"point",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L384-L395 |
232,148 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.percent_value | def percent_value(self, percent):
"""
Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if not isinstance(percent, Decimal):
raise TypeError(u"percent is not an instance of Decimal")
percent = Decimal(max(min(percent, 100), 0) / 100)
return self.begin + self.length * percent | python | def percent_value(self, percent):
"""
Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if not isinstance(percent, Decimal):
raise TypeError(u"percent is not an instance of Decimal")
percent = Decimal(max(min(percent, 100), 0) / 100)
return self.begin + self.length * percent | [
"def",
"percent_value",
"(",
"self",
",",
"percent",
")",
":",
"if",
"not",
"isinstance",
"(",
"percent",
",",
"Decimal",
")",
":",
"raise",
"TypeError",
"(",
"u\"percent is not an instance of Decimal\"",
")",
"percent",
"=",
"Decimal",
"(",
"max",
"(",
"min",
"(",
"percent",
",",
"100",
")",
",",
"0",
")",
"/",
"100",
")",
"return",
"self",
".",
"begin",
"+",
"self",
".",
"length",
"*",
"percent"
] | Returns the time value at ``percent`` of this interval.
:param percent: the percent
:type percent: :class:`~aeneas.exacttiming.Decimal`
:raises TypeError: if ``time_point`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeValue` | [
"Returns",
"the",
"time",
"value",
"at",
"percent",
"of",
"this",
"interval",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L397-L409 |
232,149 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.offset | def offset(self, offset, allow_negative=False, min_begin_value=None, max_end_value=None):
"""
Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval`
"""
if not isinstance(offset, TimeValue):
raise TypeError(u"offset is not an instance of TimeValue")
self.begin += offset
self.end += offset
if not allow_negative:
self.begin = max(self.begin, TimeValue("0.000"))
self.end = max(self.end, TimeValue("0.000"))
if (min_begin_value is not None) and (max_end_value is not None):
self.begin = min(max(self.begin, min_begin_value), max_end_value)
self.end = min(self.end, max_end_value)
return self | python | def offset(self, offset, allow_negative=False, min_begin_value=None, max_end_value=None):
"""
Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval`
"""
if not isinstance(offset, TimeValue):
raise TypeError(u"offset is not an instance of TimeValue")
self.begin += offset
self.end += offset
if not allow_negative:
self.begin = max(self.begin, TimeValue("0.000"))
self.end = max(self.end, TimeValue("0.000"))
if (min_begin_value is not None) and (max_end_value is not None):
self.begin = min(max(self.begin, min_begin_value), max_end_value)
self.end = min(self.end, max_end_value)
return self | [
"def",
"offset",
"(",
"self",
",",
"offset",
",",
"allow_negative",
"=",
"False",
",",
"min_begin_value",
"=",
"None",
",",
"max_end_value",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"offset",
",",
"TimeValue",
")",
":",
"raise",
"TypeError",
"(",
"u\"offset is not an instance of TimeValue\"",
")",
"self",
".",
"begin",
"+=",
"offset",
"self",
".",
"end",
"+=",
"offset",
"if",
"not",
"allow_negative",
":",
"self",
".",
"begin",
"=",
"max",
"(",
"self",
".",
"begin",
",",
"TimeValue",
"(",
"\"0.000\"",
")",
")",
"self",
".",
"end",
"=",
"max",
"(",
"self",
".",
"end",
",",
"TimeValue",
"(",
"\"0.000\"",
")",
")",
"if",
"(",
"min_begin_value",
"is",
"not",
"None",
")",
"and",
"(",
"max_end_value",
"is",
"not",
"None",
")",
":",
"self",
".",
"begin",
"=",
"min",
"(",
"max",
"(",
"self",
".",
"begin",
",",
"min_begin_value",
")",
",",
"max_end_value",
")",
"self",
".",
"end",
"=",
"min",
"(",
"self",
".",
"end",
",",
"max_end_value",
")",
"return",
"self"
] | Move this interval by the given shift ``offset``.
The begin and end time points of the translated interval
are ensured to be non-negative
(i.e., they are maxed with ``0.000``),
unless ``allow_negative`` is set to ``True``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:param allow_negative: if ``True``, allow the translated interval to have negative extrema
:type allow_negative: bool
:param min_begin_value: if not ``None``, specify the minimum value for the begin of the translated interval
:type min_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:param max_begin_value: if not ``None``, specify the maximum value for the end of the translated interval
:type max_begin_value: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
:rtype: :class:`~aeneas.exacttiming.TimeInterval` | [
"Move",
"this",
"interval",
"by",
"the",
"given",
"shift",
"offset",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L411-L441 |
232,150 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.intersection | def intersection(self, other):
"""
Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType``
"""
relative_position = self.relative_position_of(other)
if relative_position in [
self.RELATIVE_POSITION_PP_C,
self.RELATIVE_POSITION_PI_LC,
self.RELATIVE_POSITION_PI_LG,
self.RELATIVE_POSITION_PI_CG,
self.RELATIVE_POSITION_IP_B,
self.RELATIVE_POSITION_II_LB,
]:
return TimeInterval(begin=self.begin, end=self.begin)
if relative_position in [
self.RELATIVE_POSITION_IP_E,
self.RELATIVE_POSITION_II_EG,
]:
return TimeInterval(begin=self.end, end=self.end)
if relative_position in [
self.RELATIVE_POSITION_II_BI,
self.RELATIVE_POSITION_II_BE,
self.RELATIVE_POSITION_II_II,
self.RELATIVE_POSITION_II_IE,
]:
return TimeInterval(begin=other.begin, end=other.end)
if relative_position in [
self.RELATIVE_POSITION_IP_I,
self.RELATIVE_POSITION_II_LI,
self.RELATIVE_POSITION_II_LE,
self.RELATIVE_POSITION_II_LG,
self.RELATIVE_POSITION_II_BG,
self.RELATIVE_POSITION_II_IG,
]:
begin = max(self.begin, other.begin)
end = min(self.end, other.end)
return TimeInterval(begin=begin, end=end)
return None | python | def intersection(self, other):
"""
Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType``
"""
relative_position = self.relative_position_of(other)
if relative_position in [
self.RELATIVE_POSITION_PP_C,
self.RELATIVE_POSITION_PI_LC,
self.RELATIVE_POSITION_PI_LG,
self.RELATIVE_POSITION_PI_CG,
self.RELATIVE_POSITION_IP_B,
self.RELATIVE_POSITION_II_LB,
]:
return TimeInterval(begin=self.begin, end=self.begin)
if relative_position in [
self.RELATIVE_POSITION_IP_E,
self.RELATIVE_POSITION_II_EG,
]:
return TimeInterval(begin=self.end, end=self.end)
if relative_position in [
self.RELATIVE_POSITION_II_BI,
self.RELATIVE_POSITION_II_BE,
self.RELATIVE_POSITION_II_II,
self.RELATIVE_POSITION_II_IE,
]:
return TimeInterval(begin=other.begin, end=other.end)
if relative_position in [
self.RELATIVE_POSITION_IP_I,
self.RELATIVE_POSITION_II_LI,
self.RELATIVE_POSITION_II_LE,
self.RELATIVE_POSITION_II_LG,
self.RELATIVE_POSITION_II_BG,
self.RELATIVE_POSITION_II_IG,
]:
begin = max(self.begin, other.begin)
end = min(self.end, other.end)
return TimeInterval(begin=begin, end=end)
return None | [
"def",
"intersection",
"(",
"self",
",",
"other",
")",
":",
"relative_position",
"=",
"self",
".",
"relative_position_of",
"(",
"other",
")",
"if",
"relative_position",
"in",
"[",
"self",
".",
"RELATIVE_POSITION_PP_C",
",",
"self",
".",
"RELATIVE_POSITION_PI_LC",
",",
"self",
".",
"RELATIVE_POSITION_PI_LG",
",",
"self",
".",
"RELATIVE_POSITION_PI_CG",
",",
"self",
".",
"RELATIVE_POSITION_IP_B",
",",
"self",
".",
"RELATIVE_POSITION_II_LB",
",",
"]",
":",
"return",
"TimeInterval",
"(",
"begin",
"=",
"self",
".",
"begin",
",",
"end",
"=",
"self",
".",
"begin",
")",
"if",
"relative_position",
"in",
"[",
"self",
".",
"RELATIVE_POSITION_IP_E",
",",
"self",
".",
"RELATIVE_POSITION_II_EG",
",",
"]",
":",
"return",
"TimeInterval",
"(",
"begin",
"=",
"self",
".",
"end",
",",
"end",
"=",
"self",
".",
"end",
")",
"if",
"relative_position",
"in",
"[",
"self",
".",
"RELATIVE_POSITION_II_BI",
",",
"self",
".",
"RELATIVE_POSITION_II_BE",
",",
"self",
".",
"RELATIVE_POSITION_II_II",
",",
"self",
".",
"RELATIVE_POSITION_II_IE",
",",
"]",
":",
"return",
"TimeInterval",
"(",
"begin",
"=",
"other",
".",
"begin",
",",
"end",
"=",
"other",
".",
"end",
")",
"if",
"relative_position",
"in",
"[",
"self",
".",
"RELATIVE_POSITION_IP_I",
",",
"self",
".",
"RELATIVE_POSITION_II_LI",
",",
"self",
".",
"RELATIVE_POSITION_II_LE",
",",
"self",
".",
"RELATIVE_POSITION_II_LG",
",",
"self",
".",
"RELATIVE_POSITION_II_BG",
",",
"self",
".",
"RELATIVE_POSITION_II_IG",
",",
"]",
":",
"begin",
"=",
"max",
"(",
"self",
".",
"begin",
",",
"other",
".",
"begin",
")",
"end",
"=",
"min",
"(",
"self",
".",
"end",
",",
"other",
".",
"end",
")",
"return",
"TimeInterval",
"(",
"begin",
"=",
"begin",
",",
"end",
"=",
"end",
")",
"return",
"None"
] | Return the intersection between this time interval
and the given time interval, or
``None`` if the two intervals do not overlap.
:rtype: :class:`~aeneas.exacttiming.TimeInterval` or ``NoneType`` | [
"Return",
"the",
"intersection",
"between",
"this",
"time",
"interval",
"and",
"the",
"given",
"time",
"interval",
"or",
"None",
"if",
"the",
"two",
"intervals",
"do",
"not",
"overlap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L569-L610 |
232,151 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.is_non_zero_before_non_zero | def is_non_zero_before_non_zero(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
return self.is_adjacent_before(other) and (not self.has_zero_length) and (not other.has_zero_length) | python | def is_non_zero_before_non_zero(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
return self.is_adjacent_before(other) and (not self.has_zero_length) and (not other.has_zero_length) | [
"def",
"is_non_zero_before_non_zero",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"is_adjacent_before",
"(",
"other",
")",
"and",
"(",
"not",
"self",
".",
"has_zero_length",
")",
"and",
"(",
"not",
"other",
".",
"has_zero_length",
")"
] | Return ``True`` if this time interval ends
when the given other time interval begins,
and both have non zero length.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool | [
"Return",
"True",
"if",
"this",
"time",
"interval",
"ends",
"when",
"the",
"given",
"other",
"time",
"interval",
"begins",
"and",
"both",
"have",
"non",
"zero",
"length",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L623-L634 |
232,152 | readbeyond/aeneas | aeneas/exacttiming.py | TimeInterval.is_adjacent_before | def is_adjacent_before(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
if not isinstance(other, TimeInterval):
raise TypeError(u"other is not an instance of TimeInterval")
return (self.end == other.begin) | python | def is_adjacent_before(self, other):
"""
Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool
"""
if not isinstance(other, TimeInterval):
raise TypeError(u"other is not an instance of TimeInterval")
return (self.end == other.begin) | [
"def",
"is_adjacent_before",
"(",
"self",
",",
"other",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"TimeInterval",
")",
":",
"raise",
"TypeError",
"(",
"u\"other is not an instance of TimeInterval\"",
")",
"return",
"(",
"self",
".",
"end",
"==",
"other",
".",
"begin",
")"
] | Return ``True`` if this time interval ends
when the given other time interval begins.
:param other: the other interval
:type other: :class:`~aeneas.exacttiming.TimeInterval`
:raises TypeError: if ``other`` is not an instance of ``TimeInterval``
:rtype: bool | [
"Return",
"True",
"if",
"this",
"time",
"interval",
"ends",
"when",
"the",
"given",
"other",
"time",
"interval",
"begins",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L649-L661 |
232,153 | readbeyond/aeneas | aeneas/tools/convert_syncmap.py | ConvertSyncMapCLI.check_format | def check_format(self, sm_format):
"""
Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool
"""
if sm_format not in SyncMapFormat.ALLOWED_VALUES:
self.print_error(u"Sync map format '%s' is not allowed" % (sm_format))
self.print_info(u"Allowed formats:")
self.print_generic(u" ".join(SyncMapFormat.ALLOWED_VALUES))
return False
return True | python | def check_format(self, sm_format):
"""
Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool
"""
if sm_format not in SyncMapFormat.ALLOWED_VALUES:
self.print_error(u"Sync map format '%s' is not allowed" % (sm_format))
self.print_info(u"Allowed formats:")
self.print_generic(u" ".join(SyncMapFormat.ALLOWED_VALUES))
return False
return True | [
"def",
"check_format",
"(",
"self",
",",
"sm_format",
")",
":",
"if",
"sm_format",
"not",
"in",
"SyncMapFormat",
".",
"ALLOWED_VALUES",
":",
"self",
".",
"print_error",
"(",
"u\"Sync map format '%s' is not allowed\"",
"%",
"(",
"sm_format",
")",
")",
"self",
".",
"print_info",
"(",
"u\"Allowed formats:\"",
")",
"self",
".",
"print_generic",
"(",
"u\" \"",
".",
"join",
"(",
"SyncMapFormat",
".",
"ALLOWED_VALUES",
")",
")",
"return",
"False",
"return",
"True"
] | Return ``True`` if the given sync map format is allowed,
and ``False`` otherwise.
:param sm_format: the sync map format to be checked
:type sm_format: Unicode string
:rtype: bool | [
"Return",
"True",
"if",
"the",
"given",
"sync",
"map",
"format",
"is",
"allowed",
"and",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/convert_syncmap.py#L163-L177 |
232,154 | readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase._add_fragment | def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
"""
Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string
"""
syncmap.add_fragment(
SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
lines=lines,
language=language
),
begin=begin,
end=end
)
) | python | def _add_fragment(cls, syncmap, identifier, lines, begin, end, language=None):
"""
Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string
"""
syncmap.add_fragment(
SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
lines=lines,
language=language
),
begin=begin,
end=end
)
) | [
"def",
"_add_fragment",
"(",
"cls",
",",
"syncmap",
",",
"identifier",
",",
"lines",
",",
"begin",
",",
"end",
",",
"language",
"=",
"None",
")",
":",
"syncmap",
".",
"add_fragment",
"(",
"SyncMapFragment",
"(",
"text_fragment",
"=",
"TextFragment",
"(",
"identifier",
"=",
"identifier",
",",
"lines",
"=",
"lines",
",",
"language",
"=",
"language",
")",
",",
"begin",
"=",
"begin",
",",
"end",
"=",
"end",
")",
")"
] | Add a new fragment to ``syncmap``.
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:param identifier: the identifier
:type identifier: string
:param lines: the lines of the text
:type lines: list of string
:param begin: the begin time
:type begin: :class:`~aeneas.exacttiming.TimeValue`
:param end: the end time
:type end: :class:`~aeneas.exacttiming.TimeValue`
:param language: the language
:type language: string | [
"Add",
"a",
"new",
"fragment",
"to",
"syncmap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L53-L80 |
232,155 | readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase.parse | def parse(self, input_text, syncmap):
"""
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | python | def parse(self, input_text, syncmap):
"""
Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | [
"def",
"parse",
"(",
"self",
",",
"input_text",
",",
"syncmap",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"%s is abstract and cannot be called directly\"",
"%",
"(",
"self",
".",
"TAG",
")",
",",
"None",
",",
"True",
",",
"NotImplementedError",
")"
] | Parse the given ``input_text`` and
append the extracted fragments to ``syncmap``.
:param input_text: the input text as a Unicode string (read from file)
:type input_text: string
:param syncmap: the syncmap to append to
:type syncmap: :class:`~aeneas.syncmap.SyncMap` | [
"Parse",
"the",
"given",
"input_text",
"and",
"append",
"the",
"extracted",
"fragments",
"to",
"syncmap",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L82-L92 |
232,156 | readbeyond/aeneas | aeneas/syncmap/smfbase.py | SyncMapFormatBase.format | def format(self, syncmap):
"""
Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | python | def format(self, syncmap):
"""
Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string
"""
self.log_exc(u"%s is abstract and cannot be called directly" % (self.TAG), None, True, NotImplementedError) | [
"def",
"format",
"(",
"self",
",",
"syncmap",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"%s is abstract and cannot be called directly\"",
"%",
"(",
"self",
".",
"TAG",
")",
",",
"None",
",",
"True",
",",
"NotImplementedError",
")"
] | Format the given ``syncmap`` as a Unicode string.
:param syncmap: the syncmap to output
:type syncmap: :class:`~aeneas.syncmap.SyncMap`
:rtype: string | [
"Format",
"the",
"given",
"syncmap",
"as",
"a",
"Unicode",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfbase.py#L94-L102 |
232,157 | readbeyond/aeneas | aeneas/tools/execute_task.py | ExecuteTaskCLI.print_examples | def print_examples(self, full=False):
"""
Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones
"""
msg = []
i = 1
for key in sorted(self.DEMOS.keys()):
example = self.DEMOS[key]
if full or example["show"]:
msg.append(u"Example %d (%s)" % (i, example[u"description"]))
msg.append(u" $ %s %s" % (self.invoke, key))
msg.append(u"")
i += 1
self.print_generic(u"\n" + u"\n".join(msg) + u"\n")
return self.HELP_EXIT_CODE | python | def print_examples(self, full=False):
"""
Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones
"""
msg = []
i = 1
for key in sorted(self.DEMOS.keys()):
example = self.DEMOS[key]
if full or example["show"]:
msg.append(u"Example %d (%s)" % (i, example[u"description"]))
msg.append(u" $ %s %s" % (self.invoke, key))
msg.append(u"")
i += 1
self.print_generic(u"\n" + u"\n".join(msg) + u"\n")
return self.HELP_EXIT_CODE | [
"def",
"print_examples",
"(",
"self",
",",
"full",
"=",
"False",
")",
":",
"msg",
"=",
"[",
"]",
"i",
"=",
"1",
"for",
"key",
"in",
"sorted",
"(",
"self",
".",
"DEMOS",
".",
"keys",
"(",
")",
")",
":",
"example",
"=",
"self",
".",
"DEMOS",
"[",
"key",
"]",
"if",
"full",
"or",
"example",
"[",
"\"show\"",
"]",
":",
"msg",
".",
"append",
"(",
"u\"Example %d (%s)\"",
"%",
"(",
"i",
",",
"example",
"[",
"u\"description\"",
"]",
")",
")",
"msg",
".",
"append",
"(",
"u\" $ %s %s\"",
"%",
"(",
"self",
".",
"invoke",
",",
"key",
")",
")",
"msg",
".",
"append",
"(",
"u\"\"",
")",
"i",
"+=",
"1",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
"+",
"u\"\\n\"",
".",
"join",
"(",
"msg",
")",
"+",
"u\"\\n\"",
")",
"return",
"self",
".",
"HELP_EXIT_CODE"
] | Print the examples and exit.
:param bool full: if ``True``, print all examples; otherwise,
print only selected ones | [
"Print",
"the",
"examples",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L682-L699 |
232,158 | readbeyond/aeneas | aeneas/tools/execute_task.py | ExecuteTaskCLI.print_values | def print_values(self, parameter):
"""
Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string
"""
if parameter in self.VALUES:
self.print_info(u"Available values for parameter '%s':" % parameter)
self.print_generic(u"\n".join(self.VALUES[parameter]))
return self.HELP_EXIT_CODE
if parameter not in [u"?", u""]:
self.print_error(u"Invalid parameter name '%s'" % parameter)
self.print_info(u"Parameters for which values can be listed:")
self.print_generic(u"\n".join(sorted(self.VALUES.keys())))
return self.HELP_EXIT_CODE | python | def print_values(self, parameter):
"""
Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string
"""
if parameter in self.VALUES:
self.print_info(u"Available values for parameter '%s':" % parameter)
self.print_generic(u"\n".join(self.VALUES[parameter]))
return self.HELP_EXIT_CODE
if parameter not in [u"?", u""]:
self.print_error(u"Invalid parameter name '%s'" % parameter)
self.print_info(u"Parameters for which values can be listed:")
self.print_generic(u"\n".join(sorted(self.VALUES.keys())))
return self.HELP_EXIT_CODE | [
"def",
"print_values",
"(",
"self",
",",
"parameter",
")",
":",
"if",
"parameter",
"in",
"self",
".",
"VALUES",
":",
"self",
".",
"print_info",
"(",
"u\"Available values for parameter '%s':\"",
"%",
"parameter",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
".",
"join",
"(",
"self",
".",
"VALUES",
"[",
"parameter",
"]",
")",
")",
"return",
"self",
".",
"HELP_EXIT_CODE",
"if",
"parameter",
"not",
"in",
"[",
"u\"?\"",
",",
"u\"\"",
"]",
":",
"self",
".",
"print_error",
"(",
"u\"Invalid parameter name '%s'\"",
"%",
"parameter",
")",
"self",
".",
"print_info",
"(",
"u\"Parameters for which values can be listed:\"",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
".",
"join",
"(",
"sorted",
"(",
"self",
".",
"VALUES",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"self",
".",
"HELP_EXIT_CODE"
] | Print the list of values for the given parameter and exit.
If ``parameter`` is invalid, print the list of
parameter names that have allowed values.
:param parameter: the parameter name
:type parameter: Unicode string | [
"Print",
"the",
"list",
"of",
"values",
"for",
"the",
"given",
"parameter",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_task.py#L711-L729 |
232,159 | readbeyond/aeneas | setup.py | prepare_cew_for_windows | def prepare_cew_for_windows():
"""
Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool
"""
try:
# copy espeak_sapi.dll to C:\Windows\System32\espeak.dll
espeak_dll_win_path = "C:\\Windows\\System32\\espeak.dll"
espeak_dll_dst_path = "aeneas\\cew\\espeak.dll"
espeak_dll_src_paths = [
"C:\\aeneas\\eSpeak\\espeak_sapi.dll",
"C:\\sync\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files (x86)\\eSpeak\\espeak_sapi.dll",
]
if os.path.exists(espeak_dll_dst_path):
print("[INFO] Found eSpeak DLL in %s" % espeak_dll_dst_path)
else:
found = False
copied = False
for src_path in espeak_dll_src_paths:
if os.path.exists(src_path):
found = True
print("[INFO] Copying eSpeak DLL from %s into %s" % (src_path, espeak_dll_dst_path))
try:
shutil.copyfile(src_path, espeak_dll_dst_path)
copied = True
print("[INFO] Copied eSpeak DLL")
except:
pass
break
if not found:
print("[WARN] Unable to find the eSpeak DLL, probably because you installed eSpeak in a non-standard location.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
elif not copied:
print("[WARN] Unable to copy the eSpeak DLL, probably because you are not running with admin privileges.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
# NOTE: espeak.lib is needed only while compiling the C extension, not when using it
# so, we copy it in the current working directory from the included thirdparty\ directory
# NOTE: PREV: copy thirdparty\espeak.lib to $PYTHON\libs\espeak.lib
# NOTE: PREV: espeak_lib_dst_path = os.path.join(sys.prefix, "libs", "espeak.lib")
espeak_lib_src_path = os.path.join(os.path.dirname(__file__), "thirdparty", "espeak.lib")
espeak_lib_dst_path = os.path.join(os.path.dirname(__file__), "espeak.lib")
if os.path.exists(espeak_lib_dst_path):
print("[INFO] Found eSpeak LIB in %s" % espeak_lib_dst_path)
else:
try:
print("[INFO] Copying eSpeak LIB into %s" % espeak_lib_dst_path)
shutil.copyfile(espeak_lib_src_path, espeak_lib_dst_path)
print("[INFO] Copied eSpeak LIB")
except:
print("[WARN] Unable to copy the eSpeak LIB, probably because you are not running with admin privileges.")
print("[WARN] If you want to compile the C extension cew,")
print("[WARN] please copy espeak.lib from the thirdparty directory into %s" % espeak_lib_dst_path)
print("[WARN] and run the aeneas setup again.")
return False
# if here, we have completed the setup, return True
return True
except Exception as e:
print("[WARN] Unexpected exception while preparing cew: %s" % e)
return False | python | def prepare_cew_for_windows():
"""
Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool
"""
try:
# copy espeak_sapi.dll to C:\Windows\System32\espeak.dll
espeak_dll_win_path = "C:\\Windows\\System32\\espeak.dll"
espeak_dll_dst_path = "aeneas\\cew\\espeak.dll"
espeak_dll_src_paths = [
"C:\\aeneas\\eSpeak\\espeak_sapi.dll",
"C:\\sync\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files\\eSpeak\\espeak_sapi.dll",
"C:\\Program Files (x86)\\eSpeak\\espeak_sapi.dll",
]
if os.path.exists(espeak_dll_dst_path):
print("[INFO] Found eSpeak DLL in %s" % espeak_dll_dst_path)
else:
found = False
copied = False
for src_path in espeak_dll_src_paths:
if os.path.exists(src_path):
found = True
print("[INFO] Copying eSpeak DLL from %s into %s" % (src_path, espeak_dll_dst_path))
try:
shutil.copyfile(src_path, espeak_dll_dst_path)
copied = True
print("[INFO] Copied eSpeak DLL")
except:
pass
break
if not found:
print("[WARN] Unable to find the eSpeak DLL, probably because you installed eSpeak in a non-standard location.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
elif not copied:
print("[WARN] Unable to copy the eSpeak DLL, probably because you are not running with admin privileges.")
print("[WARN] If you want to run aeneas with the C extension cew,")
print("[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s" % espeak_dll_win_path)
# print("[WARN] and run the aeneas setup again.")
# return False
# NOTE: espeak.lib is needed only while compiling the C extension, not when using it
# so, we copy it in the current working directory from the included thirdparty\ directory
# NOTE: PREV: copy thirdparty\espeak.lib to $PYTHON\libs\espeak.lib
# NOTE: PREV: espeak_lib_dst_path = os.path.join(sys.prefix, "libs", "espeak.lib")
espeak_lib_src_path = os.path.join(os.path.dirname(__file__), "thirdparty", "espeak.lib")
espeak_lib_dst_path = os.path.join(os.path.dirname(__file__), "espeak.lib")
if os.path.exists(espeak_lib_dst_path):
print("[INFO] Found eSpeak LIB in %s" % espeak_lib_dst_path)
else:
try:
print("[INFO] Copying eSpeak LIB into %s" % espeak_lib_dst_path)
shutil.copyfile(espeak_lib_src_path, espeak_lib_dst_path)
print("[INFO] Copied eSpeak LIB")
except:
print("[WARN] Unable to copy the eSpeak LIB, probably because you are not running with admin privileges.")
print("[WARN] If you want to compile the C extension cew,")
print("[WARN] please copy espeak.lib from the thirdparty directory into %s" % espeak_lib_dst_path)
print("[WARN] and run the aeneas setup again.")
return False
# if here, we have completed the setup, return True
return True
except Exception as e:
print("[WARN] Unexpected exception while preparing cew: %s" % e)
return False | [
"def",
"prepare_cew_for_windows",
"(",
")",
":",
"try",
":",
"# copy espeak_sapi.dll to C:\\Windows\\System32\\espeak.dll",
"espeak_dll_win_path",
"=",
"\"C:\\\\Windows\\\\System32\\\\espeak.dll\"",
"espeak_dll_dst_path",
"=",
"\"aeneas\\\\cew\\\\espeak.dll\"",
"espeak_dll_src_paths",
"=",
"[",
"\"C:\\\\aeneas\\\\eSpeak\\\\espeak_sapi.dll\"",
",",
"\"C:\\\\sync\\\\eSpeak\\\\espeak_sapi.dll\"",
",",
"\"C:\\\\Program Files\\\\eSpeak\\\\espeak_sapi.dll\"",
",",
"\"C:\\\\Program Files (x86)\\\\eSpeak\\\\espeak_sapi.dll\"",
",",
"]",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"espeak_dll_dst_path",
")",
":",
"print",
"(",
"\"[INFO] Found eSpeak DLL in %s\"",
"%",
"espeak_dll_dst_path",
")",
"else",
":",
"found",
"=",
"False",
"copied",
"=",
"False",
"for",
"src_path",
"in",
"espeak_dll_src_paths",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"src_path",
")",
":",
"found",
"=",
"True",
"print",
"(",
"\"[INFO] Copying eSpeak DLL from %s into %s\"",
"%",
"(",
"src_path",
",",
"espeak_dll_dst_path",
")",
")",
"try",
":",
"shutil",
".",
"copyfile",
"(",
"src_path",
",",
"espeak_dll_dst_path",
")",
"copied",
"=",
"True",
"print",
"(",
"\"[INFO] Copied eSpeak DLL\"",
")",
"except",
":",
"pass",
"break",
"if",
"not",
"found",
":",
"print",
"(",
"\"[WARN] Unable to find the eSpeak DLL, probably because you installed eSpeak in a non-standard location.\"",
")",
"print",
"(",
"\"[WARN] If you want to run aeneas with the C extension cew,\"",
")",
"print",
"(",
"\"[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s\"",
"%",
"espeak_dll_win_path",
")",
"# print(\"[WARN] and run the aeneas setup again.\")",
"# return False",
"elif",
"not",
"copied",
":",
"print",
"(",
"\"[WARN] Unable to copy the eSpeak DLL, probably because you are not running with admin privileges.\"",
")",
"print",
"(",
"\"[WARN] If you want to run aeneas with the C extension cew,\"",
")",
"print",
"(",
"\"[WARN] please copy espeak_sapi.dll from your eSpeak directory to %s\"",
"%",
"espeak_dll_win_path",
")",
"# print(\"[WARN] and run the aeneas setup again.\")",
"# return False",
"# NOTE: espeak.lib is needed only while compiling the C extension, not when using it",
"# so, we copy it in the current working directory from the included thirdparty\\ directory",
"# NOTE: PREV: copy thirdparty\\espeak.lib to $PYTHON\\libs\\espeak.lib",
"# NOTE: PREV: espeak_lib_dst_path = os.path.join(sys.prefix, \"libs\", \"espeak.lib\")",
"espeak_lib_src_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"thirdparty\"",
",",
"\"espeak.lib\"",
")",
"espeak_lib_dst_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"espeak.lib\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"espeak_lib_dst_path",
")",
":",
"print",
"(",
"\"[INFO] Found eSpeak LIB in %s\"",
"%",
"espeak_lib_dst_path",
")",
"else",
":",
"try",
":",
"print",
"(",
"\"[INFO] Copying eSpeak LIB into %s\"",
"%",
"espeak_lib_dst_path",
")",
"shutil",
".",
"copyfile",
"(",
"espeak_lib_src_path",
",",
"espeak_lib_dst_path",
")",
"print",
"(",
"\"[INFO] Copied eSpeak LIB\"",
")",
"except",
":",
"print",
"(",
"\"[WARN] Unable to copy the eSpeak LIB, probably because you are not running with admin privileges.\"",
")",
"print",
"(",
"\"[WARN] If you want to compile the C extension cew,\"",
")",
"print",
"(",
"\"[WARN] please copy espeak.lib from the thirdparty directory into %s\"",
"%",
"espeak_lib_dst_path",
")",
"print",
"(",
"\"[WARN] and run the aeneas setup again.\"",
")",
"return",
"False",
"# if here, we have completed the setup, return True",
"return",
"True",
"except",
"Exception",
"as",
"e",
":",
"print",
"(",
"\"[WARN] Unexpected exception while preparing cew: %s\"",
"%",
"e",
")",
"return",
"False"
] | Copy files needed to compile the ``cew`` Python C extension on Windows.
A glorious day, when Microsoft will offer a decent support
for Python and shared libraries,
all this mess will be unnecessary and it should be removed.
May that day come soon.
Return ``True`` if successful, ``False`` otherwise.
:rtype: bool | [
"Copy",
"files",
"needed",
"to",
"compile",
"the",
"cew",
"Python",
"C",
"extension",
"on",
"Windows",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/setup.py#L69-L145 |
232,160 | readbeyond/aeneas | aeneas/validator.py | Validator.check_file_encoding | def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_file_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_file_encoding"):
return self.result
if not gf.file_can_be_read(input_file_path):
self._failed(u"File '%s' cannot be read." % (input_file_path))
return self.result
with io.open(input_file_path, "rb") as file_object:
bstring = file_object.read()
self._check_utf8_encoding(bstring)
return self.result | python | def check_file_encoding(self, input_file_path):
"""
Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking encoding of file '%s'", input_file_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_file_encoding"):
return self.result
if not gf.file_can_be_read(input_file_path):
self._failed(u"File '%s' cannot be read." % (input_file_path))
return self.result
with io.open(input_file_path, "rb") as file_object:
bstring = file_object.read()
self._check_utf8_encoding(bstring)
return self.result | [
"def",
"check_file_encoding",
"(",
"self",
",",
"input_file_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking encoding of file '%s'\"",
",",
"input_file_path",
"]",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_safety_checks_disabled",
"(",
"u\"check_file_encoding\"",
")",
":",
"return",
"self",
".",
"result",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"input_file_path",
")",
":",
"self",
".",
"_failed",
"(",
"u\"File '%s' cannot be read.\"",
"%",
"(",
"input_file_path",
")",
")",
"return",
"self",
".",
"result",
"with",
"io",
".",
"open",
"(",
"input_file_path",
",",
"\"rb\"",
")",
"as",
"file_object",
":",
"bstring",
"=",
"file_object",
".",
"read",
"(",
")",
"self",
".",
"_check_utf8_encoding",
"(",
"bstring",
")",
"return",
"self",
".",
"result"
] | Check whether the given file is UTF-8 encoded.
:param string input_file_path: the path of the file to be checked
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"file",
"is",
"UTF",
"-",
"8",
"encoded",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L259-L276 |
232,161 | readbeyond/aeneas | aeneas/validator.py | Validator.check_config_xml | def check_config_xml(self, contents):
"""
Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log(u"Checking contents XML config file")
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_config_xml"):
return self.result
contents = gf.safe_bytes(contents)
self.log(u"Checking that contents is well formed")
self.check_raw_string(contents, is_bstring=True)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for job")
job_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=True)
self._check_required_parameters(self.XML_JOB_REQUIRED_PARAMETERS, job_parameters)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for task")
tasks_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=False)
for parameters in tasks_parameters:
self.log([u"Checking required parameters for task: '%s'", parameters])
self._check_required_parameters(self.XML_TASK_REQUIRED_PARAMETERS, parameters)
if not self.result.passed:
return self.result
return self.result | python | def check_config_xml(self, contents):
"""
Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log(u"Checking contents XML config file")
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_config_xml"):
return self.result
contents = gf.safe_bytes(contents)
self.log(u"Checking that contents is well formed")
self.check_raw_string(contents, is_bstring=True)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for job")
job_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=True)
self._check_required_parameters(self.XML_JOB_REQUIRED_PARAMETERS, job_parameters)
if not self.result.passed:
return self.result
self.log(u"Checking required parameters for task")
tasks_parameters = gf.config_xml_to_dict(contents, self.result, parse_job=False)
for parameters in tasks_parameters:
self.log([u"Checking required parameters for task: '%s'", parameters])
self._check_required_parameters(self.XML_TASK_REQUIRED_PARAMETERS, parameters)
if not self.result.passed:
return self.result
return self.result | [
"def",
"check_config_xml",
"(",
"self",
",",
"contents",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking contents XML config file\"",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_safety_checks_disabled",
"(",
"u\"check_config_xml\"",
")",
":",
"return",
"self",
".",
"result",
"contents",
"=",
"gf",
".",
"safe_bytes",
"(",
"contents",
")",
"self",
".",
"log",
"(",
"u\"Checking that contents is well formed\"",
")",
"self",
".",
"check_raw_string",
"(",
"contents",
",",
"is_bstring",
"=",
"True",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"return",
"self",
".",
"result",
"self",
".",
"log",
"(",
"u\"Checking required parameters for job\"",
")",
"job_parameters",
"=",
"gf",
".",
"config_xml_to_dict",
"(",
"contents",
",",
"self",
".",
"result",
",",
"parse_job",
"=",
"True",
")",
"self",
".",
"_check_required_parameters",
"(",
"self",
".",
"XML_JOB_REQUIRED_PARAMETERS",
",",
"job_parameters",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"return",
"self",
".",
"result",
"self",
".",
"log",
"(",
"u\"Checking required parameters for task\"",
")",
"tasks_parameters",
"=",
"gf",
".",
"config_xml_to_dict",
"(",
"contents",
",",
"self",
".",
"result",
",",
"parse_job",
"=",
"False",
")",
"for",
"parameters",
"in",
"tasks_parameters",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking required parameters for task: '%s'\"",
",",
"parameters",
"]",
")",
"self",
".",
"_check_required_parameters",
"(",
"self",
".",
"XML_TASK_REQUIRED_PARAMETERS",
",",
"parameters",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"return",
"self",
".",
"result",
"return",
"self",
".",
"result"
] | Check whether the given XML config file contents
is well-formed and it has all the required parameters.
:param string contents: the XML config file contents or XML config string
:param bool is_config_string: if ``True``, contents is a config string
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"XML",
"config",
"file",
"contents",
"is",
"well",
"-",
"formed",
"and",
"it",
"has",
"all",
"the",
"required",
"parameters",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L380-L410 |
232,162 | readbeyond/aeneas | aeneas/validator.py | Validator.check_container | def check_container(self, container_path, container_format=None, config_string=None):
"""
Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking container '%s'", container_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_container"):
return self.result
if not (gf.file_exists(container_path) or gf.directory_exists(container_path)):
self._failed(u"Container '%s' not found." % container_path)
return self.result
container = Container(container_path, container_format)
try:
self.log(u"Checking container has config file")
if config_string is not None:
self.log(u"Container with config string from wizard")
self.check_config_txt(config_string, is_config_string=True)
elif container.has_config_xml:
self.log(u"Container has XML config file")
contents = container.read_entry(container.entry_config_xml)
if contents is None:
self._failed(u"Unable to read the contents of XML config file.")
return self.result
self.check_config_xml(contents)
elif container.has_config_txt:
self.log(u"Container has TXT config file")
contents = container.read_entry(container.entry_config_txt)
if contents is None:
self._failed(u"Unable to read the contents of TXT config file.")
return self.result
self.check_config_txt(contents, is_config_string=False)
else:
self._failed(u"Container does not have a TXT or XML configuration file.")
self.log(u"Checking we have a valid job in the container")
if not self.result.passed:
return self.result
self.log(u"Analyze the contents of the container")
analyzer = AnalyzeContainer(container)
if config_string is not None:
job = analyzer.analyze(config_string=config_string)
else:
job = analyzer.analyze()
self._check_analyzed_job(job, container)
except OSError:
self._failed(u"Unable to read the contents of the container.")
return self.result | python | def check_container(self, container_path, container_format=None, config_string=None):
"""
Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult`
"""
self.log([u"Checking container '%s'", container_path])
self.result = ValidatorResult()
if self._are_safety_checks_disabled(u"check_container"):
return self.result
if not (gf.file_exists(container_path) or gf.directory_exists(container_path)):
self._failed(u"Container '%s' not found." % container_path)
return self.result
container = Container(container_path, container_format)
try:
self.log(u"Checking container has config file")
if config_string is not None:
self.log(u"Container with config string from wizard")
self.check_config_txt(config_string, is_config_string=True)
elif container.has_config_xml:
self.log(u"Container has XML config file")
contents = container.read_entry(container.entry_config_xml)
if contents is None:
self._failed(u"Unable to read the contents of XML config file.")
return self.result
self.check_config_xml(contents)
elif container.has_config_txt:
self.log(u"Container has TXT config file")
contents = container.read_entry(container.entry_config_txt)
if contents is None:
self._failed(u"Unable to read the contents of TXT config file.")
return self.result
self.check_config_txt(contents, is_config_string=False)
else:
self._failed(u"Container does not have a TXT or XML configuration file.")
self.log(u"Checking we have a valid job in the container")
if not self.result.passed:
return self.result
self.log(u"Analyze the contents of the container")
analyzer = AnalyzeContainer(container)
if config_string is not None:
job = analyzer.analyze(config_string=config_string)
else:
job = analyzer.analyze()
self._check_analyzed_job(job, container)
except OSError:
self._failed(u"Unable to read the contents of the container.")
return self.result | [
"def",
"check_container",
"(",
"self",
",",
"container_path",
",",
"container_format",
"=",
"None",
",",
"config_string",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking container '%s'\"",
",",
"container_path",
"]",
")",
"self",
".",
"result",
"=",
"ValidatorResult",
"(",
")",
"if",
"self",
".",
"_are_safety_checks_disabled",
"(",
"u\"check_container\"",
")",
":",
"return",
"self",
".",
"result",
"if",
"not",
"(",
"gf",
".",
"file_exists",
"(",
"container_path",
")",
"or",
"gf",
".",
"directory_exists",
"(",
"container_path",
")",
")",
":",
"self",
".",
"_failed",
"(",
"u\"Container '%s' not found.\"",
"%",
"container_path",
")",
"return",
"self",
".",
"result",
"container",
"=",
"Container",
"(",
"container_path",
",",
"container_format",
")",
"try",
":",
"self",
".",
"log",
"(",
"u\"Checking container has config file\"",
")",
"if",
"config_string",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"u\"Container with config string from wizard\"",
")",
"self",
".",
"check_config_txt",
"(",
"config_string",
",",
"is_config_string",
"=",
"True",
")",
"elif",
"container",
".",
"has_config_xml",
":",
"self",
".",
"log",
"(",
"u\"Container has XML config file\"",
")",
"contents",
"=",
"container",
".",
"read_entry",
"(",
"container",
".",
"entry_config_xml",
")",
"if",
"contents",
"is",
"None",
":",
"self",
".",
"_failed",
"(",
"u\"Unable to read the contents of XML config file.\"",
")",
"return",
"self",
".",
"result",
"self",
".",
"check_config_xml",
"(",
"contents",
")",
"elif",
"container",
".",
"has_config_txt",
":",
"self",
".",
"log",
"(",
"u\"Container has TXT config file\"",
")",
"contents",
"=",
"container",
".",
"read_entry",
"(",
"container",
".",
"entry_config_txt",
")",
"if",
"contents",
"is",
"None",
":",
"self",
".",
"_failed",
"(",
"u\"Unable to read the contents of TXT config file.\"",
")",
"return",
"self",
".",
"result",
"self",
".",
"check_config_txt",
"(",
"contents",
",",
"is_config_string",
"=",
"False",
")",
"else",
":",
"self",
".",
"_failed",
"(",
"u\"Container does not have a TXT or XML configuration file.\"",
")",
"self",
".",
"log",
"(",
"u\"Checking we have a valid job in the container\"",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"return",
"self",
".",
"result",
"self",
".",
"log",
"(",
"u\"Analyze the contents of the container\"",
")",
"analyzer",
"=",
"AnalyzeContainer",
"(",
"container",
")",
"if",
"config_string",
"is",
"not",
"None",
":",
"job",
"=",
"analyzer",
".",
"analyze",
"(",
"config_string",
"=",
"config_string",
")",
"else",
":",
"job",
"=",
"analyzer",
".",
"analyze",
"(",
")",
"self",
".",
"_check_analyzed_job",
"(",
"job",
",",
"container",
")",
"except",
"OSError",
":",
"self",
".",
"_failed",
"(",
"u\"Unable to read the contents of the container.\"",
")",
"return",
"self",
".",
"result"
] | Check whether the given container is well-formed.
:param string container_path: the path of the container to be checked
:param container_format: the format of the container
:type container_format: :class:`~aeneas.container.ContainerFormat`
:param string config_string: the configuration string generated by the wizard
:rtype: :class:`~aeneas.validator.ValidatorResult` | [
"Check",
"whether",
"the",
"given",
"container",
"is",
"well",
"-",
"formed",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L412-L468 |
232,163 | readbeyond/aeneas | aeneas/validator.py | Validator._are_safety_checks_disabled | def _are_safety_checks_disabled(self, caller=u"unknown_function"):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False
self.log_warn([u"Safety checks disabled => %s passed", caller])
return True | python | def _are_safety_checks_disabled(self, caller=u"unknown_function"):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False
self.log_warn([u"Safety checks disabled => %s passed", caller])
return True | [
"def",
"_are_safety_checks_disabled",
"(",
"self",
",",
"caller",
"=",
"u\"unknown_function\"",
")",
":",
"if",
"self",
".",
"rconf",
".",
"safety_checks",
":",
"return",
"False",
"self",
".",
"log_warn",
"(",
"[",
"u\"Safety checks disabled => %s passed\"",
",",
"caller",
"]",
")",
"return",
"True"
] | Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool | [
"Return",
"True",
"if",
"safety",
"checks",
"are",
"disabled",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L470-L480 |
232,164 | readbeyond/aeneas | aeneas/validator.py | Validator._failed | def _failed(self, msg):
"""
Log a validation failure.
:param string msg: the error message
"""
self.log(msg)
self.result.passed = False
self.result.add_error(msg)
self.log(u"Failed") | python | def _failed(self, msg):
"""
Log a validation failure.
:param string msg: the error message
"""
self.log(msg)
self.result.passed = False
self.result.add_error(msg)
self.log(u"Failed") | [
"def",
"_failed",
"(",
"self",
",",
"msg",
")",
":",
"self",
".",
"log",
"(",
"msg",
")",
"self",
".",
"result",
".",
"passed",
"=",
"False",
"self",
".",
"result",
".",
"add_error",
"(",
"msg",
")",
"self",
".",
"log",
"(",
"u\"Failed\"",
")"
] | Log a validation failure.
:param string msg: the error message | [
"Log",
"a",
"validation",
"failure",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L482-L491 |
232,165 | readbeyond/aeneas | aeneas/validator.py | Validator._check_utf8_encoding | def _check_utf8_encoding(self, bstring):
"""
Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked
"""
if not gf.is_bytes(bstring):
self._failed(u"The given string is not a sequence of bytes")
return
if not gf.is_utf8_encoded(bstring):
self._failed(u"The given string is not encoded in UTF-8.") | python | def _check_utf8_encoding(self, bstring):
"""
Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked
"""
if not gf.is_bytes(bstring):
self._failed(u"The given string is not a sequence of bytes")
return
if not gf.is_utf8_encoded(bstring):
self._failed(u"The given string is not encoded in UTF-8.") | [
"def",
"_check_utf8_encoding",
"(",
"self",
",",
"bstring",
")",
":",
"if",
"not",
"gf",
".",
"is_bytes",
"(",
"bstring",
")",
":",
"self",
".",
"_failed",
"(",
"u\"The given string is not a sequence of bytes\"",
")",
"return",
"if",
"not",
"gf",
".",
"is_utf8_encoded",
"(",
"bstring",
")",
":",
"self",
".",
"_failed",
"(",
"u\"The given string is not encoded in UTF-8.\"",
")"
] | Check whether the given sequence of bytes
is properly encoded in UTF-8.
:param bytes bstring: the byte string to be checked | [
"Check",
"whether",
"the",
"given",
"sequence",
"of",
"bytes",
"is",
"properly",
"encoded",
"in",
"UTF",
"-",
"8",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L493-L504 |
232,166 | readbeyond/aeneas | aeneas/validator.py | Validator._check_reserved_characters | def _check_reserved_characters(self, ustring):
"""
Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked
"""
forbidden = [c for c in gc.CONFIG_RESERVED_CHARACTERS if c in ustring]
if len(forbidden) > 0:
self._failed(u"The given string contains the reserved characters '%s'." % u" ".join(forbidden)) | python | def _check_reserved_characters(self, ustring):
"""
Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked
"""
forbidden = [c for c in gc.CONFIG_RESERVED_CHARACTERS if c in ustring]
if len(forbidden) > 0:
self._failed(u"The given string contains the reserved characters '%s'." % u" ".join(forbidden)) | [
"def",
"_check_reserved_characters",
"(",
"self",
",",
"ustring",
")",
":",
"forbidden",
"=",
"[",
"c",
"for",
"c",
"in",
"gc",
".",
"CONFIG_RESERVED_CHARACTERS",
"if",
"c",
"in",
"ustring",
"]",
"if",
"len",
"(",
"forbidden",
")",
">",
"0",
":",
"self",
".",
"_failed",
"(",
"u\"The given string contains the reserved characters '%s'.\"",
"%",
"u\" \"",
".",
"join",
"(",
"forbidden",
")",
")"
] | Check whether the given Unicode string contains reserved characters.
:param string ustring: the string to be checked | [
"Check",
"whether",
"the",
"given",
"Unicode",
"string",
"contains",
"reserved",
"characters",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L515-L523 |
232,167 | readbeyond/aeneas | aeneas/validator.py | Validator._check_allowed_values | def _check_allowed_values(self, parameters):
"""
Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, allowed_values in self.ALLOWED_VALUES:
self.log([u"Checking allowed values for parameter '%s'", key])
if key in parameters:
value = parameters[key]
if value not in allowed_values:
self._failed(u"Parameter '%s' has value '%s' which is not allowed." % (key, value))
return
self.log(u"Passed") | python | def _check_allowed_values(self, parameters):
"""
Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, allowed_values in self.ALLOWED_VALUES:
self.log([u"Checking allowed values for parameter '%s'", key])
if key in parameters:
value = parameters[key]
if value not in allowed_values:
self._failed(u"Parameter '%s' has value '%s' which is not allowed." % (key, value))
return
self.log(u"Passed") | [
"def",
"_check_allowed_values",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"key",
",",
"allowed_values",
"in",
"self",
".",
"ALLOWED_VALUES",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking allowed values for parameter '%s'\"",
",",
"key",
"]",
")",
"if",
"key",
"in",
"parameters",
":",
"value",
"=",
"parameters",
"[",
"key",
"]",
"if",
"value",
"not",
"in",
"allowed_values",
":",
"self",
".",
"_failed",
"(",
"u\"Parameter '%s' has value '%s' which is not allowed.\"",
"%",
"(",
"key",
",",
"value",
")",
")",
"return",
"self",
".",
"log",
"(",
"u\"Passed\"",
")"
] | Check whether the given parameter value is allowed.
Log messages into ``self.result``.
:param dict parameters: the given parameters | [
"Check",
"whether",
"the",
"given",
"parameter",
"value",
"is",
"allowed",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L525-L539 |
232,168 | readbeyond/aeneas | aeneas/validator.py | Validator._check_implied_parameters | def _check_implied_parameters(self, parameters):
"""
Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, values, implied_keys in self.IMPLIED_PARAMETERS:
self.log([u"Checking implied parameters by '%s'='%s'", key, values])
if (key in parameters) and (parameters[key] in values):
found = False
for implied_key in implied_keys:
if implied_key in parameters:
found = True
if not found:
if len(implied_keys) == 1:
msg = u"Parameter '%s' is required when '%s'='%s'." % (implied_keys[0], key, parameters[key])
else:
msg = u"At least one of [%s] is required when '%s'='%s'." % (",".join(implied_keys), key, parameters[key])
self._failed(msg)
return
self.log(u"Passed") | python | def _check_implied_parameters(self, parameters):
"""
Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters
"""
for key, values, implied_keys in self.IMPLIED_PARAMETERS:
self.log([u"Checking implied parameters by '%s'='%s'", key, values])
if (key in parameters) and (parameters[key] in values):
found = False
for implied_key in implied_keys:
if implied_key in parameters:
found = True
if not found:
if len(implied_keys) == 1:
msg = u"Parameter '%s' is required when '%s'='%s'." % (implied_keys[0], key, parameters[key])
else:
msg = u"At least one of [%s] is required when '%s'='%s'." % (",".join(implied_keys), key, parameters[key])
self._failed(msg)
return
self.log(u"Passed") | [
"def",
"_check_implied_parameters",
"(",
"self",
",",
"parameters",
")",
":",
"for",
"key",
",",
"values",
",",
"implied_keys",
"in",
"self",
".",
"IMPLIED_PARAMETERS",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking implied parameters by '%s'='%s'\"",
",",
"key",
",",
"values",
"]",
")",
"if",
"(",
"key",
"in",
"parameters",
")",
"and",
"(",
"parameters",
"[",
"key",
"]",
"in",
"values",
")",
":",
"found",
"=",
"False",
"for",
"implied_key",
"in",
"implied_keys",
":",
"if",
"implied_key",
"in",
"parameters",
":",
"found",
"=",
"True",
"if",
"not",
"found",
":",
"if",
"len",
"(",
"implied_keys",
")",
"==",
"1",
":",
"msg",
"=",
"u\"Parameter '%s' is required when '%s'='%s'.\"",
"%",
"(",
"implied_keys",
"[",
"0",
"]",
",",
"key",
",",
"parameters",
"[",
"key",
"]",
")",
"else",
":",
"msg",
"=",
"u\"At least one of [%s] is required when '%s'='%s'.\"",
"%",
"(",
"\",\"",
".",
"join",
"(",
"implied_keys",
")",
",",
"key",
",",
"parameters",
"[",
"key",
"]",
")",
"self",
".",
"_failed",
"(",
"msg",
")",
"return",
"self",
".",
"log",
"(",
"u\"Passed\"",
")"
] | Check whether at least one of the keys in implied_keys
is in ``parameters``,
when a given ``key=value`` is present in ``parameters``,
for some value in values.
Log messages into ``self.result``.
:param dict parameters: the given parameters | [
"Check",
"whether",
"at",
"least",
"one",
"of",
"the",
"keys",
"in",
"implied_keys",
"is",
"in",
"parameters",
"when",
"a",
"given",
"key",
"=",
"value",
"is",
"present",
"in",
"parameters",
"for",
"some",
"value",
"in",
"values",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L541-L565 |
232,169 | readbeyond/aeneas | aeneas/validator.py | Validator._check_required_parameters | def _check_required_parameters(
self,
required_parameters,
parameters
):
"""
Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user
"""
self.log([u"Checking required parameters '%s'", required_parameters])
self.log(u"Checking input parameters are not empty")
if (parameters is None) or (len(parameters) == 0):
self._failed(u"No parameters supplied.")
return
self.log(u"Checking no required parameter is missing")
for req_param in required_parameters:
if req_param not in parameters:
self._failed(u"Required parameter '%s' not set." % req_param)
return
self.log(u"Checking all parameter values are allowed")
self._check_allowed_values(parameters)
self.log(u"Checking all implied parameters are present")
self._check_implied_parameters(parameters)
return self.result | python | def _check_required_parameters(
self,
required_parameters,
parameters
):
"""
Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user
"""
self.log([u"Checking required parameters '%s'", required_parameters])
self.log(u"Checking input parameters are not empty")
if (parameters is None) or (len(parameters) == 0):
self._failed(u"No parameters supplied.")
return
self.log(u"Checking no required parameter is missing")
for req_param in required_parameters:
if req_param not in parameters:
self._failed(u"Required parameter '%s' not set." % req_param)
return
self.log(u"Checking all parameter values are allowed")
self._check_allowed_values(parameters)
self.log(u"Checking all implied parameters are present")
self._check_implied_parameters(parameters)
return self.result | [
"def",
"_check_required_parameters",
"(",
"self",
",",
"required_parameters",
",",
"parameters",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking required parameters '%s'\"",
",",
"required_parameters",
"]",
")",
"self",
".",
"log",
"(",
"u\"Checking input parameters are not empty\"",
")",
"if",
"(",
"parameters",
"is",
"None",
")",
"or",
"(",
"len",
"(",
"parameters",
")",
"==",
"0",
")",
":",
"self",
".",
"_failed",
"(",
"u\"No parameters supplied.\"",
")",
"return",
"self",
".",
"log",
"(",
"u\"Checking no required parameter is missing\"",
")",
"for",
"req_param",
"in",
"required_parameters",
":",
"if",
"req_param",
"not",
"in",
"parameters",
":",
"self",
".",
"_failed",
"(",
"u\"Required parameter '%s' not set.\"",
"%",
"req_param",
")",
"return",
"self",
".",
"log",
"(",
"u\"Checking all parameter values are allowed\"",
")",
"self",
".",
"_check_allowed_values",
"(",
"parameters",
")",
"self",
".",
"log",
"(",
"u\"Checking all implied parameters are present\"",
")",
"self",
".",
"_check_implied_parameters",
"(",
"parameters",
")",
"return",
"self",
".",
"result"
] | Check whether the given parameter dictionary contains
all the required paramenters.
Log messages into ``self.result``.
:param list required_parameters: required parameters
:param dict parameters: parameters specified by the user | [
"Check",
"whether",
"the",
"given",
"parameter",
"dictionary",
"contains",
"all",
"the",
"required",
"paramenters",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L567-L594 |
232,170 | readbeyond/aeneas | aeneas/validator.py | Validator._check_analyzed_job | def _check_analyzed_job(self, job, container):
"""
Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container`
"""
self.log(u"Checking the Job object generated from container")
self.log(u"Checking that the Job is not None")
if job is None:
self._failed(u"Unable to create a Job from the container.")
return
self.log(u"Checking that the Job has at least one Task")
if len(job) == 0:
self._failed(u"Unable to create at least one Task from the container.")
return
if self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] > 0:
self.log(u"Checking that the Job does not have too many Tasks")
if len(job) > self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]:
self._failed(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (
len(job),
self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
))
return
self.log(u"Checking that each Task text file is well formed")
for task in job.tasks:
self.log([u"Checking Task text file '%s'", task.text_file_path])
text_file_bstring = container.read_entry(task.text_file_path)
if (text_file_bstring is None) or (len(text_file_bstring) == 0):
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self._check_utf8_encoding(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is not encoded in UTF-8" % task.text_file_path)
return
self._check_not_empty(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self.log([u"Checking Task text file '%s': passed", task.text_file_path])
self.log(u"Checking each Task text file is well formed: passed") | python | def _check_analyzed_job(self, job, container):
"""
Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container`
"""
self.log(u"Checking the Job object generated from container")
self.log(u"Checking that the Job is not None")
if job is None:
self._failed(u"Unable to create a Job from the container.")
return
self.log(u"Checking that the Job has at least one Task")
if len(job) == 0:
self._failed(u"Unable to create at least one Task from the container.")
return
if self.rconf[RuntimeConfiguration.JOB_MAX_TASKS] > 0:
self.log(u"Checking that the Job does not have too many Tasks")
if len(job) > self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]:
self._failed(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (
len(job),
self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
))
return
self.log(u"Checking that each Task text file is well formed")
for task in job.tasks:
self.log([u"Checking Task text file '%s'", task.text_file_path])
text_file_bstring = container.read_entry(task.text_file_path)
if (text_file_bstring is None) or (len(text_file_bstring) == 0):
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self._check_utf8_encoding(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is not encoded in UTF-8" % task.text_file_path)
return
self._check_not_empty(text_file_bstring)
if not self.result.passed:
self._failed(u"Text file '%s' is empty" % task.text_file_path)
return
self.log([u"Checking Task text file '%s': passed", task.text_file_path])
self.log(u"Checking each Task text file is well formed: passed") | [
"def",
"_check_analyzed_job",
"(",
"self",
",",
"job",
",",
"container",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking the Job object generated from container\"",
")",
"self",
".",
"log",
"(",
"u\"Checking that the Job is not None\"",
")",
"if",
"job",
"is",
"None",
":",
"self",
".",
"_failed",
"(",
"u\"Unable to create a Job from the container.\"",
")",
"return",
"self",
".",
"log",
"(",
"u\"Checking that the Job has at least one Task\"",
")",
"if",
"len",
"(",
"job",
")",
"==",
"0",
":",
"self",
".",
"_failed",
"(",
"u\"Unable to create at least one Task from the container.\"",
")",
"return",
"if",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"JOB_MAX_TASKS",
"]",
">",
"0",
":",
"self",
".",
"log",
"(",
"u\"Checking that the Job does not have too many Tasks\"",
")",
"if",
"len",
"(",
"job",
")",
">",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"JOB_MAX_TASKS",
"]",
":",
"self",
".",
"_failed",
"(",
"u\"The Job has %d Tasks, more than the maximum allowed (%d).\"",
"%",
"(",
"len",
"(",
"job",
")",
",",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"JOB_MAX_TASKS",
"]",
")",
")",
"return",
"self",
".",
"log",
"(",
"u\"Checking that each Task text file is well formed\"",
")",
"for",
"task",
"in",
"job",
".",
"tasks",
":",
"self",
".",
"log",
"(",
"[",
"u\"Checking Task text file '%s'\"",
",",
"task",
".",
"text_file_path",
"]",
")",
"text_file_bstring",
"=",
"container",
".",
"read_entry",
"(",
"task",
".",
"text_file_path",
")",
"if",
"(",
"text_file_bstring",
"is",
"None",
")",
"or",
"(",
"len",
"(",
"text_file_bstring",
")",
"==",
"0",
")",
":",
"self",
".",
"_failed",
"(",
"u\"Text file '%s' is empty\"",
"%",
"task",
".",
"text_file_path",
")",
"return",
"self",
".",
"_check_utf8_encoding",
"(",
"text_file_bstring",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"self",
".",
"_failed",
"(",
"u\"Text file '%s' is not encoded in UTF-8\"",
"%",
"task",
".",
"text_file_path",
")",
"return",
"self",
".",
"_check_not_empty",
"(",
"text_file_bstring",
")",
"if",
"not",
"self",
".",
"result",
".",
"passed",
":",
"self",
".",
"_failed",
"(",
"u\"Text file '%s' is empty\"",
"%",
"task",
".",
"text_file_path",
")",
"return",
"self",
".",
"log",
"(",
"[",
"u\"Checking Task text file '%s': passed\"",
",",
"task",
".",
"text_file_path",
"]",
")",
"self",
".",
"log",
"(",
"u\"Checking each Task text file is well formed: passed\"",
")"
] | Check that the job object generated from the given container
is well formed, that it has at least one task,
and that the text file of each task has the correct encoding.
Log messages into ``self.result``.
:param job: the Job object generated from container
:type job: :class:`~aeneas.job.Job`
:param container: the Container object
:type container: :class:`~aeneas.container.Container` | [
"Check",
"that",
"the",
"job",
"object",
"generated",
"from",
"the",
"given",
"container",
"is",
"well",
"formed",
"that",
"it",
"has",
"at",
"least",
"one",
"task",
"and",
"that",
"the",
"text",
"file",
"of",
"each",
"task",
"has",
"the",
"correct",
"encoding",
".",
"Log",
"messages",
"into",
"self",
".",
"result",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L596-L645 |
232,171 | readbeyond/aeneas | aeneas/validator.py | ValidatorResult.pretty_print | def pretty_print(self, warnings=False):
"""
Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string
"""
msg = []
if (warnings) and (len(self.warnings) > 0):
msg.append(u"Warnings:")
for warning in self.warnings:
msg.append(u" %s" % warning)
if len(self.errors) > 0:
msg.append(u"Errors:")
for error in self.errors:
msg.append(u" %s" % error)
return u"\n".join(msg) | python | def pretty_print(self, warnings=False):
"""
Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string
"""
msg = []
if (warnings) and (len(self.warnings) > 0):
msg.append(u"Warnings:")
for warning in self.warnings:
msg.append(u" %s" % warning)
if len(self.errors) > 0:
msg.append(u"Errors:")
for error in self.errors:
msg.append(u" %s" % error)
return u"\n".join(msg) | [
"def",
"pretty_print",
"(",
"self",
",",
"warnings",
"=",
"False",
")",
":",
"msg",
"=",
"[",
"]",
"if",
"(",
"warnings",
")",
"and",
"(",
"len",
"(",
"self",
".",
"warnings",
")",
">",
"0",
")",
":",
"msg",
".",
"append",
"(",
"u\"Warnings:\"",
")",
"for",
"warning",
"in",
"self",
".",
"warnings",
":",
"msg",
".",
"append",
"(",
"u\" %s\"",
"%",
"warning",
")",
"if",
"len",
"(",
"self",
".",
"errors",
")",
">",
"0",
":",
"msg",
".",
"append",
"(",
"u\"Errors:\"",
")",
"for",
"error",
"in",
"self",
".",
"errors",
":",
"msg",
".",
"append",
"(",
"u\" %s\"",
"%",
"error",
")",
"return",
"u\"\\n\"",
".",
"join",
"(",
"msg",
")"
] | Pretty print warnings and errors.
:param bool warnings: if ``True``, also print warnings.
:rtype: string | [
"Pretty",
"print",
"warnings",
"and",
"errors",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/validator.py#L670-L686 |
232,172 | readbeyond/aeneas | aeneas/ffmpegwrapper.py | FFMPEGWrapper.convert | def convert(
self,
input_file_path,
output_file_path,
head_length=None,
process_length=None
):
"""
Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written
"""
# test if we can read the input file
if not gf.file_can_be_read(input_file_path):
self.log_exc(u"Input file '%s' cannot be read" % (input_file_path), None, True, OSError)
# test if we can write the output file
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Output file '%s' cannot be written" % (output_file_path), None, True, OSError)
# call ffmpeg
arguments = [self.rconf[RuntimeConfiguration.FFMPEG_PATH]]
arguments.extend(["-i", input_file_path])
if head_length is not None:
arguments.extend(["-ss", head_length])
if process_length is not None:
arguments.extend(["-t", process_length])
if self.rconf.sample_rate in self.FFMPEG_PARAMETERS_MAP:
arguments.extend(self.FFMPEG_PARAMETERS_MAP[self.rconf.sample_rate])
else:
arguments.extend(self.FFMPEG_PARAMETERS_DEFAULT)
arguments.append(output_file_path)
self.log([u"Calling with arguments '%s'", arguments])
try:
proc = subprocess.Popen(
arguments,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
proc.communicate()
proc.stdout.close()
proc.stdin.close()
proc.stderr.close()
except OSError as exc:
self.log_exc(u"Unable to call the '%s' ffmpeg executable" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]), exc, True, FFMPEGPathError)
self.log(u"Call completed")
# check if the output file exists
if not gf.file_exists(output_file_path):
self.log_exc(u"Output file '%s' was not written" % (output_file_path), None, True, OSError)
# returning the output file path
self.log([u"Returning output file path '%s'", output_file_path])
return output_file_path | python | def convert(
self,
input_file_path,
output_file_path,
head_length=None,
process_length=None
):
"""
Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written
"""
# test if we can read the input file
if not gf.file_can_be_read(input_file_path):
self.log_exc(u"Input file '%s' cannot be read" % (input_file_path), None, True, OSError)
# test if we can write the output file
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Output file '%s' cannot be written" % (output_file_path), None, True, OSError)
# call ffmpeg
arguments = [self.rconf[RuntimeConfiguration.FFMPEG_PATH]]
arguments.extend(["-i", input_file_path])
if head_length is not None:
arguments.extend(["-ss", head_length])
if process_length is not None:
arguments.extend(["-t", process_length])
if self.rconf.sample_rate in self.FFMPEG_PARAMETERS_MAP:
arguments.extend(self.FFMPEG_PARAMETERS_MAP[self.rconf.sample_rate])
else:
arguments.extend(self.FFMPEG_PARAMETERS_DEFAULT)
arguments.append(output_file_path)
self.log([u"Calling with arguments '%s'", arguments])
try:
proc = subprocess.Popen(
arguments,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
proc.communicate()
proc.stdout.close()
proc.stdin.close()
proc.stderr.close()
except OSError as exc:
self.log_exc(u"Unable to call the '%s' ffmpeg executable" % (self.rconf[RuntimeConfiguration.FFMPEG_PATH]), exc, True, FFMPEGPathError)
self.log(u"Call completed")
# check if the output file exists
if not gf.file_exists(output_file_path):
self.log_exc(u"Output file '%s' was not written" % (output_file_path), None, True, OSError)
# returning the output file path
self.log([u"Returning output file path '%s'", output_file_path])
return output_file_path | [
"def",
"convert",
"(",
"self",
",",
"input_file_path",
",",
"output_file_path",
",",
"head_length",
"=",
"None",
",",
"process_length",
"=",
"None",
")",
":",
"# test if we can read the input file",
"if",
"not",
"gf",
".",
"file_can_be_read",
"(",
"input_file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Input file '%s' cannot be read\"",
"%",
"(",
"input_file_path",
")",
",",
"None",
",",
"True",
",",
"OSError",
")",
"# test if we can write the output file",
"if",
"not",
"gf",
".",
"file_can_be_written",
"(",
"output_file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Output file '%s' cannot be written\"",
"%",
"(",
"output_file_path",
")",
",",
"None",
",",
"True",
",",
"OSError",
")",
"# call ffmpeg",
"arguments",
"=",
"[",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"FFMPEG_PATH",
"]",
"]",
"arguments",
".",
"extend",
"(",
"[",
"\"-i\"",
",",
"input_file_path",
"]",
")",
"if",
"head_length",
"is",
"not",
"None",
":",
"arguments",
".",
"extend",
"(",
"[",
"\"-ss\"",
",",
"head_length",
"]",
")",
"if",
"process_length",
"is",
"not",
"None",
":",
"arguments",
".",
"extend",
"(",
"[",
"\"-t\"",
",",
"process_length",
"]",
")",
"if",
"self",
".",
"rconf",
".",
"sample_rate",
"in",
"self",
".",
"FFMPEG_PARAMETERS_MAP",
":",
"arguments",
".",
"extend",
"(",
"self",
".",
"FFMPEG_PARAMETERS_MAP",
"[",
"self",
".",
"rconf",
".",
"sample_rate",
"]",
")",
"else",
":",
"arguments",
".",
"extend",
"(",
"self",
".",
"FFMPEG_PARAMETERS_DEFAULT",
")",
"arguments",
".",
"append",
"(",
"output_file_path",
")",
"self",
".",
"log",
"(",
"[",
"u\"Calling with arguments '%s'\"",
",",
"arguments",
"]",
")",
"try",
":",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"arguments",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"proc",
".",
"communicate",
"(",
")",
"proc",
".",
"stdout",
".",
"close",
"(",
")",
"proc",
".",
"stdin",
".",
"close",
"(",
")",
"proc",
".",
"stderr",
".",
"close",
"(",
")",
"except",
"OSError",
"as",
"exc",
":",
"self",
".",
"log_exc",
"(",
"u\"Unable to call the '%s' ffmpeg executable\"",
"%",
"(",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"FFMPEG_PATH",
"]",
")",
",",
"exc",
",",
"True",
",",
"FFMPEGPathError",
")",
"self",
".",
"log",
"(",
"u\"Call completed\"",
")",
"# check if the output file exists",
"if",
"not",
"gf",
".",
"file_exists",
"(",
"output_file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Output file '%s' was not written\"",
"%",
"(",
"output_file_path",
")",
",",
"None",
",",
"True",
",",
"OSError",
")",
"# returning the output file path",
"self",
".",
"log",
"(",
"[",
"u\"Returning output file path '%s'\"",
",",
"output_file_path",
"]",
")",
"return",
"output_file_path"
] | Convert the audio file at ``input_file_path``
into ``output_file_path``,
using the parameters set in the constructor
or through the ``parameters`` property.
You can skip the beginning of the audio file
by specifying ``head_length`` seconds to skip
(if it is ``None``, start at time zero),
and you can specify to convert
only ``process_length`` seconds
(if it is ``None``, process the entire input file length).
By specifying both ``head_length`` and ``process_length``,
you can skip a portion at the beginning and at the end
of the original input file.
:param string input_file_path: the path of the audio file to convert
:param string output_file_path: the path of the converted audio file
:param float head_length: skip these many seconds
from the beginning of the audio file
:param float process_length: process these many seconds of the audio file
:raises: :class:`~aeneas.ffmpegwrapper.FFMPEGPathError`: if the path to the ``ffmpeg`` executable cannot be called
:raises: OSError: if ``input_file_path`` does not exist
or ``output_file_path`` cannot be written | [
"Convert",
"the",
"audio",
"file",
"at",
"input_file_path",
"into",
"output_file_path",
"using",
"the",
"parameters",
"set",
"in",
"the",
"constructor",
"or",
"through",
"the",
"parameters",
"property",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ffmpegwrapper.py#L163-L238 |
232,173 | readbeyond/aeneas | aeneas/syncmap/fragment.py | SyncMapFragment.rate_lack | def rate_lack(self, max_rate):
"""
The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return self.chars / max_rate - self.length
return TimeValue("0.000") | python | def rate_lack(self, max_rate):
"""
The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return self.chars / max_rate - self.length
return TimeValue("0.000") | [
"def",
"rate_lack",
"(",
"self",
",",
"max_rate",
")",
":",
"if",
"self",
".",
"fragment_type",
"==",
"self",
".",
"REGULAR",
":",
"return",
"self",
".",
"chars",
"/",
"max_rate",
"-",
"self",
".",
"length",
"return",
"TimeValue",
"(",
"\"0.000\"",
")"
] | The time interval that this fragment lacks
to respect the given max rate.
A positive value means that the current fragment
is faster than the max rate (bad).
A negative or zero value means that the current fragment
has rate slower or equal to the max rate (good).
Always return ``0.000`` for fragments that are not ``REGULAR``.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0 | [
"The",
"time",
"interval",
"that",
"this",
"fragment",
"lacks",
"to",
"respect",
"the",
"given",
"max",
"rate",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragment.py#L341-L361 |
232,174 | readbeyond/aeneas | aeneas/syncmap/fragment.py | SyncMapFragment.rate_slack | def rate_slack(self, max_rate):
"""
The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return -self.rate_lack(max_rate)
elif self.fragment_type == self.NONSPEECH:
return self.length
else:
return TimeValue("0.000") | python | def rate_slack(self, max_rate):
"""
The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0
"""
if self.fragment_type == self.REGULAR:
return -self.rate_lack(max_rate)
elif self.fragment_type == self.NONSPEECH:
return self.length
else:
return TimeValue("0.000") | [
"def",
"rate_slack",
"(",
"self",
",",
"max_rate",
")",
":",
"if",
"self",
".",
"fragment_type",
"==",
"self",
".",
"REGULAR",
":",
"return",
"-",
"self",
".",
"rate_lack",
"(",
"max_rate",
")",
"elif",
"self",
".",
"fragment_type",
"==",
"self",
".",
"NONSPEECH",
":",
"return",
"self",
".",
"length",
"else",
":",
"return",
"TimeValue",
"(",
"\"0.000\"",
")"
] | The maximum time interval that can be stolen to this fragment
while keeping it respecting the given max rate.
For ``REGULAR`` fragments this value is
the opposite of the ``rate_lack``.
For ``NONSPEECH`` fragments this value is equal to
the length of the fragment.
For ``HEAD`` and ``TAIL`` fragments this value is ``0.000``,
meaning that they cannot be stolen.
:param max_rate: the maximum rate (characters/second)
:type max_rate: :class:`~aeneas.exacttiming.Decimal`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
.. versionadded:: 1.7.0 | [
"The",
"maximum",
"time",
"interval",
"that",
"can",
"be",
"stolen",
"to",
"this",
"fragment",
"while",
"keeping",
"it",
"respecting",
"the",
"given",
"max",
"rate",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragment.py#L363-L386 |
232,175 | readbeyond/aeneas | aeneas/tools/run_vad.py | RunVADCLI.write_to_file | def write_to_file(self, output_file_path, intervals, template):
"""
Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples
"""
msg = [template % (interval) for interval in intervals]
if output_file_path is None:
self.print_info(u"Intervals detected:")
for line in msg:
self.print_generic(line)
else:
with io.open(output_file_path, "w", encoding="utf-8") as output_file:
output_file.write(u"\n".join(msg))
self.print_success(u"Created file '%s'" % output_file_path) | python | def write_to_file(self, output_file_path, intervals, template):
"""
Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples
"""
msg = [template % (interval) for interval in intervals]
if output_file_path is None:
self.print_info(u"Intervals detected:")
for line in msg:
self.print_generic(line)
else:
with io.open(output_file_path, "w", encoding="utf-8") as output_file:
output_file.write(u"\n".join(msg))
self.print_success(u"Created file '%s'" % output_file_path) | [
"def",
"write_to_file",
"(",
"self",
",",
"output_file_path",
",",
"intervals",
",",
"template",
")",
":",
"msg",
"=",
"[",
"template",
"%",
"(",
"interval",
")",
"for",
"interval",
"in",
"intervals",
"]",
"if",
"output_file_path",
"is",
"None",
":",
"self",
".",
"print_info",
"(",
"u\"Intervals detected:\"",
")",
"for",
"line",
"in",
"msg",
":",
"self",
".",
"print_generic",
"(",
"line",
")",
"else",
":",
"with",
"io",
".",
"open",
"(",
"output_file_path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"output_file",
":",
"output_file",
".",
"write",
"(",
"u\"\\n\"",
".",
"join",
"(",
"msg",
")",
")",
"self",
".",
"print_success",
"(",
"u\"Created file '%s'\"",
"%",
"output_file_path",
")"
] | Write intervals to file.
:param output_file_path: path of the output file to be written;
if ``None``, print to stdout
:type output_file_path: string (path)
:param intervals: a list of tuples, each representing an interval
:type intervals: list of tuples | [
"Write",
"intervals",
"to",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/run_vad.py#L145-L163 |
232,176 | readbeyond/aeneas | aeneas/tools/execute_job.py | ExecuteJobCLI.print_parameters | def print_parameters(self):
"""
Print the list of parameters and exit.
"""
self.print_info(u"Available parameters:")
self.print_generic(u"\n" + u"\n".join(self.PARAMETERS) + u"\n")
return self.HELP_EXIT_CODE | python | def print_parameters(self):
"""
Print the list of parameters and exit.
"""
self.print_info(u"Available parameters:")
self.print_generic(u"\n" + u"\n".join(self.PARAMETERS) + u"\n")
return self.HELP_EXIT_CODE | [
"def",
"print_parameters",
"(",
"self",
")",
":",
"self",
".",
"print_info",
"(",
"u\"Available parameters:\"",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
"+",
"u\"\\n\"",
".",
"join",
"(",
"self",
".",
"PARAMETERS",
")",
"+",
"u\"\\n\"",
")",
"return",
"self",
".",
"HELP_EXIT_CODE"
] | Print the list of parameters and exit. | [
"Print",
"the",
"list",
"of",
"parameters",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/execute_job.py#L148-L154 |
232,177 | readbeyond/aeneas | aeneas/cewsubprocess.py | main | def main():
"""
Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file.
"""
# make sure we have enough parameters
if len(sys.argv) < 6:
print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
return 1
# read parameters
c_quit_after = float(sys.argv[1]) # NOTE: cew needs float, not TimeValue
c_backwards = int(sys.argv[2])
text_file_path = sys.argv[3]
audio_file_path = sys.argv[4]
data_file_path = sys.argv[5]
# read (voice_code, text) from file
s_text = []
with io.open(text_file_path, "r", encoding="utf-8") as text:
for line in text.readlines():
# NOTE: not using strip() to avoid removing trailing blank characters
line = line.replace(u"\n", u"").replace(u"\r", u"")
idx = line.find(" ")
if idx > 0:
f_voice_code = line[:idx]
f_text = line[(idx + 1):]
s_text.append((f_voice_code, f_text))
# convert to bytes/unicode as required by subprocess
c_text = []
if gf.PY2:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
else:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))
try:
import aeneas.cew.cew
sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
audio_file_path,
c_quit_after,
c_backwards,
c_text
)
with io.open(data_file_path, "w", encoding="utf-8") as data:
data.write(u"%d\n" % (sr))
data.write(u"%d\n" % (sf))
data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
except Exception as exc:
print(u"Unexpected error: %s" % str(exc)) | python | def main():
"""
Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file.
"""
# make sure we have enough parameters
if len(sys.argv) < 6:
print("You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH")
return 1
# read parameters
c_quit_after = float(sys.argv[1]) # NOTE: cew needs float, not TimeValue
c_backwards = int(sys.argv[2])
text_file_path = sys.argv[3]
audio_file_path = sys.argv[4]
data_file_path = sys.argv[5]
# read (voice_code, text) from file
s_text = []
with io.open(text_file_path, "r", encoding="utf-8") as text:
for line in text.readlines():
# NOTE: not using strip() to avoid removing trailing blank characters
line = line.replace(u"\n", u"").replace(u"\r", u"")
idx = line.find(" ")
if idx > 0:
f_voice_code = line[:idx]
f_text = line[(idx + 1):]
s_text.append((f_voice_code, f_text))
# convert to bytes/unicode as required by subprocess
c_text = []
if gf.PY2:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_bytes(f_voice_code), gf.safe_bytes(f_text)))
else:
for f_voice_code, f_text in s_text:
c_text.append((gf.safe_unicode(f_voice_code), gf.safe_unicode(f_text)))
try:
import aeneas.cew.cew
sr, sf, intervals = aeneas.cew.cew.synthesize_multiple(
audio_file_path,
c_quit_after,
c_backwards,
c_text
)
with io.open(data_file_path, "w", encoding="utf-8") as data:
data.write(u"%d\n" % (sr))
data.write(u"%d\n" % (sf))
data.write(u"\n".join([u"%.3f %.3f" % (i[0], i[1]) for i in intervals]))
except Exception as exc:
print(u"Unexpected error: %s" % str(exc)) | [
"def",
"main",
"(",
")",
":",
"# make sure we have enough parameters",
"if",
"len",
"(",
"sys",
".",
"argv",
")",
"<",
"6",
":",
"print",
"(",
"\"You must pass five arguments: QUIT_AFTER BACKWARDS TEXT_FILE_PATH AUDIO_FILE_PATH DATA_FILE_PATH\"",
")",
"return",
"1",
"# read parameters",
"c_quit_after",
"=",
"float",
"(",
"sys",
".",
"argv",
"[",
"1",
"]",
")",
"# NOTE: cew needs float, not TimeValue",
"c_backwards",
"=",
"int",
"(",
"sys",
".",
"argv",
"[",
"2",
"]",
")",
"text_file_path",
"=",
"sys",
".",
"argv",
"[",
"3",
"]",
"audio_file_path",
"=",
"sys",
".",
"argv",
"[",
"4",
"]",
"data_file_path",
"=",
"sys",
".",
"argv",
"[",
"5",
"]",
"# read (voice_code, text) from file",
"s_text",
"=",
"[",
"]",
"with",
"io",
".",
"open",
"(",
"text_file_path",
",",
"\"r\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"text",
":",
"for",
"line",
"in",
"text",
".",
"readlines",
"(",
")",
":",
"# NOTE: not using strip() to avoid removing trailing blank characters",
"line",
"=",
"line",
".",
"replace",
"(",
"u\"\\n\"",
",",
"u\"\"",
")",
".",
"replace",
"(",
"u\"\\r\"",
",",
"u\"\"",
")",
"idx",
"=",
"line",
".",
"find",
"(",
"\" \"",
")",
"if",
"idx",
">",
"0",
":",
"f_voice_code",
"=",
"line",
"[",
":",
"idx",
"]",
"f_text",
"=",
"line",
"[",
"(",
"idx",
"+",
"1",
")",
":",
"]",
"s_text",
".",
"append",
"(",
"(",
"f_voice_code",
",",
"f_text",
")",
")",
"# convert to bytes/unicode as required by subprocess",
"c_text",
"=",
"[",
"]",
"if",
"gf",
".",
"PY2",
":",
"for",
"f_voice_code",
",",
"f_text",
"in",
"s_text",
":",
"c_text",
".",
"append",
"(",
"(",
"gf",
".",
"safe_bytes",
"(",
"f_voice_code",
")",
",",
"gf",
".",
"safe_bytes",
"(",
"f_text",
")",
")",
")",
"else",
":",
"for",
"f_voice_code",
",",
"f_text",
"in",
"s_text",
":",
"c_text",
".",
"append",
"(",
"(",
"gf",
".",
"safe_unicode",
"(",
"f_voice_code",
")",
",",
"gf",
".",
"safe_unicode",
"(",
"f_text",
")",
")",
")",
"try",
":",
"import",
"aeneas",
".",
"cew",
".",
"cew",
"sr",
",",
"sf",
",",
"intervals",
"=",
"aeneas",
".",
"cew",
".",
"cew",
".",
"synthesize_multiple",
"(",
"audio_file_path",
",",
"c_quit_after",
",",
"c_backwards",
",",
"c_text",
")",
"with",
"io",
".",
"open",
"(",
"data_file_path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"data",
":",
"data",
".",
"write",
"(",
"u\"%d\\n\"",
"%",
"(",
"sr",
")",
")",
"data",
".",
"write",
"(",
"u\"%d\\n\"",
"%",
"(",
"sf",
")",
")",
"data",
".",
"write",
"(",
"u\"\\n\"",
".",
"join",
"(",
"[",
"u\"%.3f %.3f\"",
"%",
"(",
"i",
"[",
"0",
"]",
",",
"i",
"[",
"1",
"]",
")",
"for",
"i",
"in",
"intervals",
"]",
")",
")",
"except",
"Exception",
"as",
"exc",
":",
"print",
"(",
"u\"Unexpected error: %s\"",
"%",
"str",
"(",
"exc",
")",
")"
] | Run ``aeneas.cew``, reading input text from file and writing audio and interval data to file. | [
"Run",
"aeneas",
".",
"cew",
"reading",
"input",
"text",
"from",
"file",
"and",
"writing",
"audio",
"and",
"interval",
"data",
"to",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/cewsubprocess.py#L137-L188 |
232,178 | readbeyond/aeneas | aeneas/syncmap/smfsmil.py | SyncMapFormatSMIL.parse | def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated
"""
from lxml import etree
smil_ns = "{http://www.w3.org/ns/SMIL}"
root = etree.fromstring(gf.safe_bytes(input_text))
for par in root.iter(smil_ns + "par"):
for child in par:
if child.tag == (smil_ns + "text"):
identifier = gf.safe_unicode(gf.split_url(child.get("src"))[1])
elif child.tag == (smil_ns + "audio"):
begin_text = child.get("clipBegin")
if ":" in begin_text:
begin = gf.time_from_hhmmssmmm(begin_text)
else:
begin = gf.time_from_ssmmm(begin_text)
end_text = child.get("clipEnd")
if ":" in end_text:
end = gf.time_from_hhmmssmmm(end_text)
else:
end = gf.time_from_ssmmm(end_text)
# TODO read text from additional text_file?
self._add_fragment(
syncmap=syncmap,
identifier=identifier,
lines=[u""],
begin=begin,
end=end
) | python | def parse(self, input_text, syncmap):
"""
Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated
"""
from lxml import etree
smil_ns = "{http://www.w3.org/ns/SMIL}"
root = etree.fromstring(gf.safe_bytes(input_text))
for par in root.iter(smil_ns + "par"):
for child in par:
if child.tag == (smil_ns + "text"):
identifier = gf.safe_unicode(gf.split_url(child.get("src"))[1])
elif child.tag == (smil_ns + "audio"):
begin_text = child.get("clipBegin")
if ":" in begin_text:
begin = gf.time_from_hhmmssmmm(begin_text)
else:
begin = gf.time_from_ssmmm(begin_text)
end_text = child.get("clipEnd")
if ":" in end_text:
end = gf.time_from_hhmmssmmm(end_text)
else:
end = gf.time_from_ssmmm(end_text)
# TODO read text from additional text_file?
self._add_fragment(
syncmap=syncmap,
identifier=identifier,
lines=[u""],
begin=begin,
end=end
) | [
"def",
"parse",
"(",
"self",
",",
"input_text",
",",
"syncmap",
")",
":",
"from",
"lxml",
"import",
"etree",
"smil_ns",
"=",
"\"{http://www.w3.org/ns/SMIL}\"",
"root",
"=",
"etree",
".",
"fromstring",
"(",
"gf",
".",
"safe_bytes",
"(",
"input_text",
")",
")",
"for",
"par",
"in",
"root",
".",
"iter",
"(",
"smil_ns",
"+",
"\"par\"",
")",
":",
"for",
"child",
"in",
"par",
":",
"if",
"child",
".",
"tag",
"==",
"(",
"smil_ns",
"+",
"\"text\"",
")",
":",
"identifier",
"=",
"gf",
".",
"safe_unicode",
"(",
"gf",
".",
"split_url",
"(",
"child",
".",
"get",
"(",
"\"src\"",
")",
")",
"[",
"1",
"]",
")",
"elif",
"child",
".",
"tag",
"==",
"(",
"smil_ns",
"+",
"\"audio\"",
")",
":",
"begin_text",
"=",
"child",
".",
"get",
"(",
"\"clipBegin\"",
")",
"if",
"\":\"",
"in",
"begin_text",
":",
"begin",
"=",
"gf",
".",
"time_from_hhmmssmmm",
"(",
"begin_text",
")",
"else",
":",
"begin",
"=",
"gf",
".",
"time_from_ssmmm",
"(",
"begin_text",
")",
"end_text",
"=",
"child",
".",
"get",
"(",
"\"clipEnd\"",
")",
"if",
"\":\"",
"in",
"end_text",
":",
"end",
"=",
"gf",
".",
"time_from_hhmmssmmm",
"(",
"end_text",
")",
"else",
":",
"end",
"=",
"gf",
".",
"time_from_ssmmm",
"(",
"end_text",
")",
"# TODO read text from additional text_file?",
"self",
".",
"_add_fragment",
"(",
"syncmap",
"=",
"syncmap",
",",
"identifier",
"=",
"identifier",
",",
"lines",
"=",
"[",
"u\"\"",
"]",
",",
"begin",
"=",
"begin",
",",
"end",
"=",
"end",
")"
] | Read from SMIL file.
Limitations:
1. parses only ``<par>`` elements, in order
2. timings must have ``hh:mm:ss.mmm`` or ``ss.mmm`` format (autodetected)
3. both ``clipBegin`` and ``clipEnd`` attributes of ``<audio>`` must be populated | [
"Read",
"from",
"SMIL",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfsmil.py#L55-L89 |
232,179 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList._is_valid_index | def _is_valid_index(self, index):
"""
Return ``True`` if and only if the given ``index``
is valid.
"""
if isinstance(index, int):
return (index >= 0) and (index < len(self))
if isinstance(index, list):
valid = True
for i in index:
valid = valid or self._is_valid_index(i)
return valid
return False | python | def _is_valid_index(self, index):
"""
Return ``True`` if and only if the given ``index``
is valid.
"""
if isinstance(index, int):
return (index >= 0) and (index < len(self))
if isinstance(index, list):
valid = True
for i in index:
valid = valid or self._is_valid_index(i)
return valid
return False | [
"def",
"_is_valid_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"return",
"(",
"index",
">=",
"0",
")",
"and",
"(",
"index",
"<",
"len",
"(",
"self",
")",
")",
"if",
"isinstance",
"(",
"index",
",",
"list",
")",
":",
"valid",
"=",
"True",
"for",
"i",
"in",
"index",
":",
"valid",
"=",
"valid",
"or",
"self",
".",
"_is_valid_index",
"(",
"i",
")",
"return",
"valid",
"return",
"False"
] | Return ``True`` if and only if the given ``index``
is valid. | [
"Return",
"True",
"if",
"and",
"only",
"if",
"the",
"given",
"index",
"is",
"valid",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L105-L117 |
232,180 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList._check_boundaries | def _check_boundaries(self, fragment):
"""
Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK.
"""
if not isinstance(fragment, SyncMapFragment):
raise TypeError(u"fragment is not an instance of SyncMapFragment")
interval = fragment.interval
if not isinstance(interval, TimeInterval):
raise TypeError(u"interval is not an instance of TimeInterval")
if (self.begin is not None) and (interval.begin < self.begin):
raise ValueError(u"interval.begin is before self.begin")
if (self.end is not None) and (interval.end > self.end):
raise ValueError(u"interval.end is after self.end") | python | def _check_boundaries(self, fragment):
"""
Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK.
"""
if not isinstance(fragment, SyncMapFragment):
raise TypeError(u"fragment is not an instance of SyncMapFragment")
interval = fragment.interval
if not isinstance(interval, TimeInterval):
raise TypeError(u"interval is not an instance of TimeInterval")
if (self.begin is not None) and (interval.begin < self.begin):
raise ValueError(u"interval.begin is before self.begin")
if (self.end is not None) and (interval.end > self.end):
raise ValueError(u"interval.end is after self.end") | [
"def",
"_check_boundaries",
"(",
"self",
",",
"fragment",
")",
":",
"if",
"not",
"isinstance",
"(",
"fragment",
",",
"SyncMapFragment",
")",
":",
"raise",
"TypeError",
"(",
"u\"fragment is not an instance of SyncMapFragment\"",
")",
"interval",
"=",
"fragment",
".",
"interval",
"if",
"not",
"isinstance",
"(",
"interval",
",",
"TimeInterval",
")",
":",
"raise",
"TypeError",
"(",
"u\"interval is not an instance of TimeInterval\"",
")",
"if",
"(",
"self",
".",
"begin",
"is",
"not",
"None",
")",
"and",
"(",
"interval",
".",
"begin",
"<",
"self",
".",
"begin",
")",
":",
"raise",
"ValueError",
"(",
"u\"interval.begin is before self.begin\"",
")",
"if",
"(",
"self",
".",
"end",
"is",
"not",
"None",
")",
"and",
"(",
"interval",
".",
"end",
">",
"self",
".",
"end",
")",
":",
"raise",
"ValueError",
"(",
"u\"interval.end is after self.end\"",
")"
] | Check that the interval of the given fragment
is within the boundaries of the list.
Raises an error if not OK. | [
"Check",
"that",
"the",
"interval",
"of",
"the",
"given",
"fragment",
"is",
"within",
"the",
"boundaries",
"of",
"the",
"list",
".",
"Raises",
"an",
"error",
"if",
"not",
"OK",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L119-L133 |
232,181 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.remove | def remove(self, indices):
"""
Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid
"""
if not self._is_valid_index(indices):
self.log_exc(u"The given list of indices is not valid", None, True, ValueError)
new_fragments = []
sorted_indices = sorted(indices)
i = 0
j = 0
while (i < len(self)) and (j < len(sorted_indices)):
if i != sorted_indices[j]:
new_fragments.append(self[i])
else:
j += 1
i += 1
while i < len(self):
new_fragments.append(self[i])
i += 1
self.__fragments = new_fragments | python | def remove(self, indices):
"""
Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid
"""
if not self._is_valid_index(indices):
self.log_exc(u"The given list of indices is not valid", None, True, ValueError)
new_fragments = []
sorted_indices = sorted(indices)
i = 0
j = 0
while (i < len(self)) and (j < len(sorted_indices)):
if i != sorted_indices[j]:
new_fragments.append(self[i])
else:
j += 1
i += 1
while i < len(self):
new_fragments.append(self[i])
i += 1
self.__fragments = new_fragments | [
"def",
"remove",
"(",
"self",
",",
"indices",
")",
":",
"if",
"not",
"self",
".",
"_is_valid_index",
"(",
"indices",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The given list of indices is not valid\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"new_fragments",
"=",
"[",
"]",
"sorted_indices",
"=",
"sorted",
"(",
"indices",
")",
"i",
"=",
"0",
"j",
"=",
"0",
"while",
"(",
"i",
"<",
"len",
"(",
"self",
")",
")",
"and",
"(",
"j",
"<",
"len",
"(",
"sorted_indices",
")",
")",
":",
"if",
"i",
"!=",
"sorted_indices",
"[",
"j",
"]",
":",
"new_fragments",
".",
"append",
"(",
"self",
"[",
"i",
"]",
")",
"else",
":",
"j",
"+=",
"1",
"i",
"+=",
"1",
"while",
"i",
"<",
"len",
"(",
"self",
")",
":",
"new_fragments",
".",
"append",
"(",
"self",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"self",
".",
"__fragments",
"=",
"new_fragments"
] | Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid | [
"Remove",
"the",
"fragments",
"corresponding",
"to",
"the",
"given",
"list",
"of",
"indices",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L223-L246 |
232,182 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.sort | def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log(u"Sorting...")
self.__fragments = sorted(self.__fragments)
self.log(u"Sorting... done")
self.log(u"Checking relative positions...")
for i in range(len(self) - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:
self.log(u"Found overlapping fragments:")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
self.log_exc(u"The list contains two fragments overlapping in a forbidden way", None, True, ValueError)
self.log(u"Checking relative positions... done")
self.__sorted = True | python | def sort(self):
"""
Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints
"""
if self.is_guaranteed_sorted:
self.log(u"Already sorted, returning")
return
self.log(u"Sorting...")
self.__fragments = sorted(self.__fragments)
self.log(u"Sorting... done")
self.log(u"Checking relative positions...")
for i in range(len(self) - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if current_interval.relative_position_of(next_interval) not in self.ALLOWED_POSITIONS:
self.log(u"Found overlapping fragments:")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
self.log_exc(u"The list contains two fragments overlapping in a forbidden way", None, True, ValueError)
self.log(u"Checking relative positions... done")
self.__sorted = True | [
"def",
"sort",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_guaranteed_sorted",
":",
"self",
".",
"log",
"(",
"u\"Already sorted, returning\"",
")",
"return",
"self",
".",
"log",
"(",
"u\"Sorting...\"",
")",
"self",
".",
"__fragments",
"=",
"sorted",
"(",
"self",
".",
"__fragments",
")",
"self",
".",
"log",
"(",
"u\"Sorting... done\"",
")",
"self",
".",
"log",
"(",
"u\"Checking relative positions...\"",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
")",
"-",
"1",
")",
":",
"current_interval",
"=",
"self",
"[",
"i",
"]",
".",
"interval",
"next_interval",
"=",
"self",
"[",
"i",
"+",
"1",
"]",
".",
"interval",
"if",
"current_interval",
".",
"relative_position_of",
"(",
"next_interval",
")",
"not",
"in",
"self",
".",
"ALLOWED_POSITIONS",
":",
"self",
".",
"log",
"(",
"u\"Found overlapping fragments:\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" Index %d => %s\"",
",",
"i",
",",
"current_interval",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" Index %d => %s\"",
",",
"i",
"+",
"1",
",",
"next_interval",
"]",
")",
"self",
".",
"log_exc",
"(",
"u\"The list contains two fragments overlapping in a forbidden way\"",
",",
"None",
",",
"True",
",",
"ValueError",
")",
"self",
".",
"log",
"(",
"u\"Checking relative positions... done\"",
")",
"self",
".",
"__sorted",
"=",
"True"
] | Sort the fragments in the list.
:raises ValueError: if there is a fragment which violates
the list constraints | [
"Sort",
"the",
"fragments",
"in",
"the",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L248-L271 |
232,183 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.remove_nonspeech_fragments | def remove_nonspeech_fragments(self, zero_length_only=False):
"""
Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments
"""
self.log(u"Removing nonspeech fragments...")
nonspeech = list(self.nonspeech_fragments)
if zero_length_only:
nonspeech = [(i, f) for i, f in nonspeech if f.has_zero_length]
nonspeech_indices = [i for i, f in nonspeech]
self.remove(nonspeech_indices)
if zero_length_only:
for i, f in list(self.nonspeech_fragments):
f.fragment_type = SyncMapFragment.REGULAR
self.log(u"Removing nonspeech fragments... done") | python | def remove_nonspeech_fragments(self, zero_length_only=False):
"""
Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments
"""
self.log(u"Removing nonspeech fragments...")
nonspeech = list(self.nonspeech_fragments)
if zero_length_only:
nonspeech = [(i, f) for i, f in nonspeech if f.has_zero_length]
nonspeech_indices = [i for i, f in nonspeech]
self.remove(nonspeech_indices)
if zero_length_only:
for i, f in list(self.nonspeech_fragments):
f.fragment_type = SyncMapFragment.REGULAR
self.log(u"Removing nonspeech fragments... done") | [
"def",
"remove_nonspeech_fragments",
"(",
"self",
",",
"zero_length_only",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Removing nonspeech fragments...\"",
")",
"nonspeech",
"=",
"list",
"(",
"self",
".",
"nonspeech_fragments",
")",
"if",
"zero_length_only",
":",
"nonspeech",
"=",
"[",
"(",
"i",
",",
"f",
")",
"for",
"i",
",",
"f",
"in",
"nonspeech",
"if",
"f",
".",
"has_zero_length",
"]",
"nonspeech_indices",
"=",
"[",
"i",
"for",
"i",
",",
"f",
"in",
"nonspeech",
"]",
"self",
".",
"remove",
"(",
"nonspeech_indices",
")",
"if",
"zero_length_only",
":",
"for",
"i",
",",
"f",
"in",
"list",
"(",
"self",
".",
"nonspeech_fragments",
")",
":",
"f",
".",
"fragment_type",
"=",
"SyncMapFragment",
".",
"REGULAR",
"self",
".",
"log",
"(",
"u\"Removing nonspeech fragments... done\"",
")"
] | Remove ``NONSPEECH`` fragments from the list.
If ``zero_length_only`` is ``True``, remove only
those fragments with zero length,
and make all the others ``REGULAR``.
:param bool zero_length_only: remove only zero length NONSPEECH fragments | [
"Remove",
"NONSPEECH",
"fragments",
"from",
"the",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L273-L292 |
232,184 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.has_zero_length_fragments | def has_zero_length_fragments(self, min_index=None, max_index=None):
"""
Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
zero = [i for i in range(min_index, max_index) if self[i].has_zero_length]
self.log([u"Fragments with zero length: %s", zero])
return (len(zero) > 0) | python | def has_zero_length_fragments(self, min_index=None, max_index=None):
"""
Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
zero = [i for i in range(min_index, max_index) if self[i].has_zero_length]
self.log([u"Fragments with zero length: %s", zero])
return (len(zero) > 0) | [
"def",
"has_zero_length_fragments",
"(",
"self",
",",
"min_index",
"=",
"None",
",",
"max_index",
"=",
"None",
")",
":",
"min_index",
",",
"max_index",
"=",
"self",
".",
"_check_min_max_indices",
"(",
"min_index",
",",
"max_index",
")",
"zero",
"=",
"[",
"i",
"for",
"i",
"in",
"range",
"(",
"min_index",
",",
"max_index",
")",
"if",
"self",
"[",
"i",
"]",
".",
"has_zero_length",
"]",
"self",
".",
"log",
"(",
"[",
"u\"Fragments with zero length: %s\"",
",",
"zero",
"]",
")",
"return",
"(",
"len",
"(",
"zero",
")",
">",
"0",
")"
] | Return ``True`` if the list has at least one interval
with zero length withing ``min_index`` and ``max_index``.
If the latter are not specified, check all intervals.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool | [
"Return",
"True",
"if",
"the",
"list",
"has",
"at",
"least",
"one",
"interval",
"with",
"zero",
"length",
"withing",
"min_index",
"and",
"max_index",
".",
"If",
"the",
"latter",
"are",
"not",
"specified",
"check",
"all",
"intervals",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L294-L309 |
232,185 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.has_adjacent_fragments_only | def has_adjacent_fragments_only(self, min_index=None, max_index=None):
"""
Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
for i in range(min_index, max_index - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
self.log(u"Found non adjacent fragments")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
return False
return True | python | def has_adjacent_fragments_only(self, min_index=None, max_index=None):
"""
Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool
"""
min_index, max_index = self._check_min_max_indices(min_index, max_index)
for i in range(min_index, max_index - 1):
current_interval = self[i].interval
next_interval = self[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
self.log(u"Found non adjacent fragments")
self.log([u" Index %d => %s", i, current_interval])
self.log([u" Index %d => %s", i + 1, next_interval])
return False
return True | [
"def",
"has_adjacent_fragments_only",
"(",
"self",
",",
"min_index",
"=",
"None",
",",
"max_index",
"=",
"None",
")",
":",
"min_index",
",",
"max_index",
"=",
"self",
".",
"_check_min_max_indices",
"(",
"min_index",
",",
"max_index",
")",
"for",
"i",
"in",
"range",
"(",
"min_index",
",",
"max_index",
"-",
"1",
")",
":",
"current_interval",
"=",
"self",
"[",
"i",
"]",
".",
"interval",
"next_interval",
"=",
"self",
"[",
"i",
"+",
"1",
"]",
".",
"interval",
"if",
"not",
"current_interval",
".",
"is_adjacent_before",
"(",
"next_interval",
")",
":",
"self",
".",
"log",
"(",
"u\"Found non adjacent fragments\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" Index %d => %s\"",
",",
"i",
",",
"current_interval",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" Index %d => %s\"",
",",
"i",
"+",
"1",
",",
"next_interval",
"]",
")",
"return",
"False",
"return",
"True"
] | Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:param int max_index: examine fragments with index smaller than this index (i.e., excluded)
:raises ValueError: if ``min_index`` is negative or ``max_index``
is bigger than the current number of fragments
:rtype: bool | [
"Return",
"True",
"if",
"the",
"list",
"contains",
"only",
"adjacent",
"fragments",
"that",
"is",
"if",
"it",
"does",
"not",
"have",
"gaps",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L311-L331 |
232,186 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.offset | def offset(self, offset):
"""
Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
"""
self.log(u"Applying offset to all fragments...")
self.log([u" Offset %.3f", offset])
for fragment in self.fragments:
fragment.interval.offset(
offset=offset,
allow_negative=False,
min_begin_value=self.begin,
max_end_value=self.end
)
self.log(u"Applying offset to all fragments... done") | python | def offset(self, offset):
"""
Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue``
"""
self.log(u"Applying offset to all fragments...")
self.log([u" Offset %.3f", offset])
for fragment in self.fragments:
fragment.interval.offset(
offset=offset,
allow_negative=False,
min_begin_value=self.begin,
max_end_value=self.end
)
self.log(u"Applying offset to all fragments... done") | [
"def",
"offset",
"(",
"self",
",",
"offset",
")",
":",
"self",
".",
"log",
"(",
"u\"Applying offset to all fragments...\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" Offset %.3f\"",
",",
"offset",
"]",
")",
"for",
"fragment",
"in",
"self",
".",
"fragments",
":",
"fragment",
".",
"interval",
".",
"offset",
"(",
"offset",
"=",
"offset",
",",
"allow_negative",
"=",
"False",
",",
"min_begin_value",
"=",
"self",
".",
"begin",
",",
"max_end_value",
"=",
"self",
".",
"end",
")",
"self",
".",
"log",
"(",
"u\"Applying offset to all fragments... done\"",
")"
] | Move all the intervals in the list by the given ``offset``.
:param offset: the shift to be applied
:type offset: :class:`~aeneas.exacttiming.TimeValue`
:raises TypeError: if ``offset`` is not an instance of ``TimeValue`` | [
"Move",
"all",
"the",
"intervals",
"in",
"the",
"list",
"by",
"the",
"given",
"offset",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L360-L377 |
232,187 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.move_transition_point | def move_transition_point(self, fragment_index, value):
"""
Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue`
"""
self.log(u"Called move_transition_point with")
self.log([u" fragment_index %d", fragment_index])
self.log([u" value %.3f", value])
if (fragment_index < 0) or (fragment_index > (len(self) - 3)):
self.log(u"Bad fragment_index, returning")
return
current_interval = self[fragment_index].interval
next_interval = self[fragment_index + 1].interval
if value > next_interval.end:
self.log(u"Bad value, returning")
return
if not current_interval.is_non_zero_before_non_zero(next_interval):
self.log(u"Bad interval configuration, returning")
return
current_interval.end = value
next_interval.begin = value
self.log(u"Moved transition point") | python | def move_transition_point(self, fragment_index, value):
"""
Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue`
"""
self.log(u"Called move_transition_point with")
self.log([u" fragment_index %d", fragment_index])
self.log([u" value %.3f", value])
if (fragment_index < 0) or (fragment_index > (len(self) - 3)):
self.log(u"Bad fragment_index, returning")
return
current_interval = self[fragment_index].interval
next_interval = self[fragment_index + 1].interval
if value > next_interval.end:
self.log(u"Bad value, returning")
return
if not current_interval.is_non_zero_before_non_zero(next_interval):
self.log(u"Bad interval configuration, returning")
return
current_interval.end = value
next_interval.begin = value
self.log(u"Moved transition point") | [
"def",
"move_transition_point",
"(",
"self",
",",
"fragment_index",
",",
"value",
")",
":",
"self",
".",
"log",
"(",
"u\"Called move_transition_point with\"",
")",
"self",
".",
"log",
"(",
"[",
"u\" fragment_index %d\"",
",",
"fragment_index",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" value %.3f\"",
",",
"value",
"]",
")",
"if",
"(",
"fragment_index",
"<",
"0",
")",
"or",
"(",
"fragment_index",
">",
"(",
"len",
"(",
"self",
")",
"-",
"3",
")",
")",
":",
"self",
".",
"log",
"(",
"u\"Bad fragment_index, returning\"",
")",
"return",
"current_interval",
"=",
"self",
"[",
"fragment_index",
"]",
".",
"interval",
"next_interval",
"=",
"self",
"[",
"fragment_index",
"+",
"1",
"]",
".",
"interval",
"if",
"value",
">",
"next_interval",
".",
"end",
":",
"self",
".",
"log",
"(",
"u\"Bad value, returning\"",
")",
"return",
"if",
"not",
"current_interval",
".",
"is_non_zero_before_non_zero",
"(",
"next_interval",
")",
":",
"self",
".",
"log",
"(",
"u\"Bad interval configuration, returning\"",
")",
"return",
"current_interval",
".",
"end",
"=",
"value",
"next_interval",
".",
"begin",
"=",
"value",
"self",
".",
"log",
"(",
"u\"Moved transition point\"",
")"
] | Change the transition point between fragment ``fragment_index``
and the next fragment to the time value ``value``.
This method fails silently
(without changing the fragment list)
if at least one of the following conditions holds:
* ``fragment_index`` is negative
* ``fragment_index`` is the last or the second-to-last
* ``value`` is after the current end of the next fragment
* the current fragment and the next one are not adjacent and both proper intervals (not zero length)
The above conditions ensure that the move makes sense
and that it keeps the list satisfying the constraints.
:param int fragment_index: the fragment index whose end should be moved
:param value: the new transition point
:type value: :class:`~aeneas.exacttiming.TimeValue` | [
"Change",
"the",
"transition",
"point",
"between",
"fragment",
"fragment_index",
"and",
"the",
"next",
"fragment",
"to",
"the",
"time",
"value",
"value",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L379-L416 |
232,188 | readbeyond/aeneas | aeneas/syncmap/fragmentlist.py | SyncMapFragmentList.inject_long_nonspeech_fragments | def inject_long_nonspeech_fragments(self, pairs, replacement_string):
"""
Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals
"""
self.log(u"Called inject_long_nonspeech_fragments")
# set the appropriate fragment text
if replacement_string in [None, gc.PPV_TASK_ADJUST_BOUNDARY_NONSPEECH_REMOVE]:
self.log(u" Remove long nonspeech")
lines = []
else:
self.log([u" Replace long nonspeech with '%s'", replacement_string])
lines = [replacement_string]
# first, make room for the nonspeech intervals
self.log(u" First pass: making room...")
for nsi, index in pairs:
self[index].interval.end = nsi.begin
self[index + 1].interval.begin = nsi.end
self.log(u" First pass: making room... done")
self.log(u" Second pass: append nonspeech intervals...")
for i, (nsi, index) in enumerate(pairs, 1):
identifier = u"n%06d" % i
self.add(SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
language=None,
lines=lines,
filtered_lines=lines
),
interval=nsi,
fragment_type=SyncMapFragment.NONSPEECH
), sort=False)
self.log(u" Second pass: append nonspeech intervals... done")
self.log(u" Third pass: sorting...")
self.sort()
self.log(u" Third pass: sorting... done") | python | def inject_long_nonspeech_fragments(self, pairs, replacement_string):
"""
Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals
"""
self.log(u"Called inject_long_nonspeech_fragments")
# set the appropriate fragment text
if replacement_string in [None, gc.PPV_TASK_ADJUST_BOUNDARY_NONSPEECH_REMOVE]:
self.log(u" Remove long nonspeech")
lines = []
else:
self.log([u" Replace long nonspeech with '%s'", replacement_string])
lines = [replacement_string]
# first, make room for the nonspeech intervals
self.log(u" First pass: making room...")
for nsi, index in pairs:
self[index].interval.end = nsi.begin
self[index + 1].interval.begin = nsi.end
self.log(u" First pass: making room... done")
self.log(u" Second pass: append nonspeech intervals...")
for i, (nsi, index) in enumerate(pairs, 1):
identifier = u"n%06d" % i
self.add(SyncMapFragment(
text_fragment=TextFragment(
identifier=identifier,
language=None,
lines=lines,
filtered_lines=lines
),
interval=nsi,
fragment_type=SyncMapFragment.NONSPEECH
), sort=False)
self.log(u" Second pass: append nonspeech intervals... done")
self.log(u" Third pass: sorting...")
self.sort()
self.log(u" Third pass: sorting... done") | [
"def",
"inject_long_nonspeech_fragments",
"(",
"self",
",",
"pairs",
",",
"replacement_string",
")",
":",
"self",
".",
"log",
"(",
"u\"Called inject_long_nonspeech_fragments\"",
")",
"# set the appropriate fragment text",
"if",
"replacement_string",
"in",
"[",
"None",
",",
"gc",
".",
"PPV_TASK_ADJUST_BOUNDARY_NONSPEECH_REMOVE",
"]",
":",
"self",
".",
"log",
"(",
"u\" Remove long nonspeech\"",
")",
"lines",
"=",
"[",
"]",
"else",
":",
"self",
".",
"log",
"(",
"[",
"u\" Replace long nonspeech with '%s'\"",
",",
"replacement_string",
"]",
")",
"lines",
"=",
"[",
"replacement_string",
"]",
"# first, make room for the nonspeech intervals",
"self",
".",
"log",
"(",
"u\" First pass: making room...\"",
")",
"for",
"nsi",
",",
"index",
"in",
"pairs",
":",
"self",
"[",
"index",
"]",
".",
"interval",
".",
"end",
"=",
"nsi",
".",
"begin",
"self",
"[",
"index",
"+",
"1",
"]",
".",
"interval",
".",
"begin",
"=",
"nsi",
".",
"end",
"self",
".",
"log",
"(",
"u\" First pass: making room... done\"",
")",
"self",
".",
"log",
"(",
"u\" Second pass: append nonspeech intervals...\"",
")",
"for",
"i",
",",
"(",
"nsi",
",",
"index",
")",
"in",
"enumerate",
"(",
"pairs",
",",
"1",
")",
":",
"identifier",
"=",
"u\"n%06d\"",
"%",
"i",
"self",
".",
"add",
"(",
"SyncMapFragment",
"(",
"text_fragment",
"=",
"TextFragment",
"(",
"identifier",
"=",
"identifier",
",",
"language",
"=",
"None",
",",
"lines",
"=",
"lines",
",",
"filtered_lines",
"=",
"lines",
")",
",",
"interval",
"=",
"nsi",
",",
"fragment_type",
"=",
"SyncMapFragment",
".",
"NONSPEECH",
")",
",",
"sort",
"=",
"False",
")",
"self",
".",
"log",
"(",
"u\" Second pass: append nonspeech intervals... done\"",
")",
"self",
".",
"log",
"(",
"u\" Third pass: sorting...\"",
")",
"self",
".",
"sort",
"(",
")",
"self",
".",
"log",
"(",
"u\" Third pass: sorting... done\"",
")"
] | Inject nonspeech fragments corresponding to the given intervals
in this fragment list.
It is assumed that ``pairs`` are consistent, e.g. they are produced
by ``fragments_ending_inside_nonspeech_intervals``.
:param list pairs: list of ``(TimeInterval, int)`` pairs,
each identifying a nonspeech interval and
the corresponding fragment index ending inside it
:param string replacement_string: the string to be applied to the nonspeech intervals | [
"Inject",
"nonspeech",
"fragments",
"corresponding",
"to",
"the",
"given",
"intervals",
"in",
"this",
"fragment",
"list",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/fragmentlist.py#L507-L550 |
232,189 | readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_accumulated_cost_matrix | def compute_accumulated_cost_matrix(self):
"""
Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Returning accumulated cost matrix")
return self.dtw.compute_accumulated_cost_matrix() | python | def compute_accumulated_cost_matrix(self):
"""
Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Returning accumulated cost matrix")
return self.dtw.compute_accumulated_cost_matrix() | [
"def",
"compute_accumulated_cost_matrix",
"(",
"self",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning None\"",
")",
"return",
"None",
"self",
".",
"log",
"(",
"u\"Returning accumulated cost matrix\"",
")",
"return",
"self",
".",
"dtw",
".",
"compute_accumulated_cost_matrix",
"(",
")"
] | Compute the accumulated cost matrix, and return it.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: :class:`numpy.ndarray` (2D)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.2.0 | [
"Compute",
"the",
"accumulated",
"cost",
"matrix",
"and",
"return",
"it",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L160-L178 |
232,190 | readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_path | def compute_path(self):
"""
Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Computing path...")
wave_path = self.dtw.compute_path()
self.log(u"Computing path... done")
self.log(u"Translating path to full wave indices...")
real_indices = numpy.array([t[0] for t in wave_path])
synt_indices = numpy.array([t[1] for t in wave_path])
if self.rconf.mmn:
self.log(u"Translating real indices with masked_middle_map...")
real_indices = self.real_wave_mfcc.masked_middle_map[real_indices]
real_indices[0] = self.real_wave_mfcc.head_length
self.log(u"Translating real indices with masked_middle_map... done")
self.log(u"Translating synt indices with masked_middle_map...")
synt_indices = self.synt_wave_mfcc.masked_middle_map[synt_indices]
self.log(u"Translating synt indices with masked_middle_map... done")
else:
self.log(u"Translating real indices by adding head_length...")
real_indices += self.real_wave_mfcc.head_length
self.log(u"Translating real indices by adding head_length... done")
self.log(u"Nothing to do with synt indices")
self.log(u"Translating path to full wave indices... done")
return (real_indices, synt_indices) | python | def compute_path(self):
"""
Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning None")
return None
self.log(u"Computing path...")
wave_path = self.dtw.compute_path()
self.log(u"Computing path... done")
self.log(u"Translating path to full wave indices...")
real_indices = numpy.array([t[0] for t in wave_path])
synt_indices = numpy.array([t[1] for t in wave_path])
if self.rconf.mmn:
self.log(u"Translating real indices with masked_middle_map...")
real_indices = self.real_wave_mfcc.masked_middle_map[real_indices]
real_indices[0] = self.real_wave_mfcc.head_length
self.log(u"Translating real indices with masked_middle_map... done")
self.log(u"Translating synt indices with masked_middle_map...")
synt_indices = self.synt_wave_mfcc.masked_middle_map[synt_indices]
self.log(u"Translating synt indices with masked_middle_map... done")
else:
self.log(u"Translating real indices by adding head_length...")
real_indices += self.real_wave_mfcc.head_length
self.log(u"Translating real indices by adding head_length... done")
self.log(u"Nothing to do with synt indices")
self.log(u"Translating path to full wave indices... done")
return (real_indices, synt_indices) | [
"def",
"compute_path",
"(",
"self",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning None\"",
")",
"return",
"None",
"self",
".",
"log",
"(",
"u\"Computing path...\"",
")",
"wave_path",
"=",
"self",
".",
"dtw",
".",
"compute_path",
"(",
")",
"self",
".",
"log",
"(",
"u\"Computing path... done\"",
")",
"self",
".",
"log",
"(",
"u\"Translating path to full wave indices...\"",
")",
"real_indices",
"=",
"numpy",
".",
"array",
"(",
"[",
"t",
"[",
"0",
"]",
"for",
"t",
"in",
"wave_path",
"]",
")",
"synt_indices",
"=",
"numpy",
".",
"array",
"(",
"[",
"t",
"[",
"1",
"]",
"for",
"t",
"in",
"wave_path",
"]",
")",
"if",
"self",
".",
"rconf",
".",
"mmn",
":",
"self",
".",
"log",
"(",
"u\"Translating real indices with masked_middle_map...\"",
")",
"real_indices",
"=",
"self",
".",
"real_wave_mfcc",
".",
"masked_middle_map",
"[",
"real_indices",
"]",
"real_indices",
"[",
"0",
"]",
"=",
"self",
".",
"real_wave_mfcc",
".",
"head_length",
"self",
".",
"log",
"(",
"u\"Translating real indices with masked_middle_map... done\"",
")",
"self",
".",
"log",
"(",
"u\"Translating synt indices with masked_middle_map...\"",
")",
"synt_indices",
"=",
"self",
".",
"synt_wave_mfcc",
".",
"masked_middle_map",
"[",
"synt_indices",
"]",
"self",
".",
"log",
"(",
"u\"Translating synt indices with masked_middle_map... done\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Translating real indices by adding head_length...\"",
")",
"real_indices",
"+=",
"self",
".",
"real_wave_mfcc",
".",
"head_length",
"self",
".",
"log",
"(",
"u\"Translating real indices by adding head_length... done\"",
")",
"self",
".",
"log",
"(",
"u\"Nothing to do with synt indices\"",
")",
"self",
".",
"log",
"(",
"u\"Translating path to full wave indices... done\"",
")",
"return",
"(",
"real_indices",
",",
"synt_indices",
")"
] | Compute the min cost path between the two waves, and return it.
Return the computed path as a tuple with two elements,
each being a :class:`numpy.ndarray` (1D) of ``int`` indices: ::
([r_1, r_2, ..., r_k], [s_1, s_2, ..., s_k])
where ``r_i`` are the indices in the real wave
and ``s_i`` are the indices in the synthesized wave,
and ``k`` is the length of the min cost path.
Return ``None`` if the accumulated cost matrix cannot be computed
because one of the two waves is empty after masking (if requested).
:rtype: tuple (see above)
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed. | [
"Compute",
"the",
"min",
"cost",
"path",
"between",
"the",
"two",
"waves",
"and",
"return",
"it",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L180-L224 |
232,191 | readbeyond/aeneas | aeneas/dtw.py | DTWAligner.compute_boundaries | def compute_boundaries(self, synt_anchors):
"""
Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning artificial boundary indices")
begin = self.real_wave_mfcc.middle_begin
end = self.real_wave_mfcc.tail_begin
n = len(synt_anchors)
step = float(end - begin) / n
boundary_indices = [begin + int(i * step) for i in range(n)] + [end]
return numpy.array(boundary_indices)
self.log(u"Computing path...")
real_indices, synt_indices = self.compute_path()
self.log(u"Computing path... done")
self.log(u"Computing boundary indices...")
# both real_indices and synt_indices are w.r.t. the full wave
self.log([u"Fragments: %d", len(synt_anchors)])
self.log([u"Path length: %d", len(real_indices)])
# synt_anchors as in seconds, convert them in MFCC indices
# see also issue #102
mws = self.rconf.mws
sample_rate = self.rconf.sample_rate
samples_per_mws = mws * sample_rate
if samples_per_mws.is_integer:
anchor_indices = numpy.array([int(a[0] / mws) for a in synt_anchors])
else:
#
# NOTE this is not elegant, but it saves the day for the user
#
self.log_warn(u"The number of samples in each window shift is not an integer, time drift might occur.")
anchor_indices = numpy.array([(int(a[0] * sample_rate / mws) / sample_rate) for a in synt_anchors])
#
# right side sets the split point at the very beginning of "next" fragment
#
# NOTE clip() is needed since searchsorted() with side="right" might return
# an index == len(synt_indices) == len(real_indices)
# when the insertion point is past the last element of synt_indices
# causing the fancy indexing real_indices[...] below might fail
begin_indices = numpy.clip(numpy.searchsorted(synt_indices, anchor_indices, side="right"), 0, len(synt_indices) - 1)
# first split must occur at zero
begin_indices[0] = 0
#
# map onto real indices, obtaining "default" boundary indices
#
# NOTE since len(synt_indices) == len(real_indices)
# and because the numpy.clip() above, the fancy indexing is always valid
#
boundary_indices = numpy.append(real_indices[begin_indices], self.real_wave_mfcc.tail_begin)
self.log([u"Boundary indices: %d", len(boundary_indices)])
self.log(u"Computing boundary indices... done")
return boundary_indices | python | def compute_boundaries(self, synt_anchors):
"""
Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D)
"""
self._setup_dtw()
if self.dtw is None:
self.log(u"Inner self.dtw is None => returning artificial boundary indices")
begin = self.real_wave_mfcc.middle_begin
end = self.real_wave_mfcc.tail_begin
n = len(synt_anchors)
step = float(end - begin) / n
boundary_indices = [begin + int(i * step) for i in range(n)] + [end]
return numpy.array(boundary_indices)
self.log(u"Computing path...")
real_indices, synt_indices = self.compute_path()
self.log(u"Computing path... done")
self.log(u"Computing boundary indices...")
# both real_indices and synt_indices are w.r.t. the full wave
self.log([u"Fragments: %d", len(synt_anchors)])
self.log([u"Path length: %d", len(real_indices)])
# synt_anchors as in seconds, convert them in MFCC indices
# see also issue #102
mws = self.rconf.mws
sample_rate = self.rconf.sample_rate
samples_per_mws = mws * sample_rate
if samples_per_mws.is_integer:
anchor_indices = numpy.array([int(a[0] / mws) for a in synt_anchors])
else:
#
# NOTE this is not elegant, but it saves the day for the user
#
self.log_warn(u"The number of samples in each window shift is not an integer, time drift might occur.")
anchor_indices = numpy.array([(int(a[0] * sample_rate / mws) / sample_rate) for a in synt_anchors])
#
# right side sets the split point at the very beginning of "next" fragment
#
# NOTE clip() is needed since searchsorted() with side="right" might return
# an index == len(synt_indices) == len(real_indices)
# when the insertion point is past the last element of synt_indices
# causing the fancy indexing real_indices[...] below might fail
begin_indices = numpy.clip(numpy.searchsorted(synt_indices, anchor_indices, side="right"), 0, len(synt_indices) - 1)
# first split must occur at zero
begin_indices[0] = 0
#
# map onto real indices, obtaining "default" boundary indices
#
# NOTE since len(synt_indices) == len(real_indices)
# and because the numpy.clip() above, the fancy indexing is always valid
#
boundary_indices = numpy.append(real_indices[begin_indices], self.real_wave_mfcc.tail_begin)
self.log([u"Boundary indices: %d", len(boundary_indices)])
self.log(u"Computing boundary indices... done")
return boundary_indices | [
"def",
"compute_boundaries",
"(",
"self",
",",
"synt_anchors",
")",
":",
"self",
".",
"_setup_dtw",
"(",
")",
"if",
"self",
".",
"dtw",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inner self.dtw is None => returning artificial boundary indices\"",
")",
"begin",
"=",
"self",
".",
"real_wave_mfcc",
".",
"middle_begin",
"end",
"=",
"self",
".",
"real_wave_mfcc",
".",
"tail_begin",
"n",
"=",
"len",
"(",
"synt_anchors",
")",
"step",
"=",
"float",
"(",
"end",
"-",
"begin",
")",
"/",
"n",
"boundary_indices",
"=",
"[",
"begin",
"+",
"int",
"(",
"i",
"*",
"step",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
"]",
"+",
"[",
"end",
"]",
"return",
"numpy",
".",
"array",
"(",
"boundary_indices",
")",
"self",
".",
"log",
"(",
"u\"Computing path...\"",
")",
"real_indices",
",",
"synt_indices",
"=",
"self",
".",
"compute_path",
"(",
")",
"self",
".",
"log",
"(",
"u\"Computing path... done\"",
")",
"self",
".",
"log",
"(",
"u\"Computing boundary indices...\"",
")",
"# both real_indices and synt_indices are w.r.t. the full wave",
"self",
".",
"log",
"(",
"[",
"u\"Fragments: %d\"",
",",
"len",
"(",
"synt_anchors",
")",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"Path length: %d\"",
",",
"len",
"(",
"real_indices",
")",
"]",
")",
"# synt_anchors as in seconds, convert them in MFCC indices",
"# see also issue #102",
"mws",
"=",
"self",
".",
"rconf",
".",
"mws",
"sample_rate",
"=",
"self",
".",
"rconf",
".",
"sample_rate",
"samples_per_mws",
"=",
"mws",
"*",
"sample_rate",
"if",
"samples_per_mws",
".",
"is_integer",
":",
"anchor_indices",
"=",
"numpy",
".",
"array",
"(",
"[",
"int",
"(",
"a",
"[",
"0",
"]",
"/",
"mws",
")",
"for",
"a",
"in",
"synt_anchors",
"]",
")",
"else",
":",
"#",
"# NOTE this is not elegant, but it saves the day for the user",
"#",
"self",
".",
"log_warn",
"(",
"u\"The number of samples in each window shift is not an integer, time drift might occur.\"",
")",
"anchor_indices",
"=",
"numpy",
".",
"array",
"(",
"[",
"(",
"int",
"(",
"a",
"[",
"0",
"]",
"*",
"sample_rate",
"/",
"mws",
")",
"/",
"sample_rate",
")",
"for",
"a",
"in",
"synt_anchors",
"]",
")",
"#",
"# right side sets the split point at the very beginning of \"next\" fragment",
"#",
"# NOTE clip() is needed since searchsorted() with side=\"right\" might return",
"# an index == len(synt_indices) == len(real_indices)",
"# when the insertion point is past the last element of synt_indices",
"# causing the fancy indexing real_indices[...] below might fail",
"begin_indices",
"=",
"numpy",
".",
"clip",
"(",
"numpy",
".",
"searchsorted",
"(",
"synt_indices",
",",
"anchor_indices",
",",
"side",
"=",
"\"right\"",
")",
",",
"0",
",",
"len",
"(",
"synt_indices",
")",
"-",
"1",
")",
"# first split must occur at zero",
"begin_indices",
"[",
"0",
"]",
"=",
"0",
"#",
"# map onto real indices, obtaining \"default\" boundary indices",
"#",
"# NOTE since len(synt_indices) == len(real_indices)",
"# and because the numpy.clip() above, the fancy indexing is always valid",
"#",
"boundary_indices",
"=",
"numpy",
".",
"append",
"(",
"real_indices",
"[",
"begin_indices",
"]",
",",
"self",
".",
"real_wave_mfcc",
".",
"tail_begin",
")",
"self",
".",
"log",
"(",
"[",
"u\"Boundary indices: %d\"",
",",
"len",
"(",
"boundary_indices",
")",
"]",
")",
"self",
".",
"log",
"(",
"u\"Computing boundary indices... done\"",
")",
"return",
"boundary_indices"
] | Compute the min cost path between the two waves,
and return a list of boundary points,
representing the argmin values with respect to
the provided ``synt_anchors`` timings.
If ``synt_anchors`` has ``k`` elements,
the returned array will have ``k+1`` elements,
accounting for the tail fragment.
:param synt_anchors: the anchor time values (in seconds) of the synthesized fragments,
each representing the begin time in the synthesized wave
of the corresponding fragment
:type synt_anchors: list of :class:`~aeneas.exacttiming.TimeValue`
Return the list of boundary indices.
:rtype: :class:`numpy.ndarray` (1D) | [
"Compute",
"the",
"min",
"cost",
"path",
"between",
"the",
"two",
"waves",
"and",
"return",
"a",
"list",
"of",
"boundary",
"points",
"representing",
"the",
"argmin",
"values",
"with",
"respect",
"to",
"the",
"provided",
"synt_anchors",
"timings",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L226-L296 |
232,192 | readbeyond/aeneas | aeneas/dtw.py | DTWAligner._setup_dtw | def _setup_dtw(self):
"""
Set the DTW object up.
"""
# check if the DTW object has already been set up
if self.dtw is not None:
return
# check we have the AudioFileMFCC objects
if (self.real_wave_mfcc is None) or (self.real_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The real wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
if (self.synt_wave_mfcc is None) or (self.synt_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The synt wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
# setup
algorithm = self.rconf[RuntimeConfiguration.DTW_ALGORITHM]
delta = int(2 * self.rconf.dtw_margin / self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT])
mfcc2_length = self.synt_wave_mfcc.middle_length
self.log([u"Requested algorithm: '%s'", algorithm])
self.log([u"delta = %d", delta])
self.log([u"m = %d", mfcc2_length])
# check if delta is >= length of synt wave
if mfcc2_length <= delta:
self.log(u"We have mfcc2_length <= delta")
if (self.rconf[RuntimeConfiguration.C_EXTENSIONS]) and (gf.can_run_c_extension()):
# the C code can be run: since it is still faster, do not run EXACT
self.log(u"C extensions enabled and loaded: not selecting EXACT algorithm")
else:
self.log(u"Selecting EXACT algorithm")
algorithm = DTWAlgorithm.EXACT
# select mask here
if self.rconf.mmn:
self.log(u"Using masked MFCC")
real_mfcc = self.real_wave_mfcc.masked_middle_mfcc
synt_mfcc = self.synt_wave_mfcc.masked_middle_mfcc
else:
self.log(u"Using unmasked MFCC")
real_mfcc = self.real_wave_mfcc.middle_mfcc
synt_mfcc = self.synt_wave_mfcc.middle_mfcc
n = real_mfcc.shape[1]
m = synt_mfcc.shape[1]
self.log([u" Number of MFCC frames in real wave: %d", n])
self.log([u" Number of MFCC frames in synt wave: %d", m])
if (n == 0) or (m == 0):
self.log(u"Setting self.dtw to None")
self.dtw = None
else:
# set the selected algorithm
if algorithm == DTWAlgorithm.EXACT:
self.log(u"Computing with EXACT algo")
self.dtw = DTWExact(
m1=real_mfcc,
m2=synt_mfcc,
rconf=self.rconf,
logger=self.logger
)
else:
self.log(u"Computing with STRIPE algo")
self.dtw = DTWStripe(
m1=real_mfcc,
m2=synt_mfcc,
delta=delta,
rconf=self.rconf,
logger=self.logger
) | python | def _setup_dtw(self):
"""
Set the DTW object up.
"""
# check if the DTW object has already been set up
if self.dtw is not None:
return
# check we have the AudioFileMFCC objects
if (self.real_wave_mfcc is None) or (self.real_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The real wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
if (self.synt_wave_mfcc is None) or (self.synt_wave_mfcc.middle_mfcc is None):
self.log_exc(u"The synt wave MFCCs are not initialized", None, True, DTWAlignerNotInitialized)
# setup
algorithm = self.rconf[RuntimeConfiguration.DTW_ALGORITHM]
delta = int(2 * self.rconf.dtw_margin / self.rconf[RuntimeConfiguration.MFCC_WINDOW_SHIFT])
mfcc2_length = self.synt_wave_mfcc.middle_length
self.log([u"Requested algorithm: '%s'", algorithm])
self.log([u"delta = %d", delta])
self.log([u"m = %d", mfcc2_length])
# check if delta is >= length of synt wave
if mfcc2_length <= delta:
self.log(u"We have mfcc2_length <= delta")
if (self.rconf[RuntimeConfiguration.C_EXTENSIONS]) and (gf.can_run_c_extension()):
# the C code can be run: since it is still faster, do not run EXACT
self.log(u"C extensions enabled and loaded: not selecting EXACT algorithm")
else:
self.log(u"Selecting EXACT algorithm")
algorithm = DTWAlgorithm.EXACT
# select mask here
if self.rconf.mmn:
self.log(u"Using masked MFCC")
real_mfcc = self.real_wave_mfcc.masked_middle_mfcc
synt_mfcc = self.synt_wave_mfcc.masked_middle_mfcc
else:
self.log(u"Using unmasked MFCC")
real_mfcc = self.real_wave_mfcc.middle_mfcc
synt_mfcc = self.synt_wave_mfcc.middle_mfcc
n = real_mfcc.shape[1]
m = synt_mfcc.shape[1]
self.log([u" Number of MFCC frames in real wave: %d", n])
self.log([u" Number of MFCC frames in synt wave: %d", m])
if (n == 0) or (m == 0):
self.log(u"Setting self.dtw to None")
self.dtw = None
else:
# set the selected algorithm
if algorithm == DTWAlgorithm.EXACT:
self.log(u"Computing with EXACT algo")
self.dtw = DTWExact(
m1=real_mfcc,
m2=synt_mfcc,
rconf=self.rconf,
logger=self.logger
)
else:
self.log(u"Computing with STRIPE algo")
self.dtw = DTWStripe(
m1=real_mfcc,
m2=synt_mfcc,
delta=delta,
rconf=self.rconf,
logger=self.logger
) | [
"def",
"_setup_dtw",
"(",
"self",
")",
":",
"# check if the DTW object has already been set up",
"if",
"self",
".",
"dtw",
"is",
"not",
"None",
":",
"return",
"# check we have the AudioFileMFCC objects",
"if",
"(",
"self",
".",
"real_wave_mfcc",
"is",
"None",
")",
"or",
"(",
"self",
".",
"real_wave_mfcc",
".",
"middle_mfcc",
"is",
"None",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The real wave MFCCs are not initialized\"",
",",
"None",
",",
"True",
",",
"DTWAlignerNotInitialized",
")",
"if",
"(",
"self",
".",
"synt_wave_mfcc",
"is",
"None",
")",
"or",
"(",
"self",
".",
"synt_wave_mfcc",
".",
"middle_mfcc",
"is",
"None",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"The synt wave MFCCs are not initialized\"",
",",
"None",
",",
"True",
",",
"DTWAlignerNotInitialized",
")",
"# setup",
"algorithm",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"DTW_ALGORITHM",
"]",
"delta",
"=",
"int",
"(",
"2",
"*",
"self",
".",
"rconf",
".",
"dtw_margin",
"/",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"MFCC_WINDOW_SHIFT",
"]",
")",
"mfcc2_length",
"=",
"self",
".",
"synt_wave_mfcc",
".",
"middle_length",
"self",
".",
"log",
"(",
"[",
"u\"Requested algorithm: '%s'\"",
",",
"algorithm",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"delta = %d\"",
",",
"delta",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\"m = %d\"",
",",
"mfcc2_length",
"]",
")",
"# check if delta is >= length of synt wave",
"if",
"mfcc2_length",
"<=",
"delta",
":",
"self",
".",
"log",
"(",
"u\"We have mfcc2_length <= delta\"",
")",
"if",
"(",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"C_EXTENSIONS",
"]",
")",
"and",
"(",
"gf",
".",
"can_run_c_extension",
"(",
")",
")",
":",
"# the C code can be run: since it is still faster, do not run EXACT",
"self",
".",
"log",
"(",
"u\"C extensions enabled and loaded: not selecting EXACT algorithm\"",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Selecting EXACT algorithm\"",
")",
"algorithm",
"=",
"DTWAlgorithm",
".",
"EXACT",
"# select mask here",
"if",
"self",
".",
"rconf",
".",
"mmn",
":",
"self",
".",
"log",
"(",
"u\"Using masked MFCC\"",
")",
"real_mfcc",
"=",
"self",
".",
"real_wave_mfcc",
".",
"masked_middle_mfcc",
"synt_mfcc",
"=",
"self",
".",
"synt_wave_mfcc",
".",
"masked_middle_mfcc",
"else",
":",
"self",
".",
"log",
"(",
"u\"Using unmasked MFCC\"",
")",
"real_mfcc",
"=",
"self",
".",
"real_wave_mfcc",
".",
"middle_mfcc",
"synt_mfcc",
"=",
"self",
".",
"synt_wave_mfcc",
".",
"middle_mfcc",
"n",
"=",
"real_mfcc",
".",
"shape",
"[",
"1",
"]",
"m",
"=",
"synt_mfcc",
".",
"shape",
"[",
"1",
"]",
"self",
".",
"log",
"(",
"[",
"u\" Number of MFCC frames in real wave: %d\"",
",",
"n",
"]",
")",
"self",
".",
"log",
"(",
"[",
"u\" Number of MFCC frames in synt wave: %d\"",
",",
"m",
"]",
")",
"if",
"(",
"n",
"==",
"0",
")",
"or",
"(",
"m",
"==",
"0",
")",
":",
"self",
".",
"log",
"(",
"u\"Setting self.dtw to None\"",
")",
"self",
".",
"dtw",
"=",
"None",
"else",
":",
"# set the selected algorithm",
"if",
"algorithm",
"==",
"DTWAlgorithm",
".",
"EXACT",
":",
"self",
".",
"log",
"(",
"u\"Computing with EXACT algo\"",
")",
"self",
".",
"dtw",
"=",
"DTWExact",
"(",
"m1",
"=",
"real_mfcc",
",",
"m2",
"=",
"synt_mfcc",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"else",
":",
"self",
".",
"log",
"(",
"u\"Computing with STRIPE algo\"",
")",
"self",
".",
"dtw",
"=",
"DTWStripe",
"(",
"m1",
"=",
"real_mfcc",
",",
"m2",
"=",
"synt_mfcc",
",",
"delta",
"=",
"delta",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")"
] | Set the DTW object up. | [
"Set",
"the",
"DTW",
"object",
"up",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/dtw.py#L298-L363 |
232,193 | readbeyond/aeneas | check_dependencies.py | check_import | def check_import():
"""
Try to import the aeneas package and return ``True`` if that fails.
"""
try:
import aeneas
print_success(u"aeneas OK")
return False
except ImportError:
print_error(u"aeneas ERROR")
print_info(u" Unable to load the aeneas Python package")
print_info(u" This error is probably caused by:")
print_info(u" A. you did not download/git-clone the aeneas package properly; or")
print_info(u" B. you did not install the required Python packages:")
print_info(u" 1. BeautifulSoup4")
print_info(u" 2. lxml")
print_info(u" 3. numpy")
except Exception as e:
print_error(e)
return True | python | def check_import():
"""
Try to import the aeneas package and return ``True`` if that fails.
"""
try:
import aeneas
print_success(u"aeneas OK")
return False
except ImportError:
print_error(u"aeneas ERROR")
print_info(u" Unable to load the aeneas Python package")
print_info(u" This error is probably caused by:")
print_info(u" A. you did not download/git-clone the aeneas package properly; or")
print_info(u" B. you did not install the required Python packages:")
print_info(u" 1. BeautifulSoup4")
print_info(u" 2. lxml")
print_info(u" 3. numpy")
except Exception as e:
print_error(e)
return True | [
"def",
"check_import",
"(",
")",
":",
"try",
":",
"import",
"aeneas",
"print_success",
"(",
"u\"aeneas OK\"",
")",
"return",
"False",
"except",
"ImportError",
":",
"print_error",
"(",
"u\"aeneas ERROR\"",
")",
"print_info",
"(",
"u\" Unable to load the aeneas Python package\"",
")",
"print_info",
"(",
"u\" This error is probably caused by:\"",
")",
"print_info",
"(",
"u\" A. you did not download/git-clone the aeneas package properly; or\"",
")",
"print_info",
"(",
"u\" B. you did not install the required Python packages:\"",
")",
"print_info",
"(",
"u\" 1. BeautifulSoup4\"",
")",
"print_info",
"(",
"u\" 2. lxml\"",
")",
"print_info",
"(",
"u\" 3. numpy\"",
")",
"except",
"Exception",
"as",
"e",
":",
"print_error",
"(",
"e",
")",
"return",
"True"
] | Try to import the aeneas package and return ``True`` if that fails. | [
"Try",
"to",
"import",
"the",
"aeneas",
"package",
"and",
"return",
"True",
"if",
"that",
"fails",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/check_dependencies.py#L86-L105 |
232,194 | readbeyond/aeneas | check_dependencies.py | main | def main():
""" The entry point for this module """
# first, check we can import aeneas package, exiting on failure
if check_import():
sys.exit(1)
# import and run the built-in diagnostics
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_all()
if errors:
sys.exit(1)
if c_ext_warnings:
print_warning(u"All required dependencies are met but at least one Python C extension is not available")
print_warning(u"You can still run aeneas but it will be slower")
print_warning(u"Enjoy running aeneas!")
sys.exit(2)
else:
print_success(u"All required dependencies are met and all available Python C extensions are working")
print_success(u"Enjoy running aeneas!")
sys.exit(0) | python | def main():
""" The entry point for this module """
# first, check we can import aeneas package, exiting on failure
if check_import():
sys.exit(1)
# import and run the built-in diagnostics
from aeneas.diagnostics import Diagnostics
errors, warnings, c_ext_warnings = Diagnostics.check_all()
if errors:
sys.exit(1)
if c_ext_warnings:
print_warning(u"All required dependencies are met but at least one Python C extension is not available")
print_warning(u"You can still run aeneas but it will be slower")
print_warning(u"Enjoy running aeneas!")
sys.exit(2)
else:
print_success(u"All required dependencies are met and all available Python C extensions are working")
print_success(u"Enjoy running aeneas!")
sys.exit(0) | [
"def",
"main",
"(",
")",
":",
"# first, check we can import aeneas package, exiting on failure",
"if",
"check_import",
"(",
")",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"# import and run the built-in diagnostics",
"from",
"aeneas",
".",
"diagnostics",
"import",
"Diagnostics",
"errors",
",",
"warnings",
",",
"c_ext_warnings",
"=",
"Diagnostics",
".",
"check_all",
"(",
")",
"if",
"errors",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"c_ext_warnings",
":",
"print_warning",
"(",
"u\"All required dependencies are met but at least one Python C extension is not available\"",
")",
"print_warning",
"(",
"u\"You can still run aeneas but it will be slower\"",
")",
"print_warning",
"(",
"u\"Enjoy running aeneas!\"",
")",
"sys",
".",
"exit",
"(",
"2",
")",
"else",
":",
"print_success",
"(",
"u\"All required dependencies are met and all available Python C extensions are working\"",
")",
"print_success",
"(",
"u\"Enjoy running aeneas!\"",
")",
"sys",
".",
"exit",
"(",
"0",
")"
] | The entry point for this module | [
"The",
"entry",
"point",
"for",
"this",
"module"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/check_dependencies.py#L108-L127 |
232,195 | readbeyond/aeneas | aeneas/tree.py | Tree.is_pleasant | def is_pleasant(self):
"""
Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool
"""
levels = sorted([n.level for n in self.leaves])
return levels[0] == levels[-1] | python | def is_pleasant(self):
"""
Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool
"""
levels = sorted([n.level for n in self.leaves])
return levels[0] == levels[-1] | [
"def",
"is_pleasant",
"(",
"self",
")",
":",
"levels",
"=",
"sorted",
"(",
"[",
"n",
".",
"level",
"for",
"n",
"in",
"self",
".",
"leaves",
"]",
")",
"return",
"levels",
"[",
"0",
"]",
"==",
"levels",
"[",
"-",
"1",
"]"
] | Return ``True`` if all the leaves
in the subtree rooted at this node
are at the same level.
:rtype: bool | [
"Return",
"True",
"if",
"all",
"the",
"leaves",
"in",
"the",
"subtree",
"rooted",
"at",
"this",
"node",
"are",
"at",
"the",
"same",
"level",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L208-L217 |
232,196 | readbeyond/aeneas | aeneas/tree.py | Tree.add_child | 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 of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree`
"""
if not isinstance(node, Tree):
self.log_exc(u"node is not an instance of Tree", None, True, TypeError)
if as_last:
self.__children.append(node)
else:
self.__children = [node] + self.__children
node.__parent = self
new_height = 1 + self.level
for n in node.subtree:
n.__level += new_height | python | 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 of ``node``.
:param node: the child node to be added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree`
"""
if not isinstance(node, Tree):
self.log_exc(u"node is not an instance of Tree", None, True, TypeError)
if as_last:
self.__children.append(node)
else:
self.__children = [node] + self.__children
node.__parent = self
new_height = 1 + self.level
for n in node.subtree:
n.__level += new_height | [
"def",
"add_child",
"(",
"self",
",",
"node",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
",",
"Tree",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"node is not an instance of Tree\"",
",",
"None",
",",
"True",
",",
"TypeError",
")",
"if",
"as_last",
":",
"self",
".",
"__children",
".",
"append",
"(",
"node",
")",
"else",
":",
"self",
".",
"__children",
"=",
"[",
"node",
"]",
"+",
"self",
".",
"__children",
"node",
".",
"__parent",
"=",
"self",
"new_height",
"=",
"1",
"+",
"self",
".",
"level",
"for",
"n",
"in",
"node",
".",
"subtree",
":",
"n",
".",
"__level",
"+=",
"new_height"
] | 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 added
:type node: :class:`~aeneas.tree.Tree`
:param bool as_last: if ``True``, append the node as the last child;
if ``False``, append the node as the first child
:raises: TypeError if ``node`` is not an instance of :class:`~aeneas.tree.Tree` | [
"Add",
"the",
"given",
"child",
"to",
"the",
"current",
"list",
"of",
"children",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L219-L243 |
232,197 | readbeyond/aeneas | aeneas/tree.py | Tree.remove_child | 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] + self.__children[(index + 1):] | python | 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] + self.__children[(index + 1):] | [
"def",
"remove_child",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"index",
"+",
"len",
"(",
"self",
")",
"self",
".",
"__children",
"=",
"self",
".",
"__children",
"[",
"0",
":",
"index",
"]",
"+",
"self",
".",
"__children",
"[",
"(",
"index",
"+",
"1",
")",
":",
"]"
] | Remove the child at the given index
from the current list of children.
:param int index: the index of the child to be removed | [
"Remove",
"the",
"child",
"at",
"the",
"given",
"index",
"from",
"the",
"current",
"list",
"of",
"children",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L245-L254 |
232,198 | readbeyond/aeneas | aeneas/tree.py | Tree.remove | 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):
if id(child) == id(self):
self.parent.remove_child(i)
self.parent = None
break | python | 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):
if id(child) == id(self):
self.parent.remove_child(i)
self.parent = None
break | [
"def",
"remove",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"for",
"i",
",",
"child",
"in",
"enumerate",
"(",
"self",
".",
"parent",
".",
"children",
")",
":",
"if",
"id",
"(",
"child",
")",
"==",
"id",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"remove_child",
"(",
"i",
")",
"self",
".",
"parent",
"=",
"None",
"break"
] | 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 | [
"Remove",
"this",
"node",
"from",
"the",
"list",
"of",
"children",
"of",
"its",
"current",
"parent",
"if",
"the",
"current",
"parent",
"is",
"not",
"None",
"otherwise",
"do",
"nothing",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L256-L268 |
232,199 | readbeyond/aeneas | aeneas/tree.py | Tree.remove_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:
child.parent = None
self.__children = [] | python | 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:
child.parent = None
self.__children = [] | [
"def",
"remove_children",
"(",
"self",
",",
"reset_parent",
"=",
"True",
")",
":",
"if",
"reset_parent",
":",
"for",
"child",
"in",
"self",
".",
"children",
":",
"child",
".",
"parent",
"=",
"None",
"self",
".",
"__children",
"=",
"[",
"]"
] | Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children | [
"Remove",
"all",
"the",
"children",
"of",
"this",
"node",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tree.py#L270-L280 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.