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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
readbeyond/aeneas | aeneas/textfile.py | TransliterationMap._build_map | def _build_map(self):
"""
Read the map file at path.
"""
if gf.is_py2_narrow_build():
self.log_warn(u"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.")
self.trans_map = {}
with io.open(self.file_path, "r", encoding="utf-8") as file_obj:
contents = file_obj.read().replace(u"\t", u" ")
for line in contents.splitlines():
# ignore lines starting with "#" or blank (after stripping)
if not line.startswith(u"#"):
line = line.strip()
if len(line) > 0:
self._process_map_rule(line) | python | def _build_map(self):
"""
Read the map file at path.
"""
if gf.is_py2_narrow_build():
self.log_warn(u"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.")
self.trans_map = {}
with io.open(self.file_path, "r", encoding="utf-8") as file_obj:
contents = file_obj.read().replace(u"\t", u" ")
for line in contents.splitlines():
# ignore lines starting with "#" or blank (after stripping)
if not line.startswith(u"#"):
line = line.strip()
if len(line) > 0:
self._process_map_rule(line) | [
"def",
"_build_map",
"(",
"self",
")",
":",
"if",
"gf",
".",
"is_py2_narrow_build",
"(",
")",
":",
"self",
".",
"log_warn",
"(",
"u\"Running on a Python 2 narrow build: be aware that Unicode chars above 0x10000 cannot be replaced correctly.\"",
")",
"self",
".",
"trans_map"... | Read the map file at path. | [
"Read",
"the",
"map",
"file",
"at",
"path",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1241-L1255 | train | 227,100 |
readbeyond/aeneas | aeneas/textfile.py | TransliterationMap._process_map_rule | def _process_map_rule(self, line):
"""
Process the line string containing a map rule.
"""
result = self.REPLACE_REGEX.match(line)
if result is not None:
what = self._process_first_group(result.group(1))
replacement = self._process_second_group(result.group(2))
for char in what:
self.trans_map[char] = replacement
self.log([u"Adding rule: replace '%s' with '%s'", char, replacement])
else:
result = self.DELETE_REGEX.match(line)
if result is not None:
what = self._process_first_group(result.group(1))
for char in what:
self.trans_map[char] = ""
self.log([u"Adding rule: delete '%s'", char]) | python | def _process_map_rule(self, line):
"""
Process the line string containing a map rule.
"""
result = self.REPLACE_REGEX.match(line)
if result is not None:
what = self._process_first_group(result.group(1))
replacement = self._process_second_group(result.group(2))
for char in what:
self.trans_map[char] = replacement
self.log([u"Adding rule: replace '%s' with '%s'", char, replacement])
else:
result = self.DELETE_REGEX.match(line)
if result is not None:
what = self._process_first_group(result.group(1))
for char in what:
self.trans_map[char] = ""
self.log([u"Adding rule: delete '%s'", char]) | [
"def",
"_process_map_rule",
"(",
"self",
",",
"line",
")",
":",
"result",
"=",
"self",
".",
"REPLACE_REGEX",
".",
"match",
"(",
"line",
")",
"if",
"result",
"is",
"not",
"None",
":",
"what",
"=",
"self",
".",
"_process_first_group",
"(",
"result",
".",
... | Process the line string containing a map rule. | [
"Process",
"the",
"line",
"string",
"containing",
"a",
"map",
"rule",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1257-L1274 | train | 227,101 |
readbeyond/aeneas | aeneas/textfile.py | TransliterationMap._process_first_group | def _process_first_group(self, group):
"""
Process the first group of a rule.
"""
if "-" in group:
# range
if len(group.split("-")) == 2:
arr = group.split("-")
start = self._parse_codepoint(arr[0])
end = self._parse_codepoint(arr[1])
else:
# single char/U+xxxx
start = self._parse_codepoint(group)
end = start
result = []
if (start > -1) and (end >= start):
for index in range(start, end + 1):
result.append(gf.safe_unichr(index))
return result | python | def _process_first_group(self, group):
"""
Process the first group of a rule.
"""
if "-" in group:
# range
if len(group.split("-")) == 2:
arr = group.split("-")
start = self._parse_codepoint(arr[0])
end = self._parse_codepoint(arr[1])
else:
# single char/U+xxxx
start = self._parse_codepoint(group)
end = start
result = []
if (start > -1) and (end >= start):
for index in range(start, end + 1):
result.append(gf.safe_unichr(index))
return result | [
"def",
"_process_first_group",
"(",
"self",
",",
"group",
")",
":",
"if",
"\"-\"",
"in",
"group",
":",
"# range",
"if",
"len",
"(",
"group",
".",
"split",
"(",
"\"-\"",
")",
")",
"==",
"2",
":",
"arr",
"=",
"group",
".",
"split",
"(",
"\"-\"",
")",... | Process the first group of a rule. | [
"Process",
"the",
"first",
"group",
"of",
"a",
"rule",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/textfile.py#L1276-L1294 | train | 227,102 |
readbeyond/aeneas | aeneas/executejob.py | ExecuteJob.load_job | def load_job(self, job):
"""
Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job`
"""
if not isinstance(job, Job):
self.log_exc(u"job is not an instance of Job", None, True, ExecuteJobInputError)
self.job = job | python | def load_job(self, job):
"""
Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job`
"""
if not isinstance(job, Job):
self.log_exc(u"job is not an instance of Job", None, True, ExecuteJobInputError)
self.job = job | [
"def",
"load_job",
"(",
"self",
",",
"job",
")",
":",
"if",
"not",
"isinstance",
"(",
"job",
",",
"Job",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"job is not an instance of Job\"",
",",
"None",
",",
"True",
",",
"ExecuteJobInputError",
")",
"self",
".",
... | Load the job from the given ``Job`` object.
:param job: the job to load
:type job: :class:`~aeneas.job.Job`
:raises: :class:`~aeneas.executejob.ExecuteJobInputError`: if ``job`` is not an instance of :class:`~aeneas.job.Job` | [
"Load",
"the",
"job",
"from",
"the",
"given",
"Job",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L110-L120 | train | 227,103 |
readbeyond/aeneas | aeneas/executejob.py | ExecuteJob.execute | def execute(self):
"""
Execute the job, that is, execute all of its tasks.
Each produced sync map will be stored
inside the corresponding task object.
:raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
"""
self.log(u"Executing job")
if self.job is None:
self.log_exc(u"The job object is None", None, True, ExecuteJobExecutionError)
if len(self.job) == 0:
self.log_exc(u"The job has no tasks", None, True, ExecuteJobExecutionError)
job_max_tasks = self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
if (job_max_tasks > 0) and (len(self.job) > job_max_tasks):
self.log_exc(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (len(self.job), job_max_tasks), None, True, ExecuteJobExecutionError)
self.log([u"Number of tasks: '%d'", len(self.job)])
for task in self.job.tasks:
try:
custom_id = task.configuration["custom_id"]
self.log([u"Executing task '%s'...", custom_id])
executor = ExecuteTask(task, rconf=self.rconf, logger=self.logger)
executor.execute()
self.log([u"Executing task '%s'... done", custom_id])
except Exception as exc:
self.log_exc(u"Error while executing task '%s'" % (custom_id), exc, True, ExecuteJobExecutionError)
self.log(u"Executing task: succeeded")
self.log(u"Executing job: succeeded") | python | def execute(self):
"""
Execute the job, that is, execute all of its tasks.
Each produced sync map will be stored
inside the corresponding task object.
:raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
"""
self.log(u"Executing job")
if self.job is None:
self.log_exc(u"The job object is None", None, True, ExecuteJobExecutionError)
if len(self.job) == 0:
self.log_exc(u"The job has no tasks", None, True, ExecuteJobExecutionError)
job_max_tasks = self.rconf[RuntimeConfiguration.JOB_MAX_TASKS]
if (job_max_tasks > 0) and (len(self.job) > job_max_tasks):
self.log_exc(u"The Job has %d Tasks, more than the maximum allowed (%d)." % (len(self.job), job_max_tasks), None, True, ExecuteJobExecutionError)
self.log([u"Number of tasks: '%d'", len(self.job)])
for task in self.job.tasks:
try:
custom_id = task.configuration["custom_id"]
self.log([u"Executing task '%s'...", custom_id])
executor = ExecuteTask(task, rconf=self.rconf, logger=self.logger)
executor.execute()
self.log([u"Executing task '%s'... done", custom_id])
except Exception as exc:
self.log_exc(u"Error while executing task '%s'" % (custom_id), exc, True, ExecuteJobExecutionError)
self.log(u"Executing task: succeeded")
self.log(u"Executing job: succeeded") | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing job\"",
")",
"if",
"self",
".",
"job",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The job object is None\"",
",",
"None",
",",
"True",
",",
"ExecuteJobExecutionError",
... | Execute the job, that is, execute all of its tasks.
Each produced sync map will be stored
inside the corresponding task object.
:raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution | [
"Execute",
"the",
"job",
"that",
"is",
"execute",
"all",
"of",
"its",
"tasks",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L187-L218 | train | 227,104 |
readbeyond/aeneas | aeneas/executejob.py | ExecuteJob.write_output_container | def write_output_container(self, output_directory_path):
"""
Write the output container for this job.
Return the path to output container,
which is the concatenation of ``output_directory_path``
and of the output container file or directory name.
:param string output_directory_path: the path to a directory where
the output container must be created
:rtype: string
:raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container
"""
self.log(u"Writing output container for this job")
if self.job is None:
self.log_exc(u"The job object is None", None, True, ExecuteJobOutputError)
if len(self.job) == 0:
self.log_exc(u"The job has no tasks", None, True, ExecuteJobOutputError)
self.log([u"Number of tasks: '%d'", len(self.job)])
# create temporary directory where the sync map files
# will be created
# this temporary directory will be compressed into
# the output container
self.tmp_directory = gf.tmp_directory(root=self.rconf[RuntimeConfiguration.TMP_PATH])
self.log([u"Created temporary directory '%s'", self.tmp_directory])
for task in self.job.tasks:
custom_id = task.configuration["custom_id"]
# check if the task has sync map and sync map file path
if task.sync_map_file_path is None:
self.log_exc(u"Task '%s' has sync_map_file_path not set" % (custom_id), None, True, ExecuteJobOutputError)
if task.sync_map is None:
self.log_exc(u"Task '%s' has sync_map not set" % (custom_id), None, True, ExecuteJobOutputError)
try:
# output sync map
self.log([u"Outputting sync map for task '%s'...", custom_id])
task.output_sync_map_file(self.tmp_directory)
self.log([u"Outputting sync map for task '%s'... done", custom_id])
except Exception as exc:
self.log_exc(u"Error while outputting sync map for task '%s'" % (custom_id), None, True, ExecuteJobOutputError)
# get output container info
output_container_format = self.job.configuration["o_container_format"]
self.log([u"Output container format: '%s'", output_container_format])
output_file_name = self.job.configuration["o_name"]
if ((output_container_format != ContainerFormat.UNPACKED) and
(not output_file_name.endswith(output_container_format))):
self.log(u"Adding extension to output_file_name")
output_file_name += "." + output_container_format
self.log([u"Output file name: '%s'", output_file_name])
output_file_path = gf.norm_join(
output_directory_path,
output_file_name
)
self.log([u"Output file path: '%s'", output_file_path])
try:
self.log(u"Compressing...")
container = Container(
output_file_path,
output_container_format,
logger=self.logger
)
container.compress(self.tmp_directory)
self.log(u"Compressing... done")
self.log([u"Created output file: '%s'", output_file_path])
self.log(u"Writing output container for this job: succeeded")
self.clean(False)
return output_file_path
except Exception as exc:
self.clean(False)
self.log_exc(u"Error while compressing", exc, True, ExecuteJobOutputError)
return None | python | def write_output_container(self, output_directory_path):
"""
Write the output container for this job.
Return the path to output container,
which is the concatenation of ``output_directory_path``
and of the output container file or directory name.
:param string output_directory_path: the path to a directory where
the output container must be created
:rtype: string
:raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container
"""
self.log(u"Writing output container for this job")
if self.job is None:
self.log_exc(u"The job object is None", None, True, ExecuteJobOutputError)
if len(self.job) == 0:
self.log_exc(u"The job has no tasks", None, True, ExecuteJobOutputError)
self.log([u"Number of tasks: '%d'", len(self.job)])
# create temporary directory where the sync map files
# will be created
# this temporary directory will be compressed into
# the output container
self.tmp_directory = gf.tmp_directory(root=self.rconf[RuntimeConfiguration.TMP_PATH])
self.log([u"Created temporary directory '%s'", self.tmp_directory])
for task in self.job.tasks:
custom_id = task.configuration["custom_id"]
# check if the task has sync map and sync map file path
if task.sync_map_file_path is None:
self.log_exc(u"Task '%s' has sync_map_file_path not set" % (custom_id), None, True, ExecuteJobOutputError)
if task.sync_map is None:
self.log_exc(u"Task '%s' has sync_map not set" % (custom_id), None, True, ExecuteJobOutputError)
try:
# output sync map
self.log([u"Outputting sync map for task '%s'...", custom_id])
task.output_sync_map_file(self.tmp_directory)
self.log([u"Outputting sync map for task '%s'... done", custom_id])
except Exception as exc:
self.log_exc(u"Error while outputting sync map for task '%s'" % (custom_id), None, True, ExecuteJobOutputError)
# get output container info
output_container_format = self.job.configuration["o_container_format"]
self.log([u"Output container format: '%s'", output_container_format])
output_file_name = self.job.configuration["o_name"]
if ((output_container_format != ContainerFormat.UNPACKED) and
(not output_file_name.endswith(output_container_format))):
self.log(u"Adding extension to output_file_name")
output_file_name += "." + output_container_format
self.log([u"Output file name: '%s'", output_file_name])
output_file_path = gf.norm_join(
output_directory_path,
output_file_name
)
self.log([u"Output file path: '%s'", output_file_path])
try:
self.log(u"Compressing...")
container = Container(
output_file_path,
output_container_format,
logger=self.logger
)
container.compress(self.tmp_directory)
self.log(u"Compressing... done")
self.log([u"Created output file: '%s'", output_file_path])
self.log(u"Writing output container for this job: succeeded")
self.clean(False)
return output_file_path
except Exception as exc:
self.clean(False)
self.log_exc(u"Error while compressing", exc, True, ExecuteJobOutputError)
return None | [
"def",
"write_output_container",
"(",
"self",
",",
"output_directory_path",
")",
":",
"self",
".",
"log",
"(",
"u\"Writing output container for this job\"",
")",
"if",
"self",
".",
"job",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The job object is None\"",... | Write the output container for this job.
Return the path to output container,
which is the concatenation of ``output_directory_path``
and of the output container file or directory name.
:param string output_directory_path: the path to a directory where
the output container must be created
:rtype: string
:raises: :class:`~aeneas.executejob.ExecuteJobOutputError`: if there is a problem while writing the output container | [
"Write",
"the",
"output",
"container",
"for",
"this",
"job",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L220-L296 | train | 227,105 |
readbeyond/aeneas | aeneas/executejob.py | ExecuteJob.clean | def clean(self, remove_working_directory=True):
"""
Remove the temporary directory.
If ``remove_working_directory`` is ``True``
remove the working directory as well,
otherwise just remove the temporary directory.
:param bool remove_working_directory: if ``True``, remove
the working directory as well
"""
if remove_working_directory is not None:
self.log(u"Removing working directory... ")
gf.delete_directory(self.working_directory)
self.working_directory = None
self.log(u"Removing working directory... done")
self.log(u"Removing temporary directory... ")
gf.delete_directory(self.tmp_directory)
self.tmp_directory = None
self.log(u"Removing temporary directory... done") | python | def clean(self, remove_working_directory=True):
"""
Remove the temporary directory.
If ``remove_working_directory`` is ``True``
remove the working directory as well,
otherwise just remove the temporary directory.
:param bool remove_working_directory: if ``True``, remove
the working directory as well
"""
if remove_working_directory is not None:
self.log(u"Removing working directory... ")
gf.delete_directory(self.working_directory)
self.working_directory = None
self.log(u"Removing working directory... done")
self.log(u"Removing temporary directory... ")
gf.delete_directory(self.tmp_directory)
self.tmp_directory = None
self.log(u"Removing temporary directory... done") | [
"def",
"clean",
"(",
"self",
",",
"remove_working_directory",
"=",
"True",
")",
":",
"if",
"remove_working_directory",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"u\"Removing working directory... \"",
")",
"gf",
".",
"delete_directory",
"(",
"self",
".",... | Remove the temporary directory.
If ``remove_working_directory`` is ``True``
remove the working directory as well,
otherwise just remove the temporary directory.
:param bool remove_working_directory: if ``True``, remove
the working directory as well | [
"Remove",
"the",
"temporary",
"directory",
".",
"If",
"remove_working_directory",
"is",
"True",
"remove",
"the",
"working",
"directory",
"as",
"well",
"otherwise",
"just",
"remove",
"the",
"temporary",
"directory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executejob.py#L298-L316 | train | 227,106 |
readbeyond/aeneas | aeneas/tools/plot_waveform.py | PlotWaveformCLI._read_syncmap_file | def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragments]
return [(f.begin, f.end, f.text_fragment.identifier) for f in syncmap.fragments] | python | def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragments]
return [(f.begin, f.end, f.text_fragment.identifier) for f in syncmap.fragments] | [
"def",
"_read_syncmap_file",
"(",
"self",
",",
"path",
",",
"extension",
",",
"text",
"=",
"False",
")",
":",
"syncmap",
"=",
"SyncMap",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"syncmap",
".",
"read",
"(",
"extension",
",",
"path",
",",
"parame... | Read labels from a SyncMap file | [
"Read",
"labels",
"from",
"a",
"SyncMap",
"file"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/plot_waveform.py#L156-L162 | train | 227,107 |
readbeyond/aeneas | aeneas/syncmap/__init__.py | SyncMap.has_adjacent_leaves_only | def has_adjacent_leaves_only(self):
"""
Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
are all adjacent.
:rtype: bool
.. versionadded:: 1.7.0
"""
leaves = self.leaves()
for i in range(len(leaves) - 1):
current_interval = leaves[i].interval
next_interval = leaves[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
return False
return True | python | def has_adjacent_leaves_only(self):
"""
Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
are all adjacent.
:rtype: bool
.. versionadded:: 1.7.0
"""
leaves = self.leaves()
for i in range(len(leaves) - 1):
current_interval = leaves[i].interval
next_interval = leaves[i + 1].interval
if not current_interval.is_adjacent_before(next_interval):
return False
return True | [
"def",
"has_adjacent_leaves_only",
"(",
"self",
")",
":",
"leaves",
"=",
"self",
".",
"leaves",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"leaves",
")",
"-",
"1",
")",
":",
"current_interval",
"=",
"leaves",
"[",
"i",
"]",
".",
"interval"... | Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
are all adjacent.
:rtype: bool
.. versionadded:: 1.7.0 | [
"Return",
"True",
"if",
"the",
"sync",
"map",
"fragments",
"which",
"are",
"the",
"leaves",
"of",
"the",
"sync",
"map",
"tree",
"are",
"all",
"adjacent",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L169-L185 | train | 227,108 |
readbeyond/aeneas | aeneas/syncmap/__init__.py | SyncMap.json_string | def json_string(self):
"""
Return a JSON representation of the sync map.
:rtype: string
.. versionadded:: 1.3.1
"""
def visit_children(node):
""" Recursively visit the fragments_tree """
output_fragments = []
for child in node.children_not_empty:
fragment = child.value
text = fragment.text_fragment
output_fragments.append({
"id": text.identifier,
"language": text.language,
"lines": text.lines,
"begin": gf.time_to_ssmmm(fragment.begin),
"end": gf.time_to_ssmmm(fragment.end),
"children": visit_children(child)
})
return output_fragments
output_fragments = visit_children(self.fragments_tree)
return gf.safe_unicode(
json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True)
) | python | def json_string(self):
"""
Return a JSON representation of the sync map.
:rtype: string
.. versionadded:: 1.3.1
"""
def visit_children(node):
""" Recursively visit the fragments_tree """
output_fragments = []
for child in node.children_not_empty:
fragment = child.value
text = fragment.text_fragment
output_fragments.append({
"id": text.identifier,
"language": text.language,
"lines": text.lines,
"begin": gf.time_to_ssmmm(fragment.begin),
"end": gf.time_to_ssmmm(fragment.end),
"children": visit_children(child)
})
return output_fragments
output_fragments = visit_children(self.fragments_tree)
return gf.safe_unicode(
json.dumps({"fragments": output_fragments}, indent=1, sort_keys=True)
) | [
"def",
"json_string",
"(",
"self",
")",
":",
"def",
"visit_children",
"(",
"node",
")",
":",
"\"\"\" Recursively visit the fragments_tree \"\"\"",
"output_fragments",
"=",
"[",
"]",
"for",
"child",
"in",
"node",
".",
"children_not_empty",
":",
"fragment",
"=",
"ch... | Return a JSON representation of the sync map.
:rtype: string
.. versionadded:: 1.3.1 | [
"Return",
"a",
"JSON",
"representation",
"of",
"the",
"sync",
"map",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L248-L274 | train | 227,109 |
readbeyond/aeneas | aeneas/syncmap/__init__.py | SyncMap.add_fragment | def add_fragment(self, fragment, as_last=True):
"""
Add the given sync map fragment,
as the first or last child of the root node
of the sync map tree.
:param fragment: the sync map fragment to be added
:type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment`
:param bool as_last: if ``True``, append fragment; otherwise prepend it
:raises: TypeError: if ``fragment`` is ``None`` or
it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
"""
if not isinstance(fragment, SyncMapFragment):
self.log_exc(u"fragment is not an instance of SyncMapFragment", None, True, TypeError)
self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last) | python | def add_fragment(self, fragment, as_last=True):
"""
Add the given sync map fragment,
as the first or last child of the root node
of the sync map tree.
:param fragment: the sync map fragment to be added
:type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment`
:param bool as_last: if ``True``, append fragment; otherwise prepend it
:raises: TypeError: if ``fragment`` is ``None`` or
it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment`
"""
if not isinstance(fragment, SyncMapFragment):
self.log_exc(u"fragment is not an instance of SyncMapFragment", None, True, TypeError)
self.fragments_tree.add_child(Tree(value=fragment), as_last=as_last) | [
"def",
"add_fragment",
"(",
"self",
",",
"fragment",
",",
"as_last",
"=",
"True",
")",
":",
"if",
"not",
"isinstance",
"(",
"fragment",
",",
"SyncMapFragment",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"fragment is not an instance of SyncMapFragment\"",
",",
"No... | Add the given sync map fragment,
as the first or last child of the root node
of the sync map tree.
:param fragment: the sync map fragment to be added
:type fragment: :class:`~aeneas.syncmap.fragment.SyncMapFragment`
:param bool as_last: if ``True``, append fragment; otherwise prepend it
:raises: TypeError: if ``fragment`` is ``None`` or
it is not an instance of :class:`~aeneas.syncmap.fragment.SyncMapFragment` | [
"Add",
"the",
"given",
"sync",
"map",
"fragment",
"as",
"the",
"first",
"or",
"last",
"child",
"of",
"the",
"root",
"node",
"of",
"the",
"sync",
"map",
"tree",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L276-L290 | train | 227,110 |
readbeyond/aeneas | aeneas/syncmap/__init__.py | SyncMap.output_html_for_tuning | def output_html_for_tuning(
self,
audio_file_path,
output_file_path,
parameters=None
):
"""
Output an HTML file for fine tuning the sync map manually.
:param string audio_file_path: the path to the associated audio file
:param string output_file_path: the path to the output file to write
:param dict parameters: additional parameters
.. versionadded:: 1.3.1
"""
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Cannot output HTML file '%s'. Wrong permissions?" % (output_file_path), None, True, OSError)
if parameters is None:
parameters = {}
audio_file_path_absolute = gf.fix_slash(os.path.abspath(audio_file_path))
template_path_absolute = gf.absolute_path(self.FINETUNEAS_PATH, __file__)
with io.open(template_path_absolute, "r", encoding="utf-8") as file_obj:
template = file_obj.read()
for repl in self.FINETUNEAS_REPLACEMENTS:
template = template.replace(repl[0], repl[1])
template = template.replace(
self.FINETUNEAS_REPLACE_AUDIOFILEPATH,
u"audioFilePath = \"file://%s\";" % audio_file_path_absolute
)
template = template.replace(
self.FINETUNEAS_REPLACE_FRAGMENTS,
u"fragments = (%s).fragments;" % self.json_string
)
if gc.PPN_TASK_OS_FILE_FORMAT in parameters:
output_format = parameters[gc.PPN_TASK_OS_FILE_FORMAT]
if output_format in self.FINETUNEAS_ALLOWED_FORMATS:
template = template.replace(
self.FINETUNEAS_REPLACE_OUTPUT_FORMAT,
u"outputFormat = \"%s\";" % output_format
)
if output_format == "smil":
for key, placeholder, replacement in [
(
gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF,
self.FINETUNEAS_REPLACE_SMIL_AUDIOREF,
"audioref = \"%s\";"
),
(
gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF,
self.FINETUNEAS_REPLACE_SMIL_PAGEREF,
"pageref = \"%s\";"
),
]:
if key in parameters:
template = template.replace(
placeholder,
replacement % parameters[key]
)
with io.open(output_file_path, "w", encoding="utf-8") as file_obj:
file_obj.write(template) | python | def output_html_for_tuning(
self,
audio_file_path,
output_file_path,
parameters=None
):
"""
Output an HTML file for fine tuning the sync map manually.
:param string audio_file_path: the path to the associated audio file
:param string output_file_path: the path to the output file to write
:param dict parameters: additional parameters
.. versionadded:: 1.3.1
"""
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Cannot output HTML file '%s'. Wrong permissions?" % (output_file_path), None, True, OSError)
if parameters is None:
parameters = {}
audio_file_path_absolute = gf.fix_slash(os.path.abspath(audio_file_path))
template_path_absolute = gf.absolute_path(self.FINETUNEAS_PATH, __file__)
with io.open(template_path_absolute, "r", encoding="utf-8") as file_obj:
template = file_obj.read()
for repl in self.FINETUNEAS_REPLACEMENTS:
template = template.replace(repl[0], repl[1])
template = template.replace(
self.FINETUNEAS_REPLACE_AUDIOFILEPATH,
u"audioFilePath = \"file://%s\";" % audio_file_path_absolute
)
template = template.replace(
self.FINETUNEAS_REPLACE_FRAGMENTS,
u"fragments = (%s).fragments;" % self.json_string
)
if gc.PPN_TASK_OS_FILE_FORMAT in parameters:
output_format = parameters[gc.PPN_TASK_OS_FILE_FORMAT]
if output_format in self.FINETUNEAS_ALLOWED_FORMATS:
template = template.replace(
self.FINETUNEAS_REPLACE_OUTPUT_FORMAT,
u"outputFormat = \"%s\";" % output_format
)
if output_format == "smil":
for key, placeholder, replacement in [
(
gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF,
self.FINETUNEAS_REPLACE_SMIL_AUDIOREF,
"audioref = \"%s\";"
),
(
gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF,
self.FINETUNEAS_REPLACE_SMIL_PAGEREF,
"pageref = \"%s\";"
),
]:
if key in parameters:
template = template.replace(
placeholder,
replacement % parameters[key]
)
with io.open(output_file_path, "w", encoding="utf-8") as file_obj:
file_obj.write(template) | [
"def",
"output_html_for_tuning",
"(",
"self",
",",
"audio_file_path",
",",
"output_file_path",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"not",
"gf",
".",
"file_can_be_written",
"(",
"output_file_path",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Cannot out... | Output an HTML file for fine tuning the sync map manually.
:param string audio_file_path: the path to the associated audio file
:param string output_file_path: the path to the output file to write
:param dict parameters: additional parameters
.. versionadded:: 1.3.1 | [
"Output",
"an",
"HTML",
"file",
"for",
"fine",
"tuning",
"the",
"sync",
"map",
"manually",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L309-L368 | train | 227,111 |
readbeyond/aeneas | aeneas/mfcc.py | MFCC._create_dct_matrix | def _create_dct_matrix(self):
"""
Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```.
"""
self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size))
for i in range(0, self.mfcc_size):
freq = numpy.pi * float(i) / self.filter_bank_size
self.s2dct[i] = numpy.cos(freq * numpy.arange(0.5, 0.5 + self.filter_bank_size, 1.0, 'float64'))
self.s2dct[:, 0] *= 0.5
self.s2dct = self.s2dct.transpose() | python | def _create_dct_matrix(self):
"""
Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```.
"""
self.s2dct = numpy.zeros((self.mfcc_size, self.filter_bank_size))
for i in range(0, self.mfcc_size):
freq = numpy.pi * float(i) / self.filter_bank_size
self.s2dct[i] = numpy.cos(freq * numpy.arange(0.5, 0.5 + self.filter_bank_size, 1.0, 'float64'))
self.s2dct[:, 0] *= 0.5
self.s2dct = self.s2dct.transpose() | [
"def",
"_create_dct_matrix",
"(",
"self",
")",
":",
"self",
".",
"s2dct",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"self",
".",
"mfcc_size",
",",
"self",
".",
"filter_bank_size",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"mfcc_siz... | Create the not-quite-DCT matrix as used by Sphinx,
and store it in ```self.s2dct```. | [
"Create",
"the",
"not",
"-",
"quite",
"-",
"DCT",
"matrix",
"as",
"used",
"by",
"Sphinx",
"and",
"store",
"it",
"in",
"self",
".",
"s2dct",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L104-L114 | train | 227,112 |
readbeyond/aeneas | aeneas/mfcc.py | MFCC._create_mel_filter_bank | def _create_mel_filter_bank(self):
"""
Create the Mel filter bank,
and store it in ``self.filters``.
Note that it is a function of the audio sample rate,
so it cannot be created in the class initializer,
but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`.
"""
self.filters = numpy.zeros((1 + (self.fft_order // 2), self.filter_bank_size), 'd')
dfreq = float(self.sample_rate) / self.fft_order
nyquist_frequency = self.sample_rate / 2
if self.upper_frequency > nyquist_frequency:
self.log_exc(u"Upper frequency %f exceeds Nyquist frequency %f" % (self.upper_frequency, nyquist_frequency), None, True, ValueError)
melmax = MFCC._hz2mel(self.upper_frequency)
melmin = MFCC._hz2mel(self.lower_frequency)
dmelbw = (melmax - melmin) / (self.filter_bank_size + 1)
filt_edge = MFCC._mel2hz(melmin + dmelbw * numpy.arange(self.filter_bank_size + 2, dtype='d'))
# TODO can this code be written more numpy-style?
# (the performance loss is negligible, it is just ugly to see)
for whichfilt in range(0, self.filter_bank_size):
# int() casts to native int instead of working with numpy.float64
leftfr = int(round(filt_edge[whichfilt] / dfreq))
centerfr = int(round(filt_edge[whichfilt + 1] / dfreq))
rightfr = int(round(filt_edge[whichfilt + 2] / dfreq))
fwidth = (rightfr - leftfr) * dfreq
height = 2.0 / fwidth
if centerfr != leftfr:
leftslope = height / (centerfr - leftfr)
else:
leftslope = 0
freq = leftfr + 1
while freq < centerfr:
self.filters[freq, whichfilt] = (freq - leftfr) * leftslope
freq = freq + 1
# the next if should always be true!
if freq == centerfr:
self.filters[freq, whichfilt] = height
freq = freq + 1
if centerfr != rightfr:
rightslope = height / (centerfr - rightfr)
while freq < rightfr:
self.filters[freq, whichfilt] = (freq - rightfr) * rightslope
freq = freq + 1 | python | def _create_mel_filter_bank(self):
"""
Create the Mel filter bank,
and store it in ``self.filters``.
Note that it is a function of the audio sample rate,
so it cannot be created in the class initializer,
but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`.
"""
self.filters = numpy.zeros((1 + (self.fft_order // 2), self.filter_bank_size), 'd')
dfreq = float(self.sample_rate) / self.fft_order
nyquist_frequency = self.sample_rate / 2
if self.upper_frequency > nyquist_frequency:
self.log_exc(u"Upper frequency %f exceeds Nyquist frequency %f" % (self.upper_frequency, nyquist_frequency), None, True, ValueError)
melmax = MFCC._hz2mel(self.upper_frequency)
melmin = MFCC._hz2mel(self.lower_frequency)
dmelbw = (melmax - melmin) / (self.filter_bank_size + 1)
filt_edge = MFCC._mel2hz(melmin + dmelbw * numpy.arange(self.filter_bank_size + 2, dtype='d'))
# TODO can this code be written more numpy-style?
# (the performance loss is negligible, it is just ugly to see)
for whichfilt in range(0, self.filter_bank_size):
# int() casts to native int instead of working with numpy.float64
leftfr = int(round(filt_edge[whichfilt] / dfreq))
centerfr = int(round(filt_edge[whichfilt + 1] / dfreq))
rightfr = int(round(filt_edge[whichfilt + 2] / dfreq))
fwidth = (rightfr - leftfr) * dfreq
height = 2.0 / fwidth
if centerfr != leftfr:
leftslope = height / (centerfr - leftfr)
else:
leftslope = 0
freq = leftfr + 1
while freq < centerfr:
self.filters[freq, whichfilt] = (freq - leftfr) * leftslope
freq = freq + 1
# the next if should always be true!
if freq == centerfr:
self.filters[freq, whichfilt] = height
freq = freq + 1
if centerfr != rightfr:
rightslope = height / (centerfr - rightfr)
while freq < rightfr:
self.filters[freq, whichfilt] = (freq - rightfr) * rightslope
freq = freq + 1 | [
"def",
"_create_mel_filter_bank",
"(",
"self",
")",
":",
"self",
".",
"filters",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"1",
"+",
"(",
"self",
".",
"fft_order",
"//",
"2",
")",
",",
"self",
".",
"filter_bank_size",
")",
",",
"'d'",
")",
"dfreq",
"=",
... | Create the Mel filter bank,
and store it in ``self.filters``.
Note that it is a function of the audio sample rate,
so it cannot be created in the class initializer,
but only later in :func:`aeneas.mfcc.MFCC.compute_from_data`. | [
"Create",
"the",
"Mel",
"filter",
"bank",
"and",
"store",
"it",
"in",
"self",
".",
"filters",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L116-L160 | train | 227,113 |
readbeyond/aeneas | aeneas/mfcc.py | MFCC._pre_emphasis | def _pre_emphasis(self):
"""
Pre-emphasize the entire signal at once by self.emphasis_factor,
overwriting ``self.data``.
"""
self.data = numpy.append(self.data[0], self.data[1:] - self.emphasis_factor * self.data[:-1]) | python | def _pre_emphasis(self):
"""
Pre-emphasize the entire signal at once by self.emphasis_factor,
overwriting ``self.data``.
"""
self.data = numpy.append(self.data[0], self.data[1:] - self.emphasis_factor * self.data[:-1]) | [
"def",
"_pre_emphasis",
"(",
"self",
")",
":",
"self",
".",
"data",
"=",
"numpy",
".",
"append",
"(",
"self",
".",
"data",
"[",
"0",
"]",
",",
"self",
".",
"data",
"[",
"1",
":",
"]",
"-",
"self",
".",
"emphasis_factor",
"*",
"self",
".",
"data",... | Pre-emphasize the entire signal at once by self.emphasis_factor,
overwriting ``self.data``. | [
"Pre",
"-",
"emphasize",
"the",
"entire",
"signal",
"at",
"once",
"by",
"self",
".",
"emphasis_factor",
"overwriting",
"self",
".",
"data",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L162-L167 | train | 227,114 |
readbeyond/aeneas | aeneas/mfcc.py | MFCC.compute_from_data | def compute_from_data(self, data, sample_rate):
"""
Compute MFCCs for the given audio data.
The audio data must be a 1D :class:`numpy.ndarray`,
that is, it must represent a monoaural (single channel)
array of ``float64`` values in ``[-1.0, 1.0]``.
:param data: the audio data
:type data: :class:`numpy.ndarray` (1D)
:param int sample_rate: the sample rate of the audio data, in samples/s (Hz)
:raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono),
or if the data is empty
:raises: ValueError: if the upper frequency defined in the ``rconf`` is
larger than the Nyquist frequenct (i.e., half of ``sample_rate``)
"""
def _process_frame(self, frame):
"""
Process each frame, returning the log(power()) of it.
"""
# apply Hamming window
frame *= self.hamming_window
# compute RFFT
fft = numpy.fft.rfft(frame, self.fft_order)
# equivalent to power = fft.real * fft.real + fft.imag * fft.imag
power = numpy.square(numpy.absolute(fft))
#
# return the log(power()) of the transformed vector
# v1
# COMMENTED logspec = numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf))
# COMMENTED return numpy.dot(logspec, self.s2dct) / self.filter_bank_size
# v2
return numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf))
if len(data.shape) != 1:
self.log_exc(u"The audio data must be a 1D numpy array (mono).", None, True, ValueError)
if len(data) < 1:
self.log_exc(u"The audio data must not be empty.", None, True, ValueError)
self.data = data
self.sample_rate = sample_rate
# number of samples in the audio
data_length = len(self.data)
# frame length in number of samples
frame_length = int(self.window_length * self.sample_rate)
# frame length must be at least equal to the FFT order
frame_length_padded = max(frame_length, self.fft_order)
# frame shift in number of samples
frame_shift = int(self.window_shift * self.sample_rate)
# number of MFCC vectors (one for each frame)
# this number includes the last shift,
# where the data will be padded with zeros
# if the remaining samples are less than frame_length_padded
number_of_frames = int((1.0 * data_length) / frame_shift)
# create Hamming window
self.hamming_window = numpy.hamming(frame_length_padded)
# build Mel filter bank
self._create_mel_filter_bank()
# pre-emphasize the entire audio data
self._pre_emphasis()
# allocate the MFCCs matrix
# v1
# COMMENTED mfcc = numpy.zeros((number_of_frames, self.mfcc_size), 'float64')
# v2
mfcc = numpy.zeros((number_of_frames, self.filter_bank_size), 'float64')
# compute MFCCs one frame at a time
for frame_index in range(number_of_frames):
# COMMENTED print("Computing frame %d / %d" % (frame_index, number_of_frames))
# get the start and end indices for this frame,
# do not overrun the data length
frame_start = frame_index * frame_shift
frame_end = min(frame_start + frame_length_padded, data_length)
# frame is zero-padded if the remaining samples
# are less than its length
frame = numpy.zeros(frame_length_padded)
frame[0:(frame_end - frame_start)] = self.data[frame_start:frame_end]
# process the frame
mfcc[frame_index] = _process_frame(self, frame)
# v1
# COMMENTED return mfcc
# v2
# return the dot product with the DCT matrix
return numpy.dot(mfcc, self.s2dct) / self.filter_bank_size | python | def compute_from_data(self, data, sample_rate):
"""
Compute MFCCs for the given audio data.
The audio data must be a 1D :class:`numpy.ndarray`,
that is, it must represent a monoaural (single channel)
array of ``float64`` values in ``[-1.0, 1.0]``.
:param data: the audio data
:type data: :class:`numpy.ndarray` (1D)
:param int sample_rate: the sample rate of the audio data, in samples/s (Hz)
:raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono),
or if the data is empty
:raises: ValueError: if the upper frequency defined in the ``rconf`` is
larger than the Nyquist frequenct (i.e., half of ``sample_rate``)
"""
def _process_frame(self, frame):
"""
Process each frame, returning the log(power()) of it.
"""
# apply Hamming window
frame *= self.hamming_window
# compute RFFT
fft = numpy.fft.rfft(frame, self.fft_order)
# equivalent to power = fft.real * fft.real + fft.imag * fft.imag
power = numpy.square(numpy.absolute(fft))
#
# return the log(power()) of the transformed vector
# v1
# COMMENTED logspec = numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf))
# COMMENTED return numpy.dot(logspec, self.s2dct) / self.filter_bank_size
# v2
return numpy.log(numpy.dot(power, self.filters).clip(self.CUTOFF, numpy.inf))
if len(data.shape) != 1:
self.log_exc(u"The audio data must be a 1D numpy array (mono).", None, True, ValueError)
if len(data) < 1:
self.log_exc(u"The audio data must not be empty.", None, True, ValueError)
self.data = data
self.sample_rate = sample_rate
# number of samples in the audio
data_length = len(self.data)
# frame length in number of samples
frame_length = int(self.window_length * self.sample_rate)
# frame length must be at least equal to the FFT order
frame_length_padded = max(frame_length, self.fft_order)
# frame shift in number of samples
frame_shift = int(self.window_shift * self.sample_rate)
# number of MFCC vectors (one for each frame)
# this number includes the last shift,
# where the data will be padded with zeros
# if the remaining samples are less than frame_length_padded
number_of_frames = int((1.0 * data_length) / frame_shift)
# create Hamming window
self.hamming_window = numpy.hamming(frame_length_padded)
# build Mel filter bank
self._create_mel_filter_bank()
# pre-emphasize the entire audio data
self._pre_emphasis()
# allocate the MFCCs matrix
# v1
# COMMENTED mfcc = numpy.zeros((number_of_frames, self.mfcc_size), 'float64')
# v2
mfcc = numpy.zeros((number_of_frames, self.filter_bank_size), 'float64')
# compute MFCCs one frame at a time
for frame_index in range(number_of_frames):
# COMMENTED print("Computing frame %d / %d" % (frame_index, number_of_frames))
# get the start and end indices for this frame,
# do not overrun the data length
frame_start = frame_index * frame_shift
frame_end = min(frame_start + frame_length_padded, data_length)
# frame is zero-padded if the remaining samples
# are less than its length
frame = numpy.zeros(frame_length_padded)
frame[0:(frame_end - frame_start)] = self.data[frame_start:frame_end]
# process the frame
mfcc[frame_index] = _process_frame(self, frame)
# v1
# COMMENTED return mfcc
# v2
# return the dot product with the DCT matrix
return numpy.dot(mfcc, self.s2dct) / self.filter_bank_size | [
"def",
"compute_from_data",
"(",
"self",
",",
"data",
",",
"sample_rate",
")",
":",
"def",
"_process_frame",
"(",
"self",
",",
"frame",
")",
":",
"\"\"\"\n Process each frame, returning the log(power()) of it.\n \"\"\"",
"# apply Hamming window",
"frame"... | Compute MFCCs for the given audio data.
The audio data must be a 1D :class:`numpy.ndarray`,
that is, it must represent a monoaural (single channel)
array of ``float64`` values in ``[-1.0, 1.0]``.
:param data: the audio data
:type data: :class:`numpy.ndarray` (1D)
:param int sample_rate: the sample rate of the audio data, in samples/s (Hz)
:raises: ValueError: if the data is not a 1D :class:`numpy.ndarray` (i.e., not mono),
or if the data is empty
:raises: ValueError: if the upper frequency defined in the ``rconf`` is
larger than the Nyquist frequenct (i.e., half of ``sample_rate``) | [
"Compute",
"MFCCs",
"for",
"the",
"given",
"audio",
"data",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/mfcc.py#L169-L265 | train | 227,115 |
readbeyond/aeneas | aeneas/wavfile.py | write | def write(filename, rate, data):
"""
Write a numpy array as a WAV file
Parameters
----------
filename : string or open file handle
Output wav file
rate : int
The sample rate (in samples/sec).
data : ndarray
A 1-D or 2-D numpy array of either integer or float data-type.
Notes
-----
* The file can be an open file or a filename.
* Writes a simple uncompressed WAV file.
* The bits-per-sample will be determined by the data-type.
* To write multiple-channels, use a 2-D array of shape
(Nsamples, Nchannels).
"""
if hasattr(filename, 'write'):
fid = filename
else:
fid = open(filename, 'wb')
try:
dkind = data.dtype.kind
if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and
data.dtype.itemsize == 1)):
raise ValueError("Unsupported data type '%s'" % data.dtype)
fid.write(b'RIFF')
fid.write(b'\x00\x00\x00\x00')
fid.write(b'WAVE')
# fmt chunk
fid.write(b'fmt ')
if dkind == 'f':
comp = 3
else:
comp = 1
if data.ndim == 1:
noc = 1
else:
noc = data.shape[1]
bits = data.dtype.itemsize * 8
sbytes = rate * (bits // 8) * noc
ba = noc * (bits // 8)
fid.write(struct.pack('<ihHIIHH', 16, comp, noc, rate, sbytes,
ba, bits))
# data chunk
fid.write(b'data')
fid.write(struct.pack('<i', data.nbytes))
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and
sys.byteorder == 'big'):
data = data.byteswap()
_array_tofile(fid, data)
# Determine file size and place it in correct
# position at start of the file.
size = fid.tell()
fid.seek(4)
fid.write(struct.pack('<i', size - 8))
finally:
if not hasattr(filename, 'write'):
fid.close()
else:
fid.seek(0) | python | def write(filename, rate, data):
"""
Write a numpy array as a WAV file
Parameters
----------
filename : string or open file handle
Output wav file
rate : int
The sample rate (in samples/sec).
data : ndarray
A 1-D or 2-D numpy array of either integer or float data-type.
Notes
-----
* The file can be an open file or a filename.
* Writes a simple uncompressed WAV file.
* The bits-per-sample will be determined by the data-type.
* To write multiple-channels, use a 2-D array of shape
(Nsamples, Nchannels).
"""
if hasattr(filename, 'write'):
fid = filename
else:
fid = open(filename, 'wb')
try:
dkind = data.dtype.kind
if not (dkind == 'i' or dkind == 'f' or (dkind == 'u' and
data.dtype.itemsize == 1)):
raise ValueError("Unsupported data type '%s'" % data.dtype)
fid.write(b'RIFF')
fid.write(b'\x00\x00\x00\x00')
fid.write(b'WAVE')
# fmt chunk
fid.write(b'fmt ')
if dkind == 'f':
comp = 3
else:
comp = 1
if data.ndim == 1:
noc = 1
else:
noc = data.shape[1]
bits = data.dtype.itemsize * 8
sbytes = rate * (bits // 8) * noc
ba = noc * (bits // 8)
fid.write(struct.pack('<ihHIIHH', 16, comp, noc, rate, sbytes,
ba, bits))
# data chunk
fid.write(b'data')
fid.write(struct.pack('<i', data.nbytes))
if data.dtype.byteorder == '>' or (data.dtype.byteorder == '=' and
sys.byteorder == 'big'):
data = data.byteswap()
_array_tofile(fid, data)
# Determine file size and place it in correct
# position at start of the file.
size = fid.tell()
fid.seek(4)
fid.write(struct.pack('<i', size - 8))
finally:
if not hasattr(filename, 'write'):
fid.close()
else:
fid.seek(0) | [
"def",
"write",
"(",
"filename",
",",
"rate",
",",
"data",
")",
":",
"if",
"hasattr",
"(",
"filename",
",",
"'write'",
")",
":",
"fid",
"=",
"filename",
"else",
":",
"fid",
"=",
"open",
"(",
"filename",
",",
"'wb'",
")",
"try",
":",
"dkind",
"=",
... | Write a numpy array as a WAV file
Parameters
----------
filename : string or open file handle
Output wav file
rate : int
The sample rate (in samples/sec).
data : ndarray
A 1-D or 2-D numpy array of either integer or float data-type.
Notes
-----
* The file can be an open file or a filename.
* Writes a simple uncompressed WAV file.
* The bits-per-sample will be determined by the data-type.
* To write multiple-channels, use a 2-D array of shape
(Nsamples, Nchannels). | [
"Write",
"a",
"numpy",
"array",
"as",
"a",
"WAV",
"file"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/wavfile.py#L200-L270 | train | 227,116 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_print | def safe_print(msg):
"""
Safely print a given Unicode string to stdout,
possibly replacing characters non-printable
in the current stdout encoding.
:param string msg: the message
"""
try:
print(msg)
except UnicodeEncodeError:
try:
# NOTE encoding and decoding so that in Python 3 no b"..." is printed
encoded = msg.encode(sys.stdout.encoding, "replace")
decoded = encoded.decode(sys.stdout.encoding, "replace")
print(decoded)
except (UnicodeDecodeError, UnicodeEncodeError):
print(u"[ERRO] An unexpected error happened while printing to stdout.")
print(u"[ERRO] Please check that your file/string encoding matches the shell encoding.")
print(u"[ERRO] If possible, set your shell encoding to UTF-8 and convert any files with legacy encodings.") | python | def safe_print(msg):
"""
Safely print a given Unicode string to stdout,
possibly replacing characters non-printable
in the current stdout encoding.
:param string msg: the message
"""
try:
print(msg)
except UnicodeEncodeError:
try:
# NOTE encoding and decoding so that in Python 3 no b"..." is printed
encoded = msg.encode(sys.stdout.encoding, "replace")
decoded = encoded.decode(sys.stdout.encoding, "replace")
print(decoded)
except (UnicodeDecodeError, UnicodeEncodeError):
print(u"[ERRO] An unexpected error happened while printing to stdout.")
print(u"[ERRO] Please check that your file/string encoding matches the shell encoding.")
print(u"[ERRO] If possible, set your shell encoding to UTF-8 and convert any files with legacy encodings.") | [
"def",
"safe_print",
"(",
"msg",
")",
":",
"try",
":",
"print",
"(",
"msg",
")",
"except",
"UnicodeEncodeError",
":",
"try",
":",
"# NOTE encoding and decoding so that in Python 3 no b\"...\" is printed",
"encoded",
"=",
"msg",
".",
"encode",
"(",
"sys",
".",
"std... | Safely print a given Unicode string to stdout,
possibly replacing characters non-printable
in the current stdout encoding.
:param string msg: the message | [
"Safely",
"print",
"a",
"given",
"Unicode",
"string",
"to",
"stdout",
"possibly",
"replacing",
"characters",
"non",
"-",
"printable",
"in",
"the",
"current",
"stdout",
"encoding",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L65-L84 | train | 227,117 |
readbeyond/aeneas | aeneas/globalfunctions.py | print_error | def print_error(msg, color=True):
"""
Print an error message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END))
else:
safe_print(u"[ERRO] %s" % (msg)) | python | def print_error(msg, color=True):
"""
Print an error message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[ERRO] %s%s" % (ANSI_ERROR, msg, ANSI_END))
else:
safe_print(u"[ERRO] %s" % (msg)) | [
"def",
"print_error",
"(",
"msg",
",",
"color",
"=",
"True",
")",
":",
"if",
"color",
"and",
"is_posix",
"(",
")",
":",
"safe_print",
"(",
"u\"%s[ERRO] %s%s\"",
"%",
"(",
"ANSI_ERROR",
",",
"msg",
",",
"ANSI_END",
")",
")",
"else",
":",
"safe_print",
"... | Print an error message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | [
"Print",
"an",
"error",
"message",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L87-L97 | train | 227,118 |
readbeyond/aeneas | aeneas/globalfunctions.py | print_success | def print_success(msg, color=True):
"""
Print a success message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END))
else:
safe_print(u"[INFO] %s" % (msg)) | python | def print_success(msg, color=True):
"""
Print a success message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[INFO] %s%s" % (ANSI_OK, msg, ANSI_END))
else:
safe_print(u"[INFO] %s" % (msg)) | [
"def",
"print_success",
"(",
"msg",
",",
"color",
"=",
"True",
")",
":",
"if",
"color",
"and",
"is_posix",
"(",
")",
":",
"safe_print",
"(",
"u\"%s[INFO] %s%s\"",
"%",
"(",
"ANSI_OK",
",",
"msg",
",",
"ANSI_END",
")",
")",
"else",
":",
"safe_print",
"(... | Print a success message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | [
"Print",
"a",
"success",
"message",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L110-L120 | train | 227,119 |
readbeyond/aeneas | aeneas/globalfunctions.py | print_warning | def print_warning(msg, color=True):
"""
Print a warning message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[WARN] %s%s" % (ANSI_WARNING, msg, ANSI_END))
else:
safe_print(u"[WARN] %s" % (msg)) | python | def print_warning(msg, color=True):
"""
Print a warning message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color
"""
if color and is_posix():
safe_print(u"%s[WARN] %s%s" % (ANSI_WARNING, msg, ANSI_END))
else:
safe_print(u"[WARN] %s" % (msg)) | [
"def",
"print_warning",
"(",
"msg",
",",
"color",
"=",
"True",
")",
":",
"if",
"color",
"and",
"is_posix",
"(",
")",
":",
"safe_print",
"(",
"u\"%s[WARN] %s%s\"",
"%",
"(",
"ANSI_WARNING",
",",
"msg",
",",
"ANSI_END",
")",
")",
"else",
":",
"safe_print",... | Print a warning message.
:param string msg: the message
:param bool color: if ``True``, print with POSIX color | [
"Print",
"a",
"warning",
"message",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L123-L133 | train | 227,120 |
readbeyond/aeneas | aeneas/globalfunctions.py | file_extension | def file_extension(path):
"""
Return the file extension.
Examples: ::
/foo/bar.baz => baz
None => None
:param string path: the file path
:rtype: string
"""
if path is None:
return None
ext = os.path.splitext(os.path.basename(path))[1]
if ext.startswith("."):
ext = ext[1:]
return ext | python | def file_extension(path):
"""
Return the file extension.
Examples: ::
/foo/bar.baz => baz
None => None
:param string path: the file path
:rtype: string
"""
if path is None:
return None
ext = os.path.splitext(os.path.basename(path))[1]
if ext.startswith("."):
ext = ext[1:]
return ext | [
"def",
"file_extension",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"1",
"]",
"if",
"ext",
".",
... | Return the file extension.
Examples: ::
/foo/bar.baz => baz
None => None
:param string path: the file path
:rtype: string | [
"Return",
"the",
"file",
"extension",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L196-L213 | train | 227,121 |
readbeyond/aeneas | aeneas/globalfunctions.py | mimetype_from_path | def mimetype_from_path(path):
"""
Return a mimetype from the file extension.
:param string path: the file path
:rtype: string
"""
extension = file_extension(path)
if extension is not None:
extension = extension.lower()
if extension in gc.MIMETYPE_MAP:
return gc.MIMETYPE_MAP[extension]
return None | python | def mimetype_from_path(path):
"""
Return a mimetype from the file extension.
:param string path: the file path
:rtype: string
"""
extension = file_extension(path)
if extension is not None:
extension = extension.lower()
if extension in gc.MIMETYPE_MAP:
return gc.MIMETYPE_MAP[extension]
return None | [
"def",
"mimetype_from_path",
"(",
"path",
")",
":",
"extension",
"=",
"file_extension",
"(",
"path",
")",
"if",
"extension",
"is",
"not",
"None",
":",
"extension",
"=",
"extension",
".",
"lower",
"(",
")",
"if",
"extension",
"in",
"gc",
".",
"MIMETYPE_MAP"... | Return a mimetype from the file extension.
:param string path: the file path
:rtype: string | [
"Return",
"a",
"mimetype",
"from",
"the",
"file",
"extension",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L216-L228 | train | 227,122 |
readbeyond/aeneas | aeneas/globalfunctions.py | file_name_without_extension | def file_name_without_extension(path):
"""
Return the file name without extension.
Examples: ::
/foo/bar.baz => bar
/foo/bar => bar
None => None
:param string path: the file path
:rtype: string
"""
if path is None:
return None
return os.path.splitext(os.path.basename(path))[0] | python | def file_name_without_extension(path):
"""
Return the file name without extension.
Examples: ::
/foo/bar.baz => bar
/foo/bar => bar
None => None
:param string path: the file path
:rtype: string
"""
if path is None:
return None
return os.path.splitext(os.path.basename(path))[0] | [
"def",
"file_name_without_extension",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"return",
"os",
".",
"path",
".",
"splitext",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
")",
"[",
"0",
"]"
] | Return the file name without extension.
Examples: ::
/foo/bar.baz => bar
/foo/bar => bar
None => None
:param string path: the file path
:rtype: string | [
"Return",
"the",
"file",
"name",
"without",
"extension",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L231-L246 | train | 227,123 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_float | def safe_float(string, default=None):
"""
Safely parse a string into a float.
On error return the ``default`` value.
:param string string: string value to be converted
:param float default: default value to be used in case of failure
:rtype: float
"""
value = default
try:
value = float(string)
except TypeError:
pass
except ValueError:
pass
return value | python | def safe_float(string, default=None):
"""
Safely parse a string into a float.
On error return the ``default`` value.
:param string string: string value to be converted
:param float default: default value to be used in case of failure
:rtype: float
"""
value = default
try:
value = float(string)
except TypeError:
pass
except ValueError:
pass
return value | [
"def",
"safe_float",
"(",
"string",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"default",
"try",
":",
"value",
"=",
"float",
"(",
"string",
")",
"except",
"TypeError",
":",
"pass",
"except",
"ValueError",
":",
"pass",
"return",
"value"
] | Safely parse a string into a float.
On error return the ``default`` value.
:param string string: string value to be converted
:param float default: default value to be used in case of failure
:rtype: float | [
"Safely",
"parse",
"a",
"string",
"into",
"a",
"float",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L272-L289 | train | 227,124 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_int | def safe_int(string, default=None):
"""
Safely parse a string into an int.
On error return the ``default`` value.
:param string string: string value to be converted
:param int default: default value to be used in case of failure
:rtype: int
"""
value = safe_float(string, default)
if value is not None:
value = int(value)
return value | python | def safe_int(string, default=None):
"""
Safely parse a string into an int.
On error return the ``default`` value.
:param string string: string value to be converted
:param int default: default value to be used in case of failure
:rtype: int
"""
value = safe_float(string, default)
if value is not None:
value = int(value)
return value | [
"def",
"safe_int",
"(",
"string",
",",
"default",
"=",
"None",
")",
":",
"value",
"=",
"safe_float",
"(",
"string",
",",
"default",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"int",
"(",
"value",
")",
"return",
"value"
] | Safely parse a string into an int.
On error return the ``default`` value.
:param string string: string value to be converted
:param int default: default value to be used in case of failure
:rtype: int | [
"Safely",
"parse",
"a",
"string",
"into",
"an",
"int",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L292-L305 | train | 227,125 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_get | def safe_get(dictionary, key, default_value, can_return_none=True):
"""
Safely perform a dictionary get,
returning the default value if the key is not found.
:param dict dictionary: the dictionary
:param string key: the key
:param variant default_value: the default value to be returned
:param bool can_return_none: if ``True``, the function can return ``None``;
otherwise, return ``default_value`` even if the
dictionary lookup succeeded
:rtype: variant
"""
return_value = default_value
try:
return_value = dictionary[key]
if (return_value is None) and (not can_return_none):
return_value = default_value
except (KeyError, TypeError):
# KeyError if key is not present in dictionary
# TypeError if dictionary is None
pass
return return_value | python | def safe_get(dictionary, key, default_value, can_return_none=True):
"""
Safely perform a dictionary get,
returning the default value if the key is not found.
:param dict dictionary: the dictionary
:param string key: the key
:param variant default_value: the default value to be returned
:param bool can_return_none: if ``True``, the function can return ``None``;
otherwise, return ``default_value`` even if the
dictionary lookup succeeded
:rtype: variant
"""
return_value = default_value
try:
return_value = dictionary[key]
if (return_value is None) and (not can_return_none):
return_value = default_value
except (KeyError, TypeError):
# KeyError if key is not present in dictionary
# TypeError if dictionary is None
pass
return return_value | [
"def",
"safe_get",
"(",
"dictionary",
",",
"key",
",",
"default_value",
",",
"can_return_none",
"=",
"True",
")",
":",
"return_value",
"=",
"default_value",
"try",
":",
"return_value",
"=",
"dictionary",
"[",
"key",
"]",
"if",
"(",
"return_value",
"is",
"Non... | Safely perform a dictionary get,
returning the default value if the key is not found.
:param dict dictionary: the dictionary
:param string key: the key
:param variant default_value: the default value to be returned
:param bool can_return_none: if ``True``, the function can return ``None``;
otherwise, return ``default_value`` even if the
dictionary lookup succeeded
:rtype: variant | [
"Safely",
"perform",
"a",
"dictionary",
"get",
"returning",
"the",
"default",
"value",
"if",
"the",
"key",
"is",
"not",
"found",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L308-L330 | train | 227,126 |
readbeyond/aeneas | aeneas/globalfunctions.py | norm_join | def norm_join(prefix, suffix):
"""
Join ``prefix`` and ``suffix`` paths
and return the resulting path, normalized.
:param string prefix: the prefix path
:param string suffix: the suffix path
:rtype: string
"""
if (prefix is None) and (suffix is None):
return "."
if prefix is None:
return os.path.normpath(suffix)
if suffix is None:
return os.path.normpath(prefix)
return os.path.normpath(os.path.join(prefix, suffix)) | python | def norm_join(prefix, suffix):
"""
Join ``prefix`` and ``suffix`` paths
and return the resulting path, normalized.
:param string prefix: the prefix path
:param string suffix: the suffix path
:rtype: string
"""
if (prefix is None) and (suffix is None):
return "."
if prefix is None:
return os.path.normpath(suffix)
if suffix is None:
return os.path.normpath(prefix)
return os.path.normpath(os.path.join(prefix, suffix)) | [
"def",
"norm_join",
"(",
"prefix",
",",
"suffix",
")",
":",
"if",
"(",
"prefix",
"is",
"None",
")",
"and",
"(",
"suffix",
"is",
"None",
")",
":",
"return",
"\".\"",
"if",
"prefix",
"is",
"None",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(... | Join ``prefix`` and ``suffix`` paths
and return the resulting path, normalized.
:param string prefix: the prefix path
:param string suffix: the suffix path
:rtype: string | [
"Join",
"prefix",
"and",
"suffix",
"paths",
"and",
"return",
"the",
"resulting",
"path",
"normalized",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L333-L348 | train | 227,127 |
readbeyond/aeneas | aeneas/globalfunctions.py | copytree | def copytree(source_directory, destination_directory, ignore=None):
"""
Recursively copy the contents of a source directory
into a destination directory.
Both directories must exist.
This function does not copy the root directory ``source_directory``
into ``destination_directory``.
Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist,
we cannot use for our purposes.
Code adapted from http://stackoverflow.com/a/12686557
:param string source_directory: the source directory, already existing
:param string destination_directory: the destination directory, already existing
"""
if os.path.isdir(source_directory):
if not os.path.isdir(destination_directory):
os.makedirs(destination_directory)
files = os.listdir(source_directory)
if ignore is not None:
ignored = ignore(source_directory, files)
else:
ignored = set()
for f in files:
if f not in ignored:
copytree(
os.path.join(source_directory, f),
os.path.join(destination_directory, f),
ignore
)
else:
shutil.copyfile(source_directory, destination_directory) | python | def copytree(source_directory, destination_directory, ignore=None):
"""
Recursively copy the contents of a source directory
into a destination directory.
Both directories must exist.
This function does not copy the root directory ``source_directory``
into ``destination_directory``.
Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist,
we cannot use for our purposes.
Code adapted from http://stackoverflow.com/a/12686557
:param string source_directory: the source directory, already existing
:param string destination_directory: the destination directory, already existing
"""
if os.path.isdir(source_directory):
if not os.path.isdir(destination_directory):
os.makedirs(destination_directory)
files = os.listdir(source_directory)
if ignore is not None:
ignored = ignore(source_directory, files)
else:
ignored = set()
for f in files:
if f not in ignored:
copytree(
os.path.join(source_directory, f),
os.path.join(destination_directory, f),
ignore
)
else:
shutil.copyfile(source_directory, destination_directory) | [
"def",
"copytree",
"(",
"source_directory",
",",
"destination_directory",
",",
"ignore",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"source_directory",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"destination_direct... | Recursively copy the contents of a source directory
into a destination directory.
Both directories must exist.
This function does not copy the root directory ``source_directory``
into ``destination_directory``.
Since ``shutil.copytree(src, dst)`` requires ``dst`` not to exist,
we cannot use for our purposes.
Code adapted from http://stackoverflow.com/a/12686557
:param string source_directory: the source directory, already existing
:param string destination_directory: the destination directory, already existing | [
"Recursively",
"copy",
"the",
"contents",
"of",
"a",
"source",
"directory",
"into",
"a",
"destination",
"directory",
".",
"Both",
"directories",
"must",
"exist",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L501-L534 | train | 227,128 |
readbeyond/aeneas | aeneas/globalfunctions.py | ensure_parent_directory | def ensure_parent_directory(path, ensure_parent=True):
"""
Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raises: OSError: if the path cannot be created
"""
parent_directory = os.path.abspath(path)
if ensure_parent:
parent_directory = os.path.dirname(parent_directory)
if not os.path.exists(parent_directory):
try:
os.makedirs(parent_directory)
except (IOError, OSError):
raise OSError(u"Directory '%s' cannot be created" % parent_directory) | python | def ensure_parent_directory(path, ensure_parent=True):
"""
Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raises: OSError: if the path cannot be created
"""
parent_directory = os.path.abspath(path)
if ensure_parent:
parent_directory = os.path.dirname(parent_directory)
if not os.path.exists(parent_directory):
try:
os.makedirs(parent_directory)
except (IOError, OSError):
raise OSError(u"Directory '%s' cannot be created" % parent_directory) | [
"def",
"ensure_parent_directory",
"(",
"path",
",",
"ensure_parent",
"=",
"True",
")",
":",
"parent_directory",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"ensure_parent",
":",
"parent_directory",
"=",
"os",
".",
"path",
".",
"dirname",
... | Ensures the parent directory exists.
:param string path: the path of the file
:param bool ensure_parent: if ``True``, ensure the parent directory of ``path`` exists;
if ``False``, ensure ``path`` exists
:raises: OSError: if the path cannot be created | [
"Ensures",
"the",
"parent",
"directory",
"exists",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L537-L553 | train | 227,129 |
readbeyond/aeneas | aeneas/globalfunctions.py | can_run_c_extension | def can_run_c_extension(name=None):
"""
Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param string name: the name of the Python C extension to test
:rtype: bool
"""
def can_run_cdtw():
""" Python C extension for computing DTW """
try:
import aeneas.cdtw.cdtw
return True
except ImportError:
return False
def can_run_cmfcc():
""" Python C extension for computing MFCC """
try:
import aeneas.cmfcc.cmfcc
return True
except ImportError:
return False
def can_run_cew():
""" Python C extension for synthesizing with eSpeak """
try:
import aeneas.cew.cew
return True
except ImportError:
return False
def can_run_cfw():
""" Python C extension for synthesizing with Festival """
try:
import aeneas.cfw.cfw
return True
except ImportError:
return False
if name == "cdtw":
return can_run_cdtw()
elif name == "cmfcc":
return can_run_cmfcc()
elif name == "cew":
return can_run_cew()
elif name == "cfw":
return can_run_cfw()
else:
# NOTE cfw is still experimental!
return can_run_cdtw() and can_run_cmfcc() and can_run_cew() | python | def can_run_c_extension(name=None):
"""
Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param string name: the name of the Python C extension to test
:rtype: bool
"""
def can_run_cdtw():
""" Python C extension for computing DTW """
try:
import aeneas.cdtw.cdtw
return True
except ImportError:
return False
def can_run_cmfcc():
""" Python C extension for computing MFCC """
try:
import aeneas.cmfcc.cmfcc
return True
except ImportError:
return False
def can_run_cew():
""" Python C extension for synthesizing with eSpeak """
try:
import aeneas.cew.cew
return True
except ImportError:
return False
def can_run_cfw():
""" Python C extension for synthesizing with Festival """
try:
import aeneas.cfw.cfw
return True
except ImportError:
return False
if name == "cdtw":
return can_run_cdtw()
elif name == "cmfcc":
return can_run_cmfcc()
elif name == "cew":
return can_run_cew()
elif name == "cfw":
return can_run_cfw()
else:
# NOTE cfw is still experimental!
return can_run_cdtw() and can_run_cmfcc() and can_run_cew() | [
"def",
"can_run_c_extension",
"(",
"name",
"=",
"None",
")",
":",
"def",
"can_run_cdtw",
"(",
")",
":",
"\"\"\" Python C extension for computing DTW \"\"\"",
"try",
":",
"import",
"aeneas",
".",
"cdtw",
".",
"cdtw",
"return",
"True",
"except",
"ImportError",
":",
... | Determine whether the given Python C extension loads correctly.
If ``name`` is ``None``, tests all Python C extensions,
and return ``True`` if and only if all load correctly.
:param string name: the name of the Python C extension to test
:rtype: bool | [
"Determine",
"whether",
"the",
"given",
"Python",
"C",
"extension",
"loads",
"correctly",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L805-L857 | train | 227,130 |
readbeyond/aeneas | aeneas/globalfunctions.py | run_c_extension_with_fallback | def run_c_extension_with_fallback(
log_function,
extension,
c_function,
py_function,
args,
rconf
):
"""
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0
"""
computed = False
if not rconf[u"c_extensions"]:
log_function(u"C extensions disabled")
elif extension not in rconf:
log_function([u"C extension '%s' not recognized", extension])
elif not rconf[extension]:
log_function([u"C extension '%s' disabled", extension])
else:
log_function([u"C extension '%s' enabled", extension])
if c_function is None:
log_function(u"C function is None")
elif can_run_c_extension(extension):
log_function([u"C extension '%s' enabled and it can be loaded", extension])
computed, result = c_function(*args)
else:
log_function([u"C extension '%s' enabled but it cannot be loaded", extension])
if not computed:
if py_function is None:
log_function(u"Python function is None")
else:
log_function(u"Running the pure Python code")
computed, result = py_function(*args)
if not computed:
raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)")
return result | python | def run_c_extension_with_fallback(
log_function,
extension,
c_function,
py_function,
args,
rconf
):
"""
Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0
"""
computed = False
if not rconf[u"c_extensions"]:
log_function(u"C extensions disabled")
elif extension not in rconf:
log_function([u"C extension '%s' not recognized", extension])
elif not rconf[extension]:
log_function([u"C extension '%s' disabled", extension])
else:
log_function([u"C extension '%s' enabled", extension])
if c_function is None:
log_function(u"C function is None")
elif can_run_c_extension(extension):
log_function([u"C extension '%s' enabled and it can be loaded", extension])
computed, result = c_function(*args)
else:
log_function([u"C extension '%s' enabled but it cannot be loaded", extension])
if not computed:
if py_function is None:
log_function(u"Python function is None")
else:
log_function(u"Running the pure Python code")
computed, result = py_function(*args)
if not computed:
raise RuntimeError(u"Both the C extension and the pure Python code failed. (Wrong arguments? Input too big?)")
return result | [
"def",
"run_c_extension_with_fallback",
"(",
"log_function",
",",
"extension",
",",
"c_function",
",",
"py_function",
",",
"args",
",",
"rconf",
")",
":",
"computed",
"=",
"False",
"if",
"not",
"rconf",
"[",
"u\"c_extensions\"",
"]",
":",
"log_function",
"(",
... | Run a function calling a C extension, falling back
to a pure Python function if the former does not succeed.
:param function log_function: a logger function
:param string extension: the name of the extension
:param function c_function: the (Python) function calling the C extension
:param function py_function: the (Python) function providing the fallback
:param rconf: the runtime configuration
:type rconf: :class:`aeneas.runtimeconfiguration.RuntimeConfiguration`
:rtype: depends on the extension being called
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
.. versionadded:: 1.4.0 | [
"Run",
"a",
"function",
"calling",
"a",
"C",
"extension",
"falling",
"back",
"to",
"a",
"pure",
"Python",
"function",
"if",
"the",
"former",
"does",
"not",
"succeed",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L860-L908 | train | 227,131 |
readbeyond/aeneas | aeneas/globalfunctions.py | file_can_be_read | def file_can_be_read(path):
"""
Return ``True`` if the file at the given ``path`` can be read.
:param string path: the file path
:rtype: bool
.. versionadded:: 1.4.0
"""
if path is None:
return False
try:
with io.open(path, "rb") as test_file:
pass
return True
except (IOError, OSError):
pass
return False | python | def file_can_be_read(path):
"""
Return ``True`` if the file at the given ``path`` can be read.
:param string path: the file path
:rtype: bool
.. versionadded:: 1.4.0
"""
if path is None:
return False
try:
with io.open(path, "rb") as test_file:
pass
return True
except (IOError, OSError):
pass
return False | [
"def",
"file_can_be_read",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"False",
"try",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"test_file",
":",
"pass",
"return",
"True",
"except",
"(",
"IOError",
... | Return ``True`` if the file at the given ``path`` can be read.
:param string path: the file path
:rtype: bool
.. versionadded:: 1.4.0 | [
"Return",
"True",
"if",
"the",
"file",
"at",
"the",
"given",
"path",
"can",
"be",
"read",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L911-L928 | train | 227,132 |
readbeyond/aeneas | aeneas/globalfunctions.py | file_can_be_written | def file_can_be_written(path):
"""
Return ``True`` if a file can be written at the given ``path``.
:param string path: the file path
:rtype: bool
.. warning:: This function will attempt to open the given ``path``
in write mode, possibly destroying the file previously existing there.
.. versionadded:: 1.4.0
"""
if path is None:
return False
try:
with io.open(path, "wb") as test_file:
pass
delete_file(None, path)
return True
except (IOError, OSError):
pass
return False | python | def file_can_be_written(path):
"""
Return ``True`` if a file can be written at the given ``path``.
:param string path: the file path
:rtype: bool
.. warning:: This function will attempt to open the given ``path``
in write mode, possibly destroying the file previously existing there.
.. versionadded:: 1.4.0
"""
if path is None:
return False
try:
with io.open(path, "wb") as test_file:
pass
delete_file(None, path)
return True
except (IOError, OSError):
pass
return False | [
"def",
"file_can_be_written",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"False",
"try",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"\"wb\"",
")",
"as",
"test_file",
":",
"pass",
"delete_file",
"(",
"None",
",",
"path",
... | Return ``True`` if a file can be written at the given ``path``.
:param string path: the file path
:rtype: bool
.. warning:: This function will attempt to open the given ``path``
in write mode, possibly destroying the file previously existing there.
.. versionadded:: 1.4.0 | [
"Return",
"True",
"if",
"a",
"file",
"can",
"be",
"written",
"at",
"the",
"given",
"path",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L931-L952 | train | 227,133 |
readbeyond/aeneas | aeneas/globalfunctions.py | read_file_bytes | def read_file_bytes(input_file_path):
"""
Read the file at the given file path
and return its contents as a byte string,
or ``None`` if an error occurred.
:param string input_file_path: the file path
:rtype: bytes
"""
contents = None
try:
with io.open(input_file_path, "rb") as input_file:
contents = input_file.read()
except:
pass
return contents | python | def read_file_bytes(input_file_path):
"""
Read the file at the given file path
and return its contents as a byte string,
or ``None`` if an error occurred.
:param string input_file_path: the file path
:rtype: bytes
"""
contents = None
try:
with io.open(input_file_path, "rb") as input_file:
contents = input_file.read()
except:
pass
return contents | [
"def",
"read_file_bytes",
"(",
"input_file_path",
")",
":",
"contents",
"=",
"None",
"try",
":",
"with",
"io",
".",
"open",
"(",
"input_file_path",
",",
"\"rb\"",
")",
"as",
"input_file",
":",
"contents",
"=",
"input_file",
".",
"read",
"(",
")",
"except",... | Read the file at the given file path
and return its contents as a byte string,
or ``None`` if an error occurred.
:param string input_file_path: the file path
:rtype: bytes | [
"Read",
"the",
"file",
"at",
"the",
"given",
"file",
"path",
"and",
"return",
"its",
"contents",
"as",
"a",
"byte",
"string",
"or",
"None",
"if",
"an",
"error",
"occurred",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1101-L1116 | train | 227,134 |
readbeyond/aeneas | aeneas/globalfunctions.py | human_readable_number | def human_readable_number(number, suffix=""):
"""
Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(number) < 1024.0:
return "%3.1f%s%s" % (number, unit, suffix)
number /= 1024.0
return "%.1f%s%s" % (number, "Y", suffix) | python | def human_readable_number(number, suffix=""):
"""
Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string
"""
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(number) < 1024.0:
return "%3.1f%s%s" % (number, unit, suffix)
number /= 1024.0
return "%.1f%s%s" % (number, "Y", suffix) | [
"def",
"human_readable_number",
"(",
"number",
",",
"suffix",
"=",
"\"\"",
")",
":",
"for",
"unit",
"in",
"[",
"\"\"",
",",
"\"K\"",
",",
"\"M\"",
",",
"\"G\"",
",",
"\"T\"",
",",
"\"P\"",
",",
"\"E\"",
",",
"\"Z\"",
"]",
":",
"if",
"abs",
"(",
"nu... | Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string | [
"Format",
"the",
"given",
"number",
"into",
"a",
"human",
"-",
"readable",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1119-L1133 | train | 227,135 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_unichr | def safe_unichr(codepoint):
"""
Safely return a Unicode string of length one,
containing the Unicode character with given codepoint.
:param int codepoint: the codepoint
:rtype: string
"""
if is_py2_narrow_build():
return ("\\U%08x" % codepoint).decode("unicode-escape")
elif PY2:
return unichr(codepoint)
return chr(codepoint) | python | def safe_unichr(codepoint):
"""
Safely return a Unicode string of length one,
containing the Unicode character with given codepoint.
:param int codepoint: the codepoint
:rtype: string
"""
if is_py2_narrow_build():
return ("\\U%08x" % codepoint).decode("unicode-escape")
elif PY2:
return unichr(codepoint)
return chr(codepoint) | [
"def",
"safe_unichr",
"(",
"codepoint",
")",
":",
"if",
"is_py2_narrow_build",
"(",
")",
":",
"return",
"(",
"\"\\\\U%08x\"",
"%",
"codepoint",
")",
".",
"decode",
"(",
"\"unicode-escape\"",
")",
"elif",
"PY2",
":",
"return",
"unichr",
"(",
"codepoint",
")",... | Safely return a Unicode string of length one,
containing the Unicode character with given codepoint.
:param int codepoint: the codepoint
:rtype: string | [
"Safely",
"return",
"a",
"Unicode",
"string",
"of",
"length",
"one",
"containing",
"the",
"Unicode",
"character",
"with",
"given",
"codepoint",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1192-L1204 | train | 227,136 |
readbeyond/aeneas | aeneas/globalfunctions.py | safe_unicode_stdin | def safe_unicode_stdin(string):
"""
Safely convert the given string to a Unicode string,
decoding using ``sys.stdin.encoding`` if needed.
If running from a frozen binary, ``utf-8`` encoding is assumed.
:param variant string: the byte string or Unicode string to convert
:rtype: string
"""
if string is None:
return None
if is_bytes(string):
if FROZEN:
return string.decode("utf-8")
try:
return string.decode(sys.stdin.encoding)
except UnicodeDecodeError:
return string.decode(sys.stdin.encoding, "replace")
except:
return string.decode("utf-8")
return string | python | def safe_unicode_stdin(string):
"""
Safely convert the given string to a Unicode string,
decoding using ``sys.stdin.encoding`` if needed.
If running from a frozen binary, ``utf-8`` encoding is assumed.
:param variant string: the byte string or Unicode string to convert
:rtype: string
"""
if string is None:
return None
if is_bytes(string):
if FROZEN:
return string.decode("utf-8")
try:
return string.decode(sys.stdin.encoding)
except UnicodeDecodeError:
return string.decode(sys.stdin.encoding, "replace")
except:
return string.decode("utf-8")
return string | [
"def",
"safe_unicode_stdin",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"None",
"if",
"is_bytes",
"(",
"string",
")",
":",
"if",
"FROZEN",
":",
"return",
"string",
".",
"decode",
"(",
"\"utf-8\"",
")",
"try",
":",
"return",
"... | Safely convert the given string to a Unicode string,
decoding using ``sys.stdin.encoding`` if needed.
If running from a frozen binary, ``utf-8`` encoding is assumed.
:param variant string: the byte string or Unicode string to convert
:rtype: string | [
"Safely",
"convert",
"the",
"given",
"string",
"to",
"a",
"Unicode",
"string",
"decoding",
"using",
"sys",
".",
"stdin",
".",
"encoding",
"if",
"needed",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/globalfunctions.py#L1235-L1256 | train | 227,137 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | TTSCache.get | def get(self, fragment_info):
"""
Get the value associated with the given key.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:raises: KeyError if the key is not present in the cache
"""
if not self.is_cached(fragment_info):
raise KeyError(u"Attempt to get text not cached")
return self.cache[fragment_info] | python | def get(self, fragment_info):
"""
Get the value associated with the given key.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:raises: KeyError if the key is not present in the cache
"""
if not self.is_cached(fragment_info):
raise KeyError(u"Attempt to get text not cached")
return self.cache[fragment_info] | [
"def",
"get",
"(",
"self",
",",
"fragment_info",
")",
":",
"if",
"not",
"self",
".",
"is_cached",
"(",
"fragment_info",
")",
":",
"raise",
"KeyError",
"(",
"u\"Attempt to get text not cached\"",
")",
"return",
"self",
".",
"cache",
"[",
"fragment_info",
"]"
] | Get the value associated with the given key.
:param fragment_info: the text key
:type fragment_info: tuple of str ``(language, text)``
:raises: KeyError if the key is not present in the cache | [
"Get",
"the",
"value",
"associated",
"with",
"the",
"given",
"key",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L116-L126 | train | 227,138 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | TTSCache.clear | def clear(self):
"""
Clear the cache and remove all the files from disk.
"""
self.log(u"Clearing cache...")
for file_handler, file_info in self.cache.values():
self.log([u" Removing file '%s'", file_info])
gf.delete_file(file_handler, file_info)
self._initialize_cache()
self.log(u"Clearing cache... done") | python | def clear(self):
"""
Clear the cache and remove all the files from disk.
"""
self.log(u"Clearing cache...")
for file_handler, file_info in self.cache.values():
self.log([u" Removing file '%s'", file_info])
gf.delete_file(file_handler, file_info)
self._initialize_cache()
self.log(u"Clearing cache... done") | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Clearing cache...\"",
")",
"for",
"file_handler",
",",
"file_info",
"in",
"self",
".",
"cache",
".",
"values",
"(",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\" Removing file '%s'\"",
"... | Clear the cache and remove all the files from disk. | [
"Clear",
"the",
"cache",
"and",
"remove",
"all",
"the",
"files",
"from",
"disk",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L128-L137 | train | 227,139 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._language_to_voice_code | def _language_to_voice_code(self, language):
"""
Translate a language value to a voice code.
If you want to mock support for a language
by using a voice for a similar language,
please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary.
:param language: the requested language
:type language: :class:`~aeneas.language.Language`
:rtype: string
"""
voice_code = self.rconf[RuntimeConfiguration.TTS_VOICE_CODE]
if voice_code is None:
try:
voice_code = self.LANGUAGE_TO_VOICE_CODE[language]
except KeyError as exc:
self.log_exc(u"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE" % (language), exc, False, None)
self.log_warn(u"Using the language code as the voice code")
voice_code = language
else:
self.log(u"TTS voice override in rconf")
self.log([u"Language to voice code: '%s' => '%s'", language, voice_code])
return voice_code | python | def _language_to_voice_code(self, language):
"""
Translate a language value to a voice code.
If you want to mock support for a language
by using a voice for a similar language,
please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary.
:param language: the requested language
:type language: :class:`~aeneas.language.Language`
:rtype: string
"""
voice_code = self.rconf[RuntimeConfiguration.TTS_VOICE_CODE]
if voice_code is None:
try:
voice_code = self.LANGUAGE_TO_VOICE_CODE[language]
except KeyError as exc:
self.log_exc(u"Language code '%s' not found in LANGUAGE_TO_VOICE_CODE" % (language), exc, False, None)
self.log_warn(u"Using the language code as the voice code")
voice_code = language
else:
self.log(u"TTS voice override in rconf")
self.log([u"Language to voice code: '%s' => '%s'", language, voice_code])
return voice_code | [
"def",
"_language_to_voice_code",
"(",
"self",
",",
"language",
")",
":",
"voice_code",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TTS_VOICE_CODE",
"]",
"if",
"voice_code",
"is",
"None",
":",
"try",
":",
"voice_code",
"=",
"self",
".",
"LA... | Translate a language value to a voice code.
If you want to mock support for a language
by using a voice for a similar language,
please add it to the ``LANGUAGE_TO_VOICE_CODE`` dictionary.
:param language: the requested language
:type language: :class:`~aeneas.language.Language`
:rtype: string | [
"Translate",
"a",
"language",
"value",
"to",
"a",
"voice",
"code",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L299-L322 | train | 227,140 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper.clear_cache | def clear_cache(self):
"""
Clear the TTS cache, removing all cache files from disk.
.. versionadded:: 1.6.0
"""
if self.use_cache:
self.log(u"Requested to clear TTS cache")
self.cache.clear() | python | def clear_cache(self):
"""
Clear the TTS cache, removing all cache files from disk.
.. versionadded:: 1.6.0
"""
if self.use_cache:
self.log(u"Requested to clear TTS cache")
self.cache.clear() | [
"def",
"clear_cache",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_cache",
":",
"self",
".",
"log",
"(",
"u\"Requested to clear TTS cache\"",
")",
"self",
".",
"cache",
".",
"clear",
"(",
")"
] | Clear the TTS cache, removing all cache files from disk.
.. versionadded:: 1.6.0 | [
"Clear",
"the",
"TTS",
"cache",
"removing",
"all",
"cache",
"files",
"from",
"disk",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L331-L339 | train | 227,141 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper.set_subprocess_arguments | def set_subprocess_arguments(self, subprocess_arguments):
"""
Set the list of arguments that the wrapper will pass to ``subprocess``.
Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced
by actual values in the ``_synthesize_multiple_subprocess()`` and
``_synthesize_single_subprocess()`` built-in functions.
Literal parameters will be passed unchanged.
The list should start with the path to the TTS engine.
This function should be called in the constructor
of concrete subclasses.
:param list subprocess_arguments: the list of arguments to be passed to
the TTS engine via subprocess
"""
# NOTE this is a method because we might need to access self.rconf,
# so we cannot specify the list of arguments as a class field
self.subprocess_arguments = subprocess_arguments
self.log([u"Subprocess arguments: %s", subprocess_arguments]) | python | def set_subprocess_arguments(self, subprocess_arguments):
"""
Set the list of arguments that the wrapper will pass to ``subprocess``.
Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced
by actual values in the ``_synthesize_multiple_subprocess()`` and
``_synthesize_single_subprocess()`` built-in functions.
Literal parameters will be passed unchanged.
The list should start with the path to the TTS engine.
This function should be called in the constructor
of concrete subclasses.
:param list subprocess_arguments: the list of arguments to be passed to
the TTS engine via subprocess
"""
# NOTE this is a method because we might need to access self.rconf,
# so we cannot specify the list of arguments as a class field
self.subprocess_arguments = subprocess_arguments
self.log([u"Subprocess arguments: %s", subprocess_arguments]) | [
"def",
"set_subprocess_arguments",
"(",
"self",
",",
"subprocess_arguments",
")",
":",
"# NOTE this is a method because we might need to access self.rconf,",
"# so we cannot specify the list of arguments as a class field",
"self",
".",
"subprocess_arguments",
"=",
"subprocess_argume... | Set the list of arguments that the wrapper will pass to ``subprocess``.
Placeholders ``CLI_PARAMETER_*`` can be used, and they will be replaced
by actual values in the ``_synthesize_multiple_subprocess()`` and
``_synthesize_single_subprocess()`` built-in functions.
Literal parameters will be passed unchanged.
The list should start with the path to the TTS engine.
This function should be called in the constructor
of concrete subclasses.
:param list subprocess_arguments: the list of arguments to be passed to
the TTS engine via subprocess | [
"Set",
"the",
"list",
"of",
"arguments",
"that",
"the",
"wrapper",
"will",
"pass",
"to",
"subprocess",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L341-L361 | train | 227,142 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper.synthesize_multiple | def synthesize_multiple(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize the text contained in the given fragment list
into a WAVE file.
Return a tuple (anchors, total_time, num_chars).
Concrete subclasses must implement at least one
of the following private functions:
1. ``_synthesize_multiple_python()``
2. ``_synthesize_multiple_c_extension()``
3. ``_synthesize_multiple_subprocess()``
:param text_file: the text file to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:param string output_file_path: the path to the output audio file
:param quit_after: stop synthesizing as soon as
reaching this many seconds
:type quit_after: :class:`~aeneas.exacttiming.TimeValue`
:param bool backwards: if > 0, synthesize from the end of the text file
:rtype: tuple (anchors, total_time, num_chars)
:raises: TypeError: if ``text_file`` is ``None`` or
one of the text fragments is not a Unicode string
:raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False``
and a fragment has a language code not supported by the TTS engine, or
if ``text_file`` has no fragments or all its fragments are empty
:raises: OSError: if output file cannot be written to ``output_file_path``
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
if text_file is None:
self.log_exc(u"text_file is None", None, True, TypeError)
if len(text_file) < 1:
self.log_exc(u"The text file has no fragments", None, True, ValueError)
if text_file.chars == 0:
self.log_exc(u"All fragments in the text file are empty", None, True, ValueError)
if not self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]:
for fragment in text_file.fragments:
if fragment.language not in self.LANGUAGE_TO_VOICE_CODE:
self.log_exc(u"Language '%s' is not supported by the selected TTS engine" % (fragment.language), None, True, ValueError)
for fragment in text_file.fragments:
for line in fragment.lines:
if not gf.is_unicode(line):
self.log_exc(u"The text file contain a line which is not a Unicode string", None, True, TypeError)
# log parameters
if quit_after is not None:
self.log([u"Quit after reaching %.3f", quit_after])
if backwards:
self.log(u"Synthesizing backwards")
# check that output_file_path can be written
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError)
# first, call Python function _synthesize_multiple_python() if available
if self.HAS_PYTHON_CALL:
self.log(u"Calling TTS engine via Python")
try:
computed, result = self._synthesize_multiple_python(text_file, output_file_path, quit_after, backwards)
if computed:
self.log(u"The _synthesize_multiple_python call was successful, returning anchors")
return result
else:
self.log(u"The _synthesize_multiple_python call failed")
except Exception as exc:
self.log_exc(u"An unexpected error occurred while calling _synthesize_multiple_python", exc, False, None)
# call _synthesize_multiple_c_extension() or _synthesize_multiple_subprocess()
self.log(u"Calling TTS engine via C extension or subprocess")
c_extension_function = self._synthesize_multiple_c_extension if self.HAS_C_EXTENSION_CALL else None
subprocess_function = self._synthesize_multiple_subprocess if self.HAS_SUBPROCESS_CALL else None
return gf.run_c_extension_with_fallback(
self.log,
self.C_EXTENSION_NAME,
c_extension_function,
subprocess_function,
(text_file, output_file_path, quit_after, backwards),
rconf=self.rconf
) | python | def synthesize_multiple(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize the text contained in the given fragment list
into a WAVE file.
Return a tuple (anchors, total_time, num_chars).
Concrete subclasses must implement at least one
of the following private functions:
1. ``_synthesize_multiple_python()``
2. ``_synthesize_multiple_c_extension()``
3. ``_synthesize_multiple_subprocess()``
:param text_file: the text file to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:param string output_file_path: the path to the output audio file
:param quit_after: stop synthesizing as soon as
reaching this many seconds
:type quit_after: :class:`~aeneas.exacttiming.TimeValue`
:param bool backwards: if > 0, synthesize from the end of the text file
:rtype: tuple (anchors, total_time, num_chars)
:raises: TypeError: if ``text_file`` is ``None`` or
one of the text fragments is not a Unicode string
:raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False``
and a fragment has a language code not supported by the TTS engine, or
if ``text_file`` has no fragments or all its fragments are empty
:raises: OSError: if output file cannot be written to ``output_file_path``
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed.
"""
if text_file is None:
self.log_exc(u"text_file is None", None, True, TypeError)
if len(text_file) < 1:
self.log_exc(u"The text file has no fragments", None, True, ValueError)
if text_file.chars == 0:
self.log_exc(u"All fragments in the text file are empty", None, True, ValueError)
if not self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]:
for fragment in text_file.fragments:
if fragment.language not in self.LANGUAGE_TO_VOICE_CODE:
self.log_exc(u"Language '%s' is not supported by the selected TTS engine" % (fragment.language), None, True, ValueError)
for fragment in text_file.fragments:
for line in fragment.lines:
if not gf.is_unicode(line):
self.log_exc(u"The text file contain a line which is not a Unicode string", None, True, TypeError)
# log parameters
if quit_after is not None:
self.log([u"Quit after reaching %.3f", quit_after])
if backwards:
self.log(u"Synthesizing backwards")
# check that output_file_path can be written
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Cannot write to output file '%s'" % (output_file_path), None, True, OSError)
# first, call Python function _synthesize_multiple_python() if available
if self.HAS_PYTHON_CALL:
self.log(u"Calling TTS engine via Python")
try:
computed, result = self._synthesize_multiple_python(text_file, output_file_path, quit_after, backwards)
if computed:
self.log(u"The _synthesize_multiple_python call was successful, returning anchors")
return result
else:
self.log(u"The _synthesize_multiple_python call failed")
except Exception as exc:
self.log_exc(u"An unexpected error occurred while calling _synthesize_multiple_python", exc, False, None)
# call _synthesize_multiple_c_extension() or _synthesize_multiple_subprocess()
self.log(u"Calling TTS engine via C extension or subprocess")
c_extension_function = self._synthesize_multiple_c_extension if self.HAS_C_EXTENSION_CALL else None
subprocess_function = self._synthesize_multiple_subprocess if self.HAS_SUBPROCESS_CALL else None
return gf.run_c_extension_with_fallback(
self.log,
self.C_EXTENSION_NAME,
c_extension_function,
subprocess_function,
(text_file, output_file_path, quit_after, backwards),
rconf=self.rconf
) | [
"def",
"synthesize_multiple",
"(",
"self",
",",
"text_file",
",",
"output_file_path",
",",
"quit_after",
"=",
"None",
",",
"backwards",
"=",
"False",
")",
":",
"if",
"text_file",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"text_file is None\"",
",",
... | Synthesize the text contained in the given fragment list
into a WAVE file.
Return a tuple (anchors, total_time, num_chars).
Concrete subclasses must implement at least one
of the following private functions:
1. ``_synthesize_multiple_python()``
2. ``_synthesize_multiple_c_extension()``
3. ``_synthesize_multiple_subprocess()``
:param text_file: the text file to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:param string output_file_path: the path to the output audio file
:param quit_after: stop synthesizing as soon as
reaching this many seconds
:type quit_after: :class:`~aeneas.exacttiming.TimeValue`
:param bool backwards: if > 0, synthesize from the end of the text file
:rtype: tuple (anchors, total_time, num_chars)
:raises: TypeError: if ``text_file`` is ``None`` or
one of the text fragments is not a Unicode string
:raises: ValueError: if ``self.rconf[RuntimeConfiguration.ALLOW_UNLISTED_LANGUAGES]`` is ``False``
and a fragment has a language code not supported by the TTS engine, or
if ``text_file`` has no fragments or all its fragments are empty
:raises: OSError: if output file cannot be written to ``output_file_path``
:raises: RuntimeError: if both the C extension and
the pure Python code did not succeed. | [
"Synthesize",
"the",
"text",
"contained",
"in",
"the",
"given",
"fragment",
"list",
"into",
"a",
"WAVE",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L363-L443 | train | 227,143 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._synthesize_multiple_python | def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple fragments via a Python call.
:rtype: tuple (result, (anchors, current_time, num_chars))
"""
self.log(u"Synthesizing multiple via a Python call...")
ret = self._synthesize_multiple_generic(
helper_function=self._synthesize_single_python_helper,
text_file=text_file,
output_file_path=output_file_path,
quit_after=quit_after,
backwards=backwards
)
self.log(u"Synthesizing multiple via a Python call... done")
return ret | python | def _synthesize_multiple_python(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple fragments via a Python call.
:rtype: tuple (result, (anchors, current_time, num_chars))
"""
self.log(u"Synthesizing multiple via a Python call...")
ret = self._synthesize_multiple_generic(
helper_function=self._synthesize_single_python_helper,
text_file=text_file,
output_file_path=output_file_path,
quit_after=quit_after,
backwards=backwards
)
self.log(u"Synthesizing multiple via a Python call... done")
return ret | [
"def",
"_synthesize_multiple_python",
"(",
"self",
",",
"text_file",
",",
"output_file_path",
",",
"quit_after",
"=",
"None",
",",
"backwards",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Synthesizing multiple via a Python call...\"",
")",
"ret",
"=",
"se... | Synthesize multiple fragments via a Python call.
:rtype: tuple (result, (anchors, current_time, num_chars)) | [
"Synthesize",
"multiple",
"fragments",
"via",
"a",
"Python",
"call",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L445-L460 | train | 227,144 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._synthesize_multiple_subprocess | def _synthesize_multiple_subprocess(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple fragments via ``subprocess``.
:rtype: tuple (result, (anchors, current_time, num_chars))
"""
self.log(u"Synthesizing multiple via subprocess...")
ret = self._synthesize_multiple_generic(
helper_function=self._synthesize_single_subprocess_helper,
text_file=text_file,
output_file_path=output_file_path,
quit_after=quit_after,
backwards=backwards
)
self.log(u"Synthesizing multiple via subprocess... done")
return ret | python | def _synthesize_multiple_subprocess(self, text_file, output_file_path, quit_after=None, backwards=False):
"""
Synthesize multiple fragments via ``subprocess``.
:rtype: tuple (result, (anchors, current_time, num_chars))
"""
self.log(u"Synthesizing multiple via subprocess...")
ret = self._synthesize_multiple_generic(
helper_function=self._synthesize_single_subprocess_helper,
text_file=text_file,
output_file_path=output_file_path,
quit_after=quit_after,
backwards=backwards
)
self.log(u"Synthesizing multiple via subprocess... done")
return ret | [
"def",
"_synthesize_multiple_subprocess",
"(",
"self",
",",
"text_file",
",",
"output_file_path",
",",
"quit_after",
"=",
"None",
",",
"backwards",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Synthesizing multiple via subprocess...\"",
")",
"ret",
"=",
"s... | Synthesize multiple fragments via ``subprocess``.
:rtype: tuple (result, (anchors, current_time, num_chars)) | [
"Synthesize",
"multiple",
"fragments",
"via",
"subprocess",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L496-L511 | train | 227,145 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._read_audio_data | def _read_audio_data(self, file_path):
"""
Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
"""
try:
self.log(u"Reading audio data...")
# if we know the TTS outputs to PCM16 mono WAVE
# with the correct sample rate,
# we can read samples directly from it,
# without an intermediate conversion through ffmpeg
audio_file = AudioFile(
file_path=file_path,
file_format=self.OUTPUT_AUDIO_FORMAT,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self.log([u"Duration of '%s': %f", file_path, audio_file.audio_length])
self.log(u"Reading audio data... done")
return (True, (
audio_file.audio_length,
audio_file.audio_sample_rate,
audio_file.audio_format,
audio_file.audio_samples
))
except (AudioFileUnsupportedFormatError, OSError) as exc:
self.log_exc(u"An unexpected error occurred while reading audio data", exc, True, None)
return (False, None) | python | def _read_audio_data(self, file_path):
"""
Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception
"""
try:
self.log(u"Reading audio data...")
# if we know the TTS outputs to PCM16 mono WAVE
# with the correct sample rate,
# we can read samples directly from it,
# without an intermediate conversion through ffmpeg
audio_file = AudioFile(
file_path=file_path,
file_format=self.OUTPUT_AUDIO_FORMAT,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self.log([u"Duration of '%s': %f", file_path, audio_file.audio_length])
self.log(u"Reading audio data... done")
return (True, (
audio_file.audio_length,
audio_file.audio_sample_rate,
audio_file.audio_format,
audio_file.audio_samples
))
except (AudioFileUnsupportedFormatError, OSError) as exc:
self.log_exc(u"An unexpected error occurred while reading audio data", exc, True, None)
return (False, None) | [
"def",
"_read_audio_data",
"(",
"self",
",",
"file_path",
")",
":",
"try",
":",
"self",
".",
"log",
"(",
"u\"Reading audio data...\"",
")",
"# if we know the TTS outputs to PCM16 mono WAVE",
"# with the correct sample rate,",
"# we can read samples directly from it,",
"# withou... | Read audio data from file.
:rtype: tuple (True, (duration, sample_rate, codec, data)) or (False, None) on exception | [
"Read",
"audio",
"data",
"from",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L639-L668 | train | 227,146 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._loop_no_cache | def _loop_no_cache(self, helper_function, num, fragment):
""" Synthesize all fragments without using the cache """
self.log([u"Examining fragment %d (no cache)...", num])
# synthesize and get the duration of the output file
voice_code = self._language_to_voice_code(fragment.language)
self.log(u"Calling helper function")
succeeded, data = helper_function(
text=fragment.filtered_text,
voice_code=voice_code,
output_file_path=None,
return_audio_data=True
)
# check output
if not succeeded:
self.log_crit(u"An unexpected error occurred in helper_function")
return (False, None)
self.log([u"Examining fragment %d (no cache)... done", num])
return (True, data) | python | def _loop_no_cache(self, helper_function, num, fragment):
""" Synthesize all fragments without using the cache """
self.log([u"Examining fragment %d (no cache)...", num])
# synthesize and get the duration of the output file
voice_code = self._language_to_voice_code(fragment.language)
self.log(u"Calling helper function")
succeeded, data = helper_function(
text=fragment.filtered_text,
voice_code=voice_code,
output_file_path=None,
return_audio_data=True
)
# check output
if not succeeded:
self.log_crit(u"An unexpected error occurred in helper_function")
return (False, None)
self.log([u"Examining fragment %d (no cache)... done", num])
return (True, data) | [
"def",
"_loop_no_cache",
"(",
"self",
",",
"helper_function",
",",
"num",
",",
"fragment",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Examining fragment %d (no cache)...\"",
",",
"num",
"]",
")",
"# synthesize and get the duration of the output file",
"voice_code",
"... | Synthesize all fragments without using the cache | [
"Synthesize",
"all",
"fragments",
"without",
"using",
"the",
"cache"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L769-L786 | train | 227,147 |
readbeyond/aeneas | aeneas/ttswrappers/basettswrapper.py | BaseTTSWrapper._loop_use_cache | def _loop_use_cache(self, helper_function, num, fragment):
""" Synthesize all fragments using the cache """
self.log([u"Examining fragment %d (cache)...", num])
fragment_info = (fragment.language, fragment.filtered_text)
if self.cache.is_cached(fragment_info):
self.log(u"Fragment cached: retrieving audio data from cache")
# read data from file, whose path is in the cache
file_handler, file_path = self.cache.get(fragment_info)
self.log([u"Reading cached fragment at '%s'...", file_path])
succeeded, data = self._read_audio_data(file_path)
if not succeeded:
self.log_crit(u"An unexpected error occurred while reading cached audio file")
return (False, None)
self.log([u"Reading cached fragment at '%s'... done", file_path])
else:
self.log(u"Fragment not cached: synthesizing and caching")
# creating destination file
file_info = gf.tmp_file(suffix=u".cache.wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
file_handler, file_path = file_info
self.log([u"Synthesizing fragment to '%s'...", file_path])
# synthesize and get the duration of the output file
voice_code = self._language_to_voice_code(fragment.language)
self.log(u"Calling helper function")
succeeded, data = helper_function(
text=fragment.filtered_text,
voice_code=voice_code,
output_file_path=file_path,
return_audio_data=True
)
# check output
if not succeeded:
self.log_crit(u"An unexpected error occurred in helper_function")
return (False, None)
self.log([u"Synthesizing fragment to '%s'... done", file_path])
duration, sr_nu, enc_nu, samples = data
if duration > 0:
self.log(u"Fragment has > 0 duration, adding it to cache")
self.cache.add(fragment_info, file_info)
self.log(u"Added fragment to cache")
else:
self.log(u"Fragment has zero duration, not adding it to cache")
self.log([u"Closing file handler for cached output file path '%s'", file_path])
gf.close_file_handler(file_handler)
self.log([u"Examining fragment %d (cache)... done", num])
return (True, data) | python | def _loop_use_cache(self, helper_function, num, fragment):
""" Synthesize all fragments using the cache """
self.log([u"Examining fragment %d (cache)...", num])
fragment_info = (fragment.language, fragment.filtered_text)
if self.cache.is_cached(fragment_info):
self.log(u"Fragment cached: retrieving audio data from cache")
# read data from file, whose path is in the cache
file_handler, file_path = self.cache.get(fragment_info)
self.log([u"Reading cached fragment at '%s'...", file_path])
succeeded, data = self._read_audio_data(file_path)
if not succeeded:
self.log_crit(u"An unexpected error occurred while reading cached audio file")
return (False, None)
self.log([u"Reading cached fragment at '%s'... done", file_path])
else:
self.log(u"Fragment not cached: synthesizing and caching")
# creating destination file
file_info = gf.tmp_file(suffix=u".cache.wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
file_handler, file_path = file_info
self.log([u"Synthesizing fragment to '%s'...", file_path])
# synthesize and get the duration of the output file
voice_code = self._language_to_voice_code(fragment.language)
self.log(u"Calling helper function")
succeeded, data = helper_function(
text=fragment.filtered_text,
voice_code=voice_code,
output_file_path=file_path,
return_audio_data=True
)
# check output
if not succeeded:
self.log_crit(u"An unexpected error occurred in helper_function")
return (False, None)
self.log([u"Synthesizing fragment to '%s'... done", file_path])
duration, sr_nu, enc_nu, samples = data
if duration > 0:
self.log(u"Fragment has > 0 duration, adding it to cache")
self.cache.add(fragment_info, file_info)
self.log(u"Added fragment to cache")
else:
self.log(u"Fragment has zero duration, not adding it to cache")
self.log([u"Closing file handler for cached output file path '%s'", file_path])
gf.close_file_handler(file_handler)
self.log([u"Examining fragment %d (cache)... done", num])
return (True, data) | [
"def",
"_loop_use_cache",
"(",
"self",
",",
"helper_function",
",",
"num",
",",
"fragment",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Examining fragment %d (cache)...\"",
",",
"num",
"]",
")",
"fragment_info",
"=",
"(",
"fragment",
".",
"language",
",",
"f... | Synthesize all fragments using the cache | [
"Synthesize",
"all",
"fragments",
"using",
"the",
"cache"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/ttswrappers/basettswrapper.py#L788-L835 | train | 227,148 |
readbeyond/aeneas | aeneas/adjustboundaryalgorithm.py | AdjustBoundaryAlgorithm.adjust | def adjust(
self,
aba_parameters,
boundary_indices,
real_wave_mfcc,
text_file,
allow_arbitrary_shift=False
):
"""
Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the sync map fragment list internally.
:param dict aba_parameters: a dictionary containing the algorithm and its parameters,
as produced by ``aba_parameters()`` in ``TaskConfiguration``
:param boundary_indices: the current boundary indices,
with respect to the audio file full MFCCs
:type boundary_indices: :class:`numpy.ndarray` (1D)
:param real_wave_mfcc: the audio file MFCCs
:type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file containing the text fragments associated
:type text_file: :class:`~aeneas.textfile.TextFile`
:param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length
:rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList`
"""
self.log(u"Called adjust")
if boundary_indices is None:
self.log_exc(u"boundary_indices is None", None, True, TypeError)
if not isinstance(real_wave_mfcc, AudioFileMFCC):
self.log_exc(u"real_wave_mfcc is not an AudioFileMFCC object", None, True, TypeError)
if not isinstance(text_file, TextFile):
self.log_exc(u"text_file is not a TextFile object", None, True, TypeError)
nozero = aba_parameters["nozero"]
ns_min, ns_string = aba_parameters["nonspeech"]
algorithm, algo_parameters = aba_parameters["algorithm"]
self.log(u" Converting boundary indices to fragment list...")
begin = real_wave_mfcc.middle_begin * real_wave_mfcc.rconf.mws
end = real_wave_mfcc.middle_end * real_wave_mfcc.rconf.mws
time_values = [begin] + list(boundary_indices * self.mws) + [end]
self.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
self.log(u" Converting boundary indices to fragment list... done")
self.log(u" Processing fragments with zero length...")
self._process_zero_length(nozero, allow_arbitrary_shift)
self.log(u" Processing fragments with zero length... done")
self.log(u" Processing nonspeech fragments...")
self._process_long_nonspeech(ns_min, ns_string, real_wave_mfcc)
self.log(u" Processing nonspeech fragments... done")
self.log(u" Adjusting...")
ALGORITHM_MAP = {
self.AFTERCURRENT: self._adjust_aftercurrent,
self.AUTO: self._adjust_auto,
self.BEFORENEXT: self._adjust_beforenext,
self.OFFSET: self._adjust_offset,
self.PERCENT: self._adjust_percent,
self.RATE: self._adjust_rate,
self.RATEAGGRESSIVE: self._adjust_rate_aggressive,
}
ALGORITHM_MAP[algorithm](real_wave_mfcc, algo_parameters)
self.log(u" Adjusting... done")
self.log(u" Smoothing...")
self._smooth_fragment_list(real_wave_mfcc.audio_length, ns_string)
self.log(u" Smoothing... done")
return self.smflist | python | def adjust(
self,
aba_parameters,
boundary_indices,
real_wave_mfcc,
text_file,
allow_arbitrary_shift=False
):
"""
Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the sync map fragment list internally.
:param dict aba_parameters: a dictionary containing the algorithm and its parameters,
as produced by ``aba_parameters()`` in ``TaskConfiguration``
:param boundary_indices: the current boundary indices,
with respect to the audio file full MFCCs
:type boundary_indices: :class:`numpy.ndarray` (1D)
:param real_wave_mfcc: the audio file MFCCs
:type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file containing the text fragments associated
:type text_file: :class:`~aeneas.textfile.TextFile`
:param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length
:rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList`
"""
self.log(u"Called adjust")
if boundary_indices is None:
self.log_exc(u"boundary_indices is None", None, True, TypeError)
if not isinstance(real_wave_mfcc, AudioFileMFCC):
self.log_exc(u"real_wave_mfcc is not an AudioFileMFCC object", None, True, TypeError)
if not isinstance(text_file, TextFile):
self.log_exc(u"text_file is not a TextFile object", None, True, TypeError)
nozero = aba_parameters["nozero"]
ns_min, ns_string = aba_parameters["nonspeech"]
algorithm, algo_parameters = aba_parameters["algorithm"]
self.log(u" Converting boundary indices to fragment list...")
begin = real_wave_mfcc.middle_begin * real_wave_mfcc.rconf.mws
end = real_wave_mfcc.middle_end * real_wave_mfcc.rconf.mws
time_values = [begin] + list(boundary_indices * self.mws) + [end]
self.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
self.log(u" Converting boundary indices to fragment list... done")
self.log(u" Processing fragments with zero length...")
self._process_zero_length(nozero, allow_arbitrary_shift)
self.log(u" Processing fragments with zero length... done")
self.log(u" Processing nonspeech fragments...")
self._process_long_nonspeech(ns_min, ns_string, real_wave_mfcc)
self.log(u" Processing nonspeech fragments... done")
self.log(u" Adjusting...")
ALGORITHM_MAP = {
self.AFTERCURRENT: self._adjust_aftercurrent,
self.AUTO: self._adjust_auto,
self.BEFORENEXT: self._adjust_beforenext,
self.OFFSET: self._adjust_offset,
self.PERCENT: self._adjust_percent,
self.RATE: self._adjust_rate,
self.RATEAGGRESSIVE: self._adjust_rate_aggressive,
}
ALGORITHM_MAP[algorithm](real_wave_mfcc, algo_parameters)
self.log(u" Adjusting... done")
self.log(u" Smoothing...")
self._smooth_fragment_list(real_wave_mfcc.audio_length, ns_string)
self.log(u" Smoothing... done")
return self.smflist | [
"def",
"adjust",
"(",
"self",
",",
"aba_parameters",
",",
"boundary_indices",
",",
"real_wave_mfcc",
",",
"text_file",
",",
"allow_arbitrary_shift",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"u\"Called adjust\"",
")",
"if",
"boundary_indices",
"is",
"None... | Adjust the boundaries of the text map
using the algorithm and parameters
specified in the constructor,
storing the sync map fragment list internally.
:param dict aba_parameters: a dictionary containing the algorithm and its parameters,
as produced by ``aba_parameters()`` in ``TaskConfiguration``
:param boundary_indices: the current boundary indices,
with respect to the audio file full MFCCs
:type boundary_indices: :class:`numpy.ndarray` (1D)
:param real_wave_mfcc: the audio file MFCCs
:type real_wave_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file containing the text fragments associated
:type text_file: :class:`~aeneas.textfile.TextFile`
:param bool allow_arbitrary_shift: if ``True``, allow arbitrary shifts when adjusting zero length
:rtype: list of :class:`~aeneas.syncmap.SyncMapFragmentList` | [
"Adjust",
"the",
"boundaries",
"of",
"the",
"text",
"map",
"using",
"the",
"algorithm",
"and",
"parameters",
"specified",
"in",
"the",
"constructor",
"storing",
"the",
"sync",
"map",
"fragment",
"list",
"internally",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L236-L310 | train | 227,149 |
readbeyond/aeneas | aeneas/adjustboundaryalgorithm.py | AdjustBoundaryAlgorithm.append_fragment_list_to_sync_root | def append_fragment_list_to_sync_root(self, sync_root):
"""
Append the sync map fragment list
to the given node from a sync map tree.
:param sync_root: the root of the sync map tree to which the new nodes should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
"""
if not isinstance(sync_root, Tree):
self.log_exc(u"sync_root is not a Tree object", None, True, TypeError)
self.log(u"Appending fragment list to sync root...")
for fragment in self.smflist:
sync_root.add_child(Tree(value=fragment))
self.log(u"Appending fragment list to sync root... done") | python | def append_fragment_list_to_sync_root(self, sync_root):
"""
Append the sync map fragment list
to the given node from a sync map tree.
:param sync_root: the root of the sync map tree to which the new nodes should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
"""
if not isinstance(sync_root, Tree):
self.log_exc(u"sync_root is not a Tree object", None, True, TypeError)
self.log(u"Appending fragment list to sync root...")
for fragment in self.smflist:
sync_root.add_child(Tree(value=fragment))
self.log(u"Appending fragment list to sync root... done") | [
"def",
"append_fragment_list_to_sync_root",
"(",
"self",
",",
"sync_root",
")",
":",
"if",
"not",
"isinstance",
"(",
"sync_root",
",",
"Tree",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"sync_root is not a Tree object\"",
",",
"None",
",",
"True",
",",
"TypeError... | Append the sync map fragment list
to the given node from a sync map tree.
:param sync_root: the root of the sync map tree to which the new nodes should be appended
:type sync_root: :class:`~aeneas.tree.Tree` | [
"Append",
"the",
"sync",
"map",
"fragment",
"list",
"to",
"the",
"given",
"node",
"from",
"a",
"sync",
"map",
"tree",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L387-L401 | train | 227,150 |
readbeyond/aeneas | aeneas/adjustboundaryalgorithm.py | AdjustBoundaryAlgorithm._process_zero_length | def _process_zero_length(self, nozero, allow_arbitrary_shift):
"""
If ``nozero`` is ``True``, modify the sync map fragment list
so that no fragment will have zero length.
"""
self.log(u"Called _process_zero_length")
if not nozero:
self.log(u"Processing zero length intervals not requested: returning")
return
self.log(u"Processing zero length intervals requested")
self.log(u" Checking and fixing...")
duration = self.rconf[RuntimeConfiguration.ABA_NO_ZERO_DURATION]
self.log([u" Requested no zero duration: %.3f", duration])
if not allow_arbitrary_shift:
self.log(u" No arbitrary shift => taking max with mws")
duration = self.rconf.mws.geq_multiple(duration)
self.log([u" Actual no zero duration: %.3f", duration])
# ignore HEAD and TAIL
max_index = len(self.smflist) - 1
self.smflist.fix_zero_length_fragments(
duration=duration,
min_index=1,
max_index=max_index
)
self.log(u" Checking and fixing... done")
if self.smflist.has_zero_length_fragments(1, max_index):
self.log_warn(u" The fragment list still has fragments with zero length")
else:
self.log(u" The fragment list does not have fragments with zero length") | python | def _process_zero_length(self, nozero, allow_arbitrary_shift):
"""
If ``nozero`` is ``True``, modify the sync map fragment list
so that no fragment will have zero length.
"""
self.log(u"Called _process_zero_length")
if not nozero:
self.log(u"Processing zero length intervals not requested: returning")
return
self.log(u"Processing zero length intervals requested")
self.log(u" Checking and fixing...")
duration = self.rconf[RuntimeConfiguration.ABA_NO_ZERO_DURATION]
self.log([u" Requested no zero duration: %.3f", duration])
if not allow_arbitrary_shift:
self.log(u" No arbitrary shift => taking max with mws")
duration = self.rconf.mws.geq_multiple(duration)
self.log([u" Actual no zero duration: %.3f", duration])
# ignore HEAD and TAIL
max_index = len(self.smflist) - 1
self.smflist.fix_zero_length_fragments(
duration=duration,
min_index=1,
max_index=max_index
)
self.log(u" Checking and fixing... done")
if self.smflist.has_zero_length_fragments(1, max_index):
self.log_warn(u" The fragment list still has fragments with zero length")
else:
self.log(u" The fragment list does not have fragments with zero length") | [
"def",
"_process_zero_length",
"(",
"self",
",",
"nozero",
",",
"allow_arbitrary_shift",
")",
":",
"self",
".",
"log",
"(",
"u\"Called _process_zero_length\"",
")",
"if",
"not",
"nozero",
":",
"self",
".",
"log",
"(",
"u\"Processing zero length intervals not requested... | If ``nozero`` is ``True``, modify the sync map fragment list
so that no fragment will have zero length. | [
"If",
"nozero",
"is",
"True",
"modify",
"the",
"sync",
"map",
"fragment",
"list",
"so",
"that",
"no",
"fragment",
"will",
"have",
"zero",
"length",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/adjustboundaryalgorithm.py#L407-L435 | train | 227,151 |
readbeyond/aeneas | pyinstaller-aeneas-cli.py | main | def main():
"""
This is the aeneas-cli "hydra" script,
to be compiled by pyinstaller.
"""
if FROZEN:
HydraCLI(invoke="aeneas-cli").run(
arguments=sys.argv,
show_help=False
)
else:
HydraCLI(invoke="pyinstaller-aeneas-cli.py").run(
arguments=sys.argv,
show_help=False
) | python | def main():
"""
This is the aeneas-cli "hydra" script,
to be compiled by pyinstaller.
"""
if FROZEN:
HydraCLI(invoke="aeneas-cli").run(
arguments=sys.argv,
show_help=False
)
else:
HydraCLI(invoke="pyinstaller-aeneas-cli.py").run(
arguments=sys.argv,
show_help=False
) | [
"def",
"main",
"(",
")",
":",
"if",
"FROZEN",
":",
"HydraCLI",
"(",
"invoke",
"=",
"\"aeneas-cli\"",
")",
".",
"run",
"(",
"arguments",
"=",
"sys",
".",
"argv",
",",
"show_help",
"=",
"False",
")",
"else",
":",
"HydraCLI",
"(",
"invoke",
"=",
"\"pyin... | This is the aeneas-cli "hydra" script,
to be compiled by pyinstaller. | [
"This",
"is",
"the",
"aeneas",
"-",
"cli",
"hydra",
"script",
"to",
"be",
"compiled",
"by",
"pyinstaller",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/pyinstaller-aeneas-cli.py#L48-L62 | train | 227,152 |
readbeyond/aeneas | aeneas/vad.py | VAD.run_vad | def run_vad(
self,
wave_energy,
log_energy_threshold=None,
min_nonspeech_length=None,
extend_before=None,
extend_after=None
):
"""
Compute the time intervals containing speech and nonspeech,
and return a boolean mask with speech frames set to ``True``,
and nonspeech frames set to ``False``.
The last four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param wave_energy: the energy vector of the audio file (0-th MFCC)
:type wave_energy: :class:`numpy.ndarray` (1D)
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after)
:rtype: :class:`numpy.ndarray` (1D)
"""
self.log(u"Computing VAD for wave")
mfcc_window_shift = self.rconf.mws
self.log([u"MFCC window shift (s): %.3f", mfcc_window_shift])
if log_energy_threshold is None:
log_energy_threshold = self.rconf[RuntimeConfiguration.VAD_LOG_ENERGY_THRESHOLD]
self.log([u"Log energy threshold: %.3f", log_energy_threshold])
if min_nonspeech_length is None:
min_nonspeech_length = int(self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH] / mfcc_window_shift)
self.log([u"Min nonspeech length (s): %.3f", self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH]])
if extend_before is None:
extend_before = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE] / mfcc_window_shift)
self.log([u"Extend speech before (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE]])
if extend_after is None:
extend_after = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER] / mfcc_window_shift)
self.log([u"Extend speech after (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER]])
energy_length = len(wave_energy)
energy_threshold = numpy.min(wave_energy) + log_energy_threshold
self.log([u"Min nonspeech length (frames): %d", min_nonspeech_length])
self.log([u"Extend speech before (frames): %d", extend_before])
self.log([u"Extend speech after (frames): %d", extend_after])
self.log([u"Energy vector length (frames): %d", energy_length])
self.log([u"Energy threshold (log): %.3f", energy_threshold])
# using windows to be sure we have at least
# min_nonspeech_length consecutive frames with nonspeech
self.log(u"Determining initial labels...")
mask = wave_energy >= energy_threshold
windows = self._rolling_window(mask, min_nonspeech_length)
nonspeech_runs = self._compute_runs((numpy.where(numpy.sum(windows, axis=1) == 0))[0])
self.log(u"Determining initial labels... done")
# initially, everything is marked as speech
# we remove the nonspeech intervals as needed,
# possibly extending the adjacent speech interval
# if requested by the user
self.log(u"Determining final labels...")
mask = numpy.ones(energy_length, dtype="bool")
for ns in nonspeech_runs:
start = ns[0]
if (extend_after > 0) and (start > 0):
start += extend_after
stop = ns[-1] + min_nonspeech_length
if (extend_before > 0) and (stop < energy_length - 1):
stop -= extend_before
mask[start:stop] = 0
self.log(u"Determining final labels... done")
return mask | python | def run_vad(
self,
wave_energy,
log_energy_threshold=None,
min_nonspeech_length=None,
extend_before=None,
extend_after=None
):
"""
Compute the time intervals containing speech and nonspeech,
and return a boolean mask with speech frames set to ``True``,
and nonspeech frames set to ``False``.
The last four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param wave_energy: the energy vector of the audio file (0-th MFCC)
:type wave_energy: :class:`numpy.ndarray` (1D)
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after)
:rtype: :class:`numpy.ndarray` (1D)
"""
self.log(u"Computing VAD for wave")
mfcc_window_shift = self.rconf.mws
self.log([u"MFCC window shift (s): %.3f", mfcc_window_shift])
if log_energy_threshold is None:
log_energy_threshold = self.rconf[RuntimeConfiguration.VAD_LOG_ENERGY_THRESHOLD]
self.log([u"Log energy threshold: %.3f", log_energy_threshold])
if min_nonspeech_length is None:
min_nonspeech_length = int(self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH] / mfcc_window_shift)
self.log([u"Min nonspeech length (s): %.3f", self.rconf[RuntimeConfiguration.VAD_MIN_NONSPEECH_LENGTH]])
if extend_before is None:
extend_before = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE] / mfcc_window_shift)
self.log([u"Extend speech before (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_BEFORE]])
if extend_after is None:
extend_after = int(self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER] / mfcc_window_shift)
self.log([u"Extend speech after (s): %.3f", self.rconf[RuntimeConfiguration.VAD_EXTEND_SPEECH_INTERVAL_AFTER]])
energy_length = len(wave_energy)
energy_threshold = numpy.min(wave_energy) + log_energy_threshold
self.log([u"Min nonspeech length (frames): %d", min_nonspeech_length])
self.log([u"Extend speech before (frames): %d", extend_before])
self.log([u"Extend speech after (frames): %d", extend_after])
self.log([u"Energy vector length (frames): %d", energy_length])
self.log([u"Energy threshold (log): %.3f", energy_threshold])
# using windows to be sure we have at least
# min_nonspeech_length consecutive frames with nonspeech
self.log(u"Determining initial labels...")
mask = wave_energy >= energy_threshold
windows = self._rolling_window(mask, min_nonspeech_length)
nonspeech_runs = self._compute_runs((numpy.where(numpy.sum(windows, axis=1) == 0))[0])
self.log(u"Determining initial labels... done")
# initially, everything is marked as speech
# we remove the nonspeech intervals as needed,
# possibly extending the adjacent speech interval
# if requested by the user
self.log(u"Determining final labels...")
mask = numpy.ones(energy_length, dtype="bool")
for ns in nonspeech_runs:
start = ns[0]
if (extend_after > 0) and (start > 0):
start += extend_after
stop = ns[-1] + min_nonspeech_length
if (extend_before > 0) and (stop < energy_length - 1):
stop -= extend_before
mask[start:stop] = 0
self.log(u"Determining final labels... done")
return mask | [
"def",
"run_vad",
"(",
"self",
",",
"wave_energy",
",",
"log_energy_threshold",
"=",
"None",
",",
"min_nonspeech_length",
"=",
"None",
",",
"extend_before",
"=",
"None",
",",
"extend_after",
"=",
"None",
")",
":",
"self",
".",
"log",
"(",
"u\"Computing VAD for... | Compute the time intervals containing speech and nonspeech,
and return a boolean mask with speech frames set to ``True``,
and nonspeech frames set to ``False``.
The last four parameters might be ``None``:
in this case, the corresponding RuntimeConfiguration values
are applied.
:param wave_energy: the energy vector of the audio file (0-th MFCC)
:type wave_energy: :class:`numpy.ndarray` (1D)
:param float log_energy_threshold: the minimum log energy threshold to consider a frame as speech
:param int min_nonspeech_length: the minimum length, in frames, of a nonspeech interval
:param int extend_before: extend each speech interval by this number of frames to the left (before)
:param int extend_after: extend each speech interval by this number of frames to the right (after)
:rtype: :class:`numpy.ndarray` (1D) | [
"Compute",
"the",
"time",
"intervals",
"containing",
"speech",
"and",
"nonspeech",
"and",
"return",
"a",
"boolean",
"mask",
"with",
"speech",
"frames",
"set",
"to",
"True",
"and",
"nonspeech",
"frames",
"set",
"to",
"False",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L60-L131 | train | 227,153 |
readbeyond/aeneas | aeneas/vad.py | VAD._compute_runs | def _compute_runs(self, array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) | python | def _compute_runs(self, array):
"""
Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays
"""
if len(array) < 1:
return []
return numpy.split(array, numpy.where(numpy.diff(array) != 1)[0] + 1) | [
"def",
"_compute_runs",
"(",
"self",
",",
"array",
")",
":",
"if",
"len",
"(",
"array",
")",
"<",
"1",
":",
"return",
"[",
"]",
"return",
"numpy",
".",
"split",
"(",
"array",
",",
"numpy",
".",
"where",
"(",
"numpy",
".",
"diff",
"(",
"array",
")... | Compute runs as a list of arrays,
each containing the indices of a contiguous run.
:param array: the data array
:type array: numpy 1D array
:rtype: list of numpy 1D arrays | [
"Compute",
"runs",
"as",
"a",
"list",
"of",
"arrays",
"each",
"containing",
"the",
"indices",
"of",
"a",
"contiguous",
"run",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L134-L145 | train | 227,154 |
readbeyond/aeneas | aeneas/vad.py | VAD._rolling_window | def _rolling_window(self, array, size):
"""
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size)
"""
shape = array.shape[:-1] + (array.shape[-1] - size + 1, size)
strides = array.strides + (array.strides[-1],)
return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) | python | def _rolling_window(self, array, size):
"""
Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size)
"""
shape = array.shape[:-1] + (array.shape[-1] - size + 1, size)
strides = array.strides + (array.strides[-1],)
return numpy.lib.stride_tricks.as_strided(array, shape=shape, strides=strides) | [
"def",
"_rolling_window",
"(",
"self",
",",
"array",
",",
"size",
")",
":",
"shape",
"=",
"array",
".",
"shape",
"[",
":",
"-",
"1",
"]",
"+",
"(",
"array",
".",
"shape",
"[",
"-",
"1",
"]",
"-",
"size",
"+",
"1",
",",
"size",
")",
"strides",
... | Compute rolling windows of width ``size`` of the given array.
Return a numpy 2D stride array,
where rows are the windows, each of ``size`` elements.
:param array: the data array
:type array: numpy 1D array (n)
:param int size: the width of each window
:rtype: numpy 2D stride array (n // size, size) | [
"Compute",
"rolling",
"windows",
"of",
"width",
"size",
"of",
"the",
"given",
"array",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/vad.py#L148-L162 | train | 227,155 |
pysam-developers/pysam | pysam/utils.py | PysamDispatcher.usage | def usage(self):
'''return the samtools usage information for this command'''
retval, stderr, stdout = _pysam_dispatch(
self.collection,
self.dispatch,
is_usage=True,
catch_stdout=True)
# some tools write usage to stderr, such as mpileup
if stderr:
return stderr
else:
return stdout | python | def usage(self):
'''return the samtools usage information for this command'''
retval, stderr, stdout = _pysam_dispatch(
self.collection,
self.dispatch,
is_usage=True,
catch_stdout=True)
# some tools write usage to stderr, such as mpileup
if stderr:
return stderr
else:
return stdout | [
"def",
"usage",
"(",
"self",
")",
":",
"retval",
",",
"stderr",
",",
"stdout",
"=",
"_pysam_dispatch",
"(",
"self",
".",
"collection",
",",
"self",
".",
"dispatch",
",",
"is_usage",
"=",
"True",
",",
"catch_stdout",
"=",
"True",
")",
"# some tools write us... | return the samtools usage information for this command | [
"return",
"the",
"samtools",
"usage",
"information",
"for",
"this",
"command"
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/utils.py#L93-L104 | train | 227,156 |
pysam-developers/pysam | pysam/Pileup.py | iterate | def iterate(infile):
'''iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates
'''
conv_subst = (str, lambda x: int(x) - 1, str,
str, int, int, int, int, str, str)
conv_indel = (str, lambda x: int(x) - 1, str, str, int,
int, int, int, str, str, int, int, int)
for line in infile:
d = line[:-1].split()
if d[2] == "*":
try:
yield PileupIndel(*[x(y) for x, y in zip(conv_indel, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line)
else:
try:
yield PileupSubstitution(*[x(y) for x, y in zip(conv_subst, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line) | python | def iterate(infile):
'''iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates
'''
conv_subst = (str, lambda x: int(x) - 1, str,
str, int, int, int, int, str, str)
conv_indel = (str, lambda x: int(x) - 1, str, str, int,
int, int, int, str, str, int, int, int)
for line in infile:
d = line[:-1].split()
if d[2] == "*":
try:
yield PileupIndel(*[x(y) for x, y in zip(conv_indel, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line)
else:
try:
yield PileupSubstitution(*[x(y) for x, y in zip(conv_subst, d)])
except TypeError:
raise pysam.SamtoolsError("parsing error in line: `%s`" % line) | [
"def",
"iterate",
"(",
"infile",
")",
":",
"conv_subst",
"=",
"(",
"str",
",",
"lambda",
"x",
":",
"int",
"(",
"x",
")",
"-",
"1",
",",
"str",
",",
"str",
",",
"int",
",",
"int",
",",
"int",
",",
"int",
",",
"str",
",",
"str",
")",
"conv_inde... | iterate over ``samtools pileup -c`` formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution`
or :class:`pysam.Pileup.PileupIndel`.
.. note::
The parser converts to 0-based coordinates | [
"iterate",
"over",
"samtools",
"pileup",
"-",
"c",
"formatted",
"file",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L35-L64 | train | 227,157 |
pysam-developers/pysam | pysam/Pileup.py | vcf2pileup | def vcf2pileup(vcf, sample):
'''convert vcf record to pileup record.'''
chromosome = vcf.contig
pos = vcf.pos
reference = vcf.ref
allelles = [reference] + vcf.alt
data = vcf[sample]
# get genotype
genotypes = data["GT"]
if len(genotypes) > 1:
raise ValueError("only single genotype per position, %s" % (str(vcf)))
genotypes = genotypes[0]
# not a variant
if genotypes[0] == ".":
return None
genotypes = [allelles[int(x)] for x in genotypes if x != "/"]
# snp_quality is "genotype quality"
snp_quality = consensus_quality = data.get("GQ", [0])[0]
mapping_quality = vcf.info.get("MQ", [0])[0]
coverage = data.get("DP", 0)
if len(reference) > 1 or max([len(x) for x in vcf.alt]) > 1:
# indel
genotype, offset = translateIndelGenotypeFromVCF(genotypes, reference)
return PileupIndel(chromosome,
pos + offset,
"*",
genotype,
consensus_quality,
snp_quality,
mapping_quality,
coverage,
genotype,
"<" * len(genotype),
0,
0,
0)
else:
genotype = encodeGenotype("".join(genotypes))
read_bases = ""
base_qualities = ""
return PileupSubstitution(chromosome, pos, reference,
genotype, consensus_quality,
snp_quality, mapping_quality,
coverage, read_bases,
base_qualities) | python | def vcf2pileup(vcf, sample):
'''convert vcf record to pileup record.'''
chromosome = vcf.contig
pos = vcf.pos
reference = vcf.ref
allelles = [reference] + vcf.alt
data = vcf[sample]
# get genotype
genotypes = data["GT"]
if len(genotypes) > 1:
raise ValueError("only single genotype per position, %s" % (str(vcf)))
genotypes = genotypes[0]
# not a variant
if genotypes[0] == ".":
return None
genotypes = [allelles[int(x)] for x in genotypes if x != "/"]
# snp_quality is "genotype quality"
snp_quality = consensus_quality = data.get("GQ", [0])[0]
mapping_quality = vcf.info.get("MQ", [0])[0]
coverage = data.get("DP", 0)
if len(reference) > 1 or max([len(x) for x in vcf.alt]) > 1:
# indel
genotype, offset = translateIndelGenotypeFromVCF(genotypes, reference)
return PileupIndel(chromosome,
pos + offset,
"*",
genotype,
consensus_quality,
snp_quality,
mapping_quality,
coverage,
genotype,
"<" * len(genotype),
0,
0,
0)
else:
genotype = encodeGenotype("".join(genotypes))
read_bases = ""
base_qualities = ""
return PileupSubstitution(chromosome, pos, reference,
genotype, consensus_quality,
snp_quality, mapping_quality,
coverage, read_bases,
base_qualities) | [
"def",
"vcf2pileup",
"(",
"vcf",
",",
"sample",
")",
":",
"chromosome",
"=",
"vcf",
".",
"contig",
"pos",
"=",
"vcf",
".",
"pos",
"reference",
"=",
"vcf",
".",
"ref",
"allelles",
"=",
"[",
"reference",
"]",
"+",
"vcf",
".",
"alt",
"data",
"=",
"vcf... | convert vcf record to pileup record. | [
"convert",
"vcf",
"record",
"to",
"pileup",
"record",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L198-L253 | train | 227,158 |
pysam-developers/pysam | pysam/Pileup.py | iterate_from_vcf | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly.
'''
vcf = pysam.VCF()
vcf.connect(infile)
if sample not in vcf.getsamples():
raise KeyError("sample %s not vcf file")
for row in vcf.fetch():
result = vcf2pileup(row, sample)
if result:
yield result | python | def iterate_from_vcf(infile, sample):
'''iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly.
'''
vcf = pysam.VCF()
vcf.connect(infile)
if sample not in vcf.getsamples():
raise KeyError("sample %s not vcf file")
for row in vcf.fetch():
result = vcf2pileup(row, sample)
if result:
yield result | [
"def",
"iterate_from_vcf",
"(",
"infile",
",",
"sample",
")",
":",
"vcf",
"=",
"pysam",
".",
"VCF",
"(",
")",
"vcf",
".",
"connect",
"(",
"infile",
")",
"if",
"sample",
"not",
"in",
"vcf",
".",
"getsamples",
"(",
")",
":",
"raise",
"KeyError",
"(",
... | iterate over a vcf-formatted file.
*infile* can be any iterator over a lines.
The function yields named tuples of the type
:class:`pysam.Pileup.PileupSubstitution` or
:class:`pysam.Pileup.PileupIndel`.
Positions without a snp will be skipped.
This method is wasteful and written to support same legacy code
that expects samtools pileup output.
Better use the vcf parser directly. | [
"iterate",
"over",
"a",
"vcf",
"-",
"formatted",
"file",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/Pileup.py#L256-L282 | train | 227,159 |
pysam-developers/pysam | devtools/import.py | _update_pysam_files | def _update_pysam_files(cf, destdir):
'''update pysam files applying redirection of ouput'''
basename = os.path.basename(destdir)
for filename in cf:
if not filename:
continue
dest = filename + ".pysam.c"
with open(filename, encoding="utf-8") as infile:
lines = "".join(infile.readlines())
with open(dest, "w", encoding="utf-8") as outfile:
outfile.write('#include "{}.pysam.h"\n\n'.format(basename))
subname, _ = os.path.splitext(os.path.basename(filename))
if subname in MAIN.get(basename, []):
lines = re.sub(r"int main\(", "int {}_main(".format(
basename), lines)
else:
lines = re.sub(r"int main\(", "int {}_{}_main(".format(
basename, subname), lines)
lines = re.sub("stderr", "{}_stderr".format(basename), lines)
lines = re.sub("stdout", "{}_stdout".format(basename), lines)
lines = re.sub(r" printf\(", " fprintf({}_stdout, ".format(basename), lines)
lines = re.sub(r"([^kf])puts\(", r"\1{}_puts(".format(basename), lines)
lines = re.sub(r"putchar\(([^)]+)\)",
r"fputc(\1, {}_stdout)".format(basename), lines)
fn = os.path.basename(filename)
# some specific fixes:
SPECIFIC_SUBSTITUTIONS = {
"bam_md.c": (
'sam_open_format("-", mode_w',
'sam_open_format({}_stdout_fn, mode_w'.format(basename)),
"phase.c": (
'putc("ACGT"[f->seq[j] == 1? (c&3, {}_stdout) : (c>>16&3)]);'.format(basename),
'putc("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)], {}_stdout);'.format(basename)),
"cut_target.c": (
'putc(33 + (cns[j]>>8>>2, {}_stdout));'.format(basename),
'putc(33 + (cns[j]>>8>>2), {}_stdout);'.format(basename))
}
if fn in SPECIFIC_SUBSTITUTIONS:
lines = lines.replace(
SPECIFIC_SUBSTITUTIONS[fn][0],
SPECIFIC_SUBSTITUTIONS[fn][1])
outfile.write(lines)
with open(os.path.join("import", "pysam.h")) as inf, \
open(os.path.join(destdir, "{}.pysam.h".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read()))
with open(os.path.join("import", "pysam.c")) as inf, \
open(os.path.join(destdir, "{}.pysam.c".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read())) | python | def _update_pysam_files(cf, destdir):
'''update pysam files applying redirection of ouput'''
basename = os.path.basename(destdir)
for filename in cf:
if not filename:
continue
dest = filename + ".pysam.c"
with open(filename, encoding="utf-8") as infile:
lines = "".join(infile.readlines())
with open(dest, "w", encoding="utf-8") as outfile:
outfile.write('#include "{}.pysam.h"\n\n'.format(basename))
subname, _ = os.path.splitext(os.path.basename(filename))
if subname in MAIN.get(basename, []):
lines = re.sub(r"int main\(", "int {}_main(".format(
basename), lines)
else:
lines = re.sub(r"int main\(", "int {}_{}_main(".format(
basename, subname), lines)
lines = re.sub("stderr", "{}_stderr".format(basename), lines)
lines = re.sub("stdout", "{}_stdout".format(basename), lines)
lines = re.sub(r" printf\(", " fprintf({}_stdout, ".format(basename), lines)
lines = re.sub(r"([^kf])puts\(", r"\1{}_puts(".format(basename), lines)
lines = re.sub(r"putchar\(([^)]+)\)",
r"fputc(\1, {}_stdout)".format(basename), lines)
fn = os.path.basename(filename)
# some specific fixes:
SPECIFIC_SUBSTITUTIONS = {
"bam_md.c": (
'sam_open_format("-", mode_w',
'sam_open_format({}_stdout_fn, mode_w'.format(basename)),
"phase.c": (
'putc("ACGT"[f->seq[j] == 1? (c&3, {}_stdout) : (c>>16&3)]);'.format(basename),
'putc("ACGT"[f->seq[j] == 1? (c&3) : (c>>16&3)], {}_stdout);'.format(basename)),
"cut_target.c": (
'putc(33 + (cns[j]>>8>>2, {}_stdout));'.format(basename),
'putc(33 + (cns[j]>>8>>2), {}_stdout);'.format(basename))
}
if fn in SPECIFIC_SUBSTITUTIONS:
lines = lines.replace(
SPECIFIC_SUBSTITUTIONS[fn][0],
SPECIFIC_SUBSTITUTIONS[fn][1])
outfile.write(lines)
with open(os.path.join("import", "pysam.h")) as inf, \
open(os.path.join(destdir, "{}.pysam.h".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read()))
with open(os.path.join("import", "pysam.c")) as inf, \
open(os.path.join(destdir, "{}.pysam.c".format(basename)), "w") as outf:
outf.write(re.sub("@pysam@", basename, inf.read())) | [
"def",
"_update_pysam_files",
"(",
"cf",
",",
"destdir",
")",
":",
"basename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"destdir",
")",
"for",
"filename",
"in",
"cf",
":",
"if",
"not",
"filename",
":",
"continue",
"dest",
"=",
"filename",
"+",
"\"... | update pysam files applying redirection of ouput | [
"update",
"pysam",
"files",
"applying",
"redirection",
"of",
"ouput"
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/devtools/import.py#L83-L134 | train | 227,160 |
pysam-developers/pysam | pysam/__init__.py | get_include | def get_include():
'''return a list of include directories.'''
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
#
# Header files may be stored in different relative locations
# depending on installation mode (e.g., `python setup.py install`,
# `python setup.py develop`. The first entry in each list is
# where develop-mode headers can be found.
#
htslib_possibilities = [os.path.join(dirname, '..', 'htslib'),
os.path.join(dirname, 'include', 'htslib')]
samtool_possibilities = [os.path.join(dirname, '..', 'samtools'),
os.path.join(dirname, 'include', 'samtools')]
includes = [dirname]
for header_locations in [htslib_possibilities, samtool_possibilities]:
for header_location in header_locations:
if os.path.exists(header_location):
includes.append(os.path.abspath(header_location))
break
return includes | python | def get_include():
'''return a list of include directories.'''
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
#
# Header files may be stored in different relative locations
# depending on installation mode (e.g., `python setup.py install`,
# `python setup.py develop`. The first entry in each list is
# where develop-mode headers can be found.
#
htslib_possibilities = [os.path.join(dirname, '..', 'htslib'),
os.path.join(dirname, 'include', 'htslib')]
samtool_possibilities = [os.path.join(dirname, '..', 'samtools'),
os.path.join(dirname, 'include', 'samtools')]
includes = [dirname]
for header_locations in [htslib_possibilities, samtool_possibilities]:
for header_location in header_locations:
if os.path.exists(header_location):
includes.append(os.path.abspath(header_location))
break
return includes | [
"def",
"get_include",
"(",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"#",
"# Header files may be stored in different relative lo... | return a list of include directories. | [
"return",
"a",
"list",
"of",
"include",
"directories",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/__init__.py#L53-L75 | train | 227,161 |
pysam-developers/pysam | pysam/__init__.py | get_libraries | def get_libraries():
'''return a list of libraries to link against.'''
# Note that this list does not include libcsamtools.so as there are
# numerous name conflicts with libchtslib.so.
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
pysam_libs = ['libctabixproxies',
'libcfaidx',
'libcsamfile',
'libcvcf',
'libcbcf',
'libctabix']
if pysam.config.HTSLIB == "builtin":
pysam_libs.append('libchtslib')
so = sysconfig.get_config_var('SO')
return [os.path.join(dirname, x + so) for x in pysam_libs] | python | def get_libraries():
'''return a list of libraries to link against.'''
# Note that this list does not include libcsamtools.so as there are
# numerous name conflicts with libchtslib.so.
dirname = os.path.abspath(os.path.join(os.path.dirname(__file__)))
pysam_libs = ['libctabixproxies',
'libcfaidx',
'libcsamfile',
'libcvcf',
'libcbcf',
'libctabix']
if pysam.config.HTSLIB == "builtin":
pysam_libs.append('libchtslib')
so = sysconfig.get_config_var('SO')
return [os.path.join(dirname, x + so) for x in pysam_libs] | [
"def",
"get_libraries",
"(",
")",
":",
"# Note that this list does not include libcsamtools.so as there are",
"# numerous name conflicts with libchtslib.so.",
"dirname",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",... | return a list of libraries to link against. | [
"return",
"a",
"list",
"of",
"libraries",
"to",
"link",
"against",
"."
] | 9961bebd4cd1f2bf5e42817df25699a6e6344b5a | https://github.com/pysam-developers/pysam/blob/9961bebd4cd1f2bf5e42817df25699a6e6344b5a/pysam/__init__.py#L85-L100 | train | 227,162 |
nerdvegas/rez | src/rez/vendor/pygraph/classes/digraph.py | digraph.has_edge | def has_edge(self, edge):
"""
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence.
"""
u, v = edge
return (u, v) in self.edge_properties | python | def has_edge(self, edge):
"""
Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence.
"""
u, v = edge
return (u, v) in self.edge_properties | [
"def",
"has_edge",
"(",
"self",
",",
"edge",
")",
":",
"u",
",",
"v",
"=",
"edge",
"return",
"(",
"u",
",",
"v",
")",
"in",
"self",
".",
"edge_properties"
] | Return whether an edge exists.
@type edge: tuple
@param edge: Edge.
@rtype: boolean
@return: Truth-value for edge existence. | [
"Return",
"whether",
"an",
"edge",
"exists",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/digraph.py#L214-L225 | train | 227,163 |
nerdvegas/rez | src/rez/package_serialise.py | dump_package_data | def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
"""Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print.
"""
if format_ == FileFormat.txt:
raise ValueError("'txt' format not supported for packages.")
data_ = dict((k, v) for k, v in data.iteritems() if v is not None)
data_ = package_serialise_schema.validate(data_)
skip = set(skip_attributes or [])
items = []
for key in package_key_order:
if key not in skip:
value = data_.pop(key, None)
if value is not None:
items.append((key, value))
# remaining are arbitrary keys
for key, value in data_.iteritems():
if key not in skip:
items.append((key, value))
dump_func = dump_functions[format_]
dump_func(items, buf) | python | def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
"""Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print.
"""
if format_ == FileFormat.txt:
raise ValueError("'txt' format not supported for packages.")
data_ = dict((k, v) for k, v in data.iteritems() if v is not None)
data_ = package_serialise_schema.validate(data_)
skip = set(skip_attributes or [])
items = []
for key in package_key_order:
if key not in skip:
value = data_.pop(key, None)
if value is not None:
items.append((key, value))
# remaining are arbitrary keys
for key, value in data_.iteritems():
if key not in skip:
items.append((key, value))
dump_func = dump_functions[format_]
dump_func(items, buf) | [
"def",
"dump_package_data",
"(",
"data",
",",
"buf",
",",
"format_",
"=",
"FileFormat",
".",
"py",
",",
"skip_attributes",
"=",
"None",
")",
":",
"if",
"format_",
"==",
"FileFormat",
".",
"txt",
":",
"raise",
"ValueError",
"(",
"\"'txt' format not supported fo... | Write package data to `buf`.
Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print. | [
"Write",
"package",
"data",
"to",
"buf",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_serialise.py#L97-L126 | train | 227,164 |
nerdvegas/rez | src/rez/vendor/distlib/_backport/sysconfig.py | get_config_vars | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _CONFIG_VARS
if _CONFIG_VARS is None:
_CONFIG_VARS = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# distutils2 module.
_CONFIG_VARS['prefix'] = _PREFIX
_CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
_CONFIG_VARS['py_version'] = _PY_VERSION
_CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
_CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
_CONFIG_VARS['base'] = _PREFIX
_CONFIG_VARS['platbase'] = _EXEC_PREFIX
_CONFIG_VARS['projectbase'] = _PROJECT_BASE
try:
_CONFIG_VARS['abiflags'] = sys.abiflags
except AttributeError:
# sys.abiflags may not be defined on all platforms.
_CONFIG_VARS['abiflags'] = ''
if os.name in ('nt', 'os2'):
_init_non_posix(_CONFIG_VARS)
if os.name == 'posix':
_init_posix(_CONFIG_VARS)
# Setting 'userbase' is done below the call to the
# init function to enable using 'get_config_var' in
# the init-function.
if sys.version >= '2.6':
_CONFIG_VARS['userbase'] = _getuserbase()
if 'srcdir' not in _CONFIG_VARS:
_CONFIG_VARS['srcdir'] = _PROJECT_BASE
else:
_CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir'])
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if _PYTHON_BUILD and os.name == "posix":
base = _PROJECT_BASE
try:
cwd = os.getcwd()
except OSError:
cwd = None
if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
base != cwd):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
_CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
kernel_version = os.uname()[2] # Kernel version (8.4.3)
major_version = int(kernel_version.split('.')[0])
if major_version < 8:
# On Mac OS X before 10.4, check if -arch and -isysroot
# are in CFLAGS or LDFLAGS and remove them if they are.
# This is needed when building extensions on a 10.3 system
# using a universal build of python.
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = re.sub('-isysroot [^ \t]*', ' ', flags)
_CONFIG_VARS[key] = flags
else:
# Allow the user to override the architecture flags using
# an environment variable.
# NOTE: This name was introduced by Apple in OSX 10.5 and
# is used by several scripting languages distributed with
# that OS release.
if 'ARCHFLAGS' in os.environ:
arch = os.environ['ARCHFLAGS']
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_CONFIG_VARS[key] = flags
# If we're on OSX 10.5 or later and the user tries to
# compiles an extension using an SDK that is not present
# on the current machine it is better to not use an SDK
# than to fail.
#
# The major usecase for this is users using a Python.org
# binary installer on OSX 10.6: that installer uses
# the 10.4u SDK, but that SDK is not installed by default
# when you install Xcode.
#
CFLAGS = _CONFIG_VARS.get('CFLAGS', '')
m = re.search('-isysroot\s+(\S+)', CFLAGS)
if m is not None:
sdk = m.group(1)
if not os.path.exists(sdk):
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
_CONFIG_VARS[key] = flags
if args:
vals = []
for name in args:
vals.append(_CONFIG_VARS.get(name))
return vals
else:
return _CONFIG_VARS | python | def get_config_vars(*args):
"""With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary.
"""
global _CONFIG_VARS
if _CONFIG_VARS is None:
_CONFIG_VARS = {}
# Normalized versions of prefix and exec_prefix are handy to have;
# in fact, these are the standard versions used most places in the
# distutils2 module.
_CONFIG_VARS['prefix'] = _PREFIX
_CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX
_CONFIG_VARS['py_version'] = _PY_VERSION
_CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT
_CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2]
_CONFIG_VARS['base'] = _PREFIX
_CONFIG_VARS['platbase'] = _EXEC_PREFIX
_CONFIG_VARS['projectbase'] = _PROJECT_BASE
try:
_CONFIG_VARS['abiflags'] = sys.abiflags
except AttributeError:
# sys.abiflags may not be defined on all platforms.
_CONFIG_VARS['abiflags'] = ''
if os.name in ('nt', 'os2'):
_init_non_posix(_CONFIG_VARS)
if os.name == 'posix':
_init_posix(_CONFIG_VARS)
# Setting 'userbase' is done below the call to the
# init function to enable using 'get_config_var' in
# the init-function.
if sys.version >= '2.6':
_CONFIG_VARS['userbase'] = _getuserbase()
if 'srcdir' not in _CONFIG_VARS:
_CONFIG_VARS['srcdir'] = _PROJECT_BASE
else:
_CONFIG_VARS['srcdir'] = _safe_realpath(_CONFIG_VARS['srcdir'])
# Convert srcdir into an absolute path if it appears necessary.
# Normally it is relative to the build directory. However, during
# testing, for example, we might be running a non-installed python
# from a different directory.
if _PYTHON_BUILD and os.name == "posix":
base = _PROJECT_BASE
try:
cwd = os.getcwd()
except OSError:
cwd = None
if (not os.path.isabs(_CONFIG_VARS['srcdir']) and
base != cwd):
# srcdir is relative and we are not in the same directory
# as the executable. Assume executable is in the build
# directory and make srcdir absolute.
srcdir = os.path.join(base, _CONFIG_VARS['srcdir'])
_CONFIG_VARS['srcdir'] = os.path.normpath(srcdir)
if sys.platform == 'darwin':
kernel_version = os.uname()[2] # Kernel version (8.4.3)
major_version = int(kernel_version.split('.')[0])
if major_version < 8:
# On Mac OS X before 10.4, check if -arch and -isysroot
# are in CFLAGS or LDFLAGS and remove them if they are.
# This is needed when building extensions on a 10.3 system
# using a universal build of python.
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = re.sub('-isysroot [^ \t]*', ' ', flags)
_CONFIG_VARS[key] = flags
else:
# Allow the user to override the architecture flags using
# an environment variable.
# NOTE: This name was introduced by Apple in OSX 10.5 and
# is used by several scripting languages distributed with
# that OS release.
if 'ARCHFLAGS' in os.environ:
arch = os.environ['ARCHFLAGS']
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-arch\s+\w+\s', ' ', flags)
flags = flags + ' ' + arch
_CONFIG_VARS[key] = flags
# If we're on OSX 10.5 or later and the user tries to
# compiles an extension using an SDK that is not present
# on the current machine it is better to not use an SDK
# than to fail.
#
# The major usecase for this is users using a Python.org
# binary installer on OSX 10.6: that installer uses
# the 10.4u SDK, but that SDK is not installed by default
# when you install Xcode.
#
CFLAGS = _CONFIG_VARS.get('CFLAGS', '')
m = re.search('-isysroot\s+(\S+)', CFLAGS)
if m is not None:
sdk = m.group(1)
if not os.path.exists(sdk):
for key in ('LDFLAGS', 'BASECFLAGS',
# a number of derived variables. These need to be
# patched up as well.
'CFLAGS', 'PY_CFLAGS', 'BLDSHARED'):
flags = _CONFIG_VARS[key]
flags = re.sub('-isysroot\s+\S+(\s|$)', ' ', flags)
_CONFIG_VARS[key] = flags
if args:
vals = []
for name in args:
vals.append(_CONFIG_VARS.get(name))
return vals
else:
return _CONFIG_VARS | [
"def",
"get_config_vars",
"(",
"*",
"args",
")",
":",
"global",
"_CONFIG_VARS",
"if",
"_CONFIG_VARS",
"is",
"None",
":",
"_CONFIG_VARS",
"=",
"{",
"}",
"# Normalized versions of prefix and exec_prefix are handy to have;",
"# in fact, these are the standard versions used most pl... | With no arguments, return a dictionary of all configuration
variables relevant for the current platform.
On Unix, this means every variable defined in Python's installed Makefile;
On Windows and Mac OS it's a much smaller set.
With arguments, return a list of values that result from looking up
each argument in the configuration variable dictionary. | [
"With",
"no",
"arguments",
"return",
"a",
"dictionary",
"of",
"all",
"configuration",
"variables",
"relevant",
"for",
"the",
"current",
"platform",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/_backport/sysconfig.py#L463-L591 | train | 227,165 |
nerdvegas/rez | src/support/package_utils/set_authors.py | set_authors | def set_authors(data):
"""Add 'authors' attribute based on repo contributions
"""
if "authors" in data:
return
shfile = os.path.join(os.path.dirname(__file__), "get_committers.sh")
p = subprocess.Popen(["bash", shfile], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode:
return
authors = out.strip().split('\n')
authors = [x.strip() for x in authors]
data["authors"] = authors | python | def set_authors(data):
"""Add 'authors' attribute based on repo contributions
"""
if "authors" in data:
return
shfile = os.path.join(os.path.dirname(__file__), "get_committers.sh")
p = subprocess.Popen(["bash", shfile], stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode:
return
authors = out.strip().split('\n')
authors = [x.strip() for x in authors]
data["authors"] = authors | [
"def",
"set_authors",
"(",
"data",
")",
":",
"if",
"\"authors\"",
"in",
"data",
":",
"return",
"shfile",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"\"get_committers.sh\"",
")",
"p",
"=",
"... | Add 'authors' attribute based on repo contributions | [
"Add",
"authors",
"attribute",
"based",
"on",
"repo",
"contributions"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/support/package_utils/set_authors.py#L5-L21 | train | 227,166 |
nerdvegas/rez | src/rez/package_maker__.py | make_package | def make_package(name, path, make_base=None, make_root=None, skip_existing=True,
warn_on_skip=True):
"""Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any.
"""
maker = PackageMaker(name)
yield maker
# post-with-block:
#
package = maker.get_package()
cwd = os.getcwd()
src_variants = []
# skip those variants that already exist
if skip_existing:
for variant in package.iter_variants():
variant_ = variant.install(path, dry_run=True)
if variant_ is None:
src_variants.append(variant)
else:
maker.skipped_variants.append(variant_)
if warn_on_skip:
print_warning("Skipping installation: Package variant already "
"exists: %s" % variant_.uri)
else:
src_variants = package.iter_variants()
with retain_cwd():
# install the package variant(s) into the filesystem package repo at `path`
for variant in src_variants:
variant_ = variant.install(path)
base = variant_.base
if make_base and base:
if not os.path.exists(base):
os.makedirs(base)
os.chdir(base)
make_base(variant_, base)
root = variant_.root
if make_root and root:
if not os.path.exists(root):
os.makedirs(root)
os.chdir(root)
make_root(variant_, root)
maker.installed_variants.append(variant_) | python | def make_package(name, path, make_base=None, make_root=None, skip_existing=True,
warn_on_skip=True):
"""Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any.
"""
maker = PackageMaker(name)
yield maker
# post-with-block:
#
package = maker.get_package()
cwd = os.getcwd()
src_variants = []
# skip those variants that already exist
if skip_existing:
for variant in package.iter_variants():
variant_ = variant.install(path, dry_run=True)
if variant_ is None:
src_variants.append(variant)
else:
maker.skipped_variants.append(variant_)
if warn_on_skip:
print_warning("Skipping installation: Package variant already "
"exists: %s" % variant_.uri)
else:
src_variants = package.iter_variants()
with retain_cwd():
# install the package variant(s) into the filesystem package repo at `path`
for variant in src_variants:
variant_ = variant.install(path)
base = variant_.base
if make_base and base:
if not os.path.exists(base):
os.makedirs(base)
os.chdir(base)
make_base(variant_, base)
root = variant_.root
if make_root and root:
if not os.path.exists(root):
os.makedirs(root)
os.chdir(root)
make_root(variant_, root)
maker.installed_variants.append(variant_) | [
"def",
"make_package",
"(",
"name",
",",
"path",
",",
"make_base",
"=",
"None",
",",
"make_root",
"=",
"None",
",",
"skip_existing",
"=",
"True",
",",
"warn_on_skip",
"=",
"True",
")",
":",
"maker",
"=",
"PackageMaker",
"(",
"name",
")",
"yield",
"maker"... | Make and install a package.
Example:
>>> def make_root(variant, path):
>>> os.symlink("/foo_payload/misc/python27", "ext")
>>>
>>> with make_package('foo', '/packages', make_root=make_root) as pkg:
>>> pkg.version = '1.0.0'
>>> pkg.description = 'does foo things'
>>> pkg.requires = ['python-2.7']
Args:
name (str): Package name.
path (str): Package repository path to install package into.
make_base (callable): Function that is used to create the package
payload, if applicable.
make_root (callable): Function that is used to create the package
variant payloads, if applicable.
skip_existing (bool): If True, detect if a variant already exists, and
skip with a warning message if so.
warn_on_skip (bool): If True, print warning when a variant is skipped.
Yields:
`PackageMaker` object.
Note:
Both `make_base` and `make_root` are called once per variant install,
and have the signature (variant, path).
Note:
The 'installed_variants' attribute on the `PackageMaker` instance will
be appended with variant(s) created by this function, if any. | [
"Make",
"and",
"install",
"a",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_maker__.py#L140-L219 | train | 227,167 |
nerdvegas/rez | src/rez/package_maker__.py | PackageMaker.get_package | def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
if "requires_rez_version" in package_data:
ver = package_data.pop("requires_rez_version")
if _rez_Version < ver:
raise PackageMetadataError(
"Failed reading package definition file: rez version >= %s "
"needed (current version is %s)" % (ver, _rez_Version))
# create a 'memory' package repository containing just this package
version_str = package_data.get("version") or "_NO_VERSION"
repo_data = {self.name: {version_str: package_data}}
repo = create_memory_package_repository(repo_data)
# retrieve the package from the new repository
family_resource = repo.get_package_family(self.name)
it = repo.iter_packages(family_resource)
package_resource = it.next()
package = self.package_cls(package_resource)
# revalidate the package for extra measure
package.validate_data()
return package | python | def get_package(self):
"""Create the analogous package.
Returns:
`Package` object.
"""
# get and validate package data
package_data = self._get_data()
package_data = package_schema.validate(package_data)
# check compatibility with rez version
if "requires_rez_version" in package_data:
ver = package_data.pop("requires_rez_version")
if _rez_Version < ver:
raise PackageMetadataError(
"Failed reading package definition file: rez version >= %s "
"needed (current version is %s)" % (ver, _rez_Version))
# create a 'memory' package repository containing just this package
version_str = package_data.get("version") or "_NO_VERSION"
repo_data = {self.name: {version_str: package_data}}
repo = create_memory_package_repository(repo_data)
# retrieve the package from the new repository
family_resource = repo.get_package_family(self.name)
it = repo.iter_packages(family_resource)
package_resource = it.next()
package = self.package_cls(package_resource)
# revalidate the package for extra measure
package.validate_data()
return package | [
"def",
"get_package",
"(",
"self",
")",
":",
"# get and validate package data",
"package_data",
"=",
"self",
".",
"_get_data",
"(",
")",
"package_data",
"=",
"package_schema",
".",
"validate",
"(",
"package_data",
")",
"# check compatibility with rez version",
"if",
"... | Create the analogous package.
Returns:
`Package` object. | [
"Create",
"the",
"analogous",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_maker__.py#L93-L126 | train | 227,168 |
nerdvegas/rez | src/rez/vendor/pyparsing/pyparsing.py | getTokensEndLoc | def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in fstack[2:]:
if f[3] == "_parseNoCache":
endloc = f[0].f_locals["loc"]
return endloc
else:
raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack | python | def getTokensEndLoc():
"""Method to be called from within a parse action to determine the end
location of the parsed tokens."""
import inspect
fstack = inspect.stack()
try:
# search up the stack (through intervening argument normalizers) for correct calling routine
for f in fstack[2:]:
if f[3] == "_parseNoCache":
endloc = f[0].f_locals["loc"]
return endloc
else:
raise ParseFatalException("incorrect usage of getTokensEndLoc - may only be called from within a parse action")
finally:
del fstack | [
"def",
"getTokensEndLoc",
"(",
")",
":",
"import",
"inspect",
"fstack",
"=",
"inspect",
".",
"stack",
"(",
")",
"try",
":",
"# search up the stack (through intervening argument normalizers) for correct calling routine\r",
"for",
"f",
"in",
"fstack",
"[",
"2",
":",
"]"... | Method to be called from within a parse action to determine the end
location of the parsed tokens. | [
"Method",
"to",
"be",
"called",
"from",
"within",
"a",
"parse",
"action",
"to",
"determine",
"the",
"end",
"location",
"of",
"the",
"parsed",
"tokens",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pyparsing/pyparsing.py#L3350-L3364 | train | 227,169 |
nerdvegas/rez | src/rez/utils/schema.py | schema_keys | def schema_keys(schema):
"""Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring})
"""
def _get_leaf(value):
if isinstance(value, Schema):
return _get_leaf(value._schema)
return value
keys = set()
dict_ = schema._schema
assert isinstance(dict_, dict)
for key in dict_.iterkeys():
key_ = _get_leaf(key)
if isinstance(key_, basestring):
keys.add(key_)
return keys | python | def schema_keys(schema):
"""Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring})
"""
def _get_leaf(value):
if isinstance(value, Schema):
return _get_leaf(value._schema)
return value
keys = set()
dict_ = schema._schema
assert isinstance(dict_, dict)
for key in dict_.iterkeys():
key_ = _get_leaf(key)
if isinstance(key_, basestring):
keys.add(key_)
return keys | [
"def",
"schema_keys",
"(",
"schema",
")",
":",
"def",
"_get_leaf",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Schema",
")",
":",
"return",
"_get_leaf",
"(",
"value",
".",
"_schema",
")",
"return",
"value",
"keys",
"=",
"set",
"(",
... | Get the string values of keys in a dict-based schema.
Non-string keys are ignored.
Returns:
Set of string keys of a schema which is in the form (eg):
schema = Schema({Required("foo"): int,
Optional("bah"): basestring}) | [
"Get",
"the",
"string",
"values",
"of",
"keys",
"in",
"a",
"dict",
"-",
"based",
"schema",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/schema.py#L12-L37 | train | 227,170 |
nerdvegas/rez | src/rez/utils/schema.py | dict_to_schema | def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None):
"""Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object.
"""
if modifier:
modifier = Use(modifier)
def _to(value):
if isinstance(value, dict):
d = {}
for k, v in value.iteritems():
if isinstance(k, basestring):
k = Required(k) if required else Optional(k)
d[k] = _to(v)
if allow_custom_keys:
d[Optional(basestring)] = modifier or object
schema = Schema(d)
elif modifier:
schema = And(value, modifier)
else:
schema = value
return schema
return _to(schema_dict) | python | def dict_to_schema(schema_dict, required, allow_custom_keys=True, modifier=None):
"""Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object.
"""
if modifier:
modifier = Use(modifier)
def _to(value):
if isinstance(value, dict):
d = {}
for k, v in value.iteritems():
if isinstance(k, basestring):
k = Required(k) if required else Optional(k)
d[k] = _to(v)
if allow_custom_keys:
d[Optional(basestring)] = modifier or object
schema = Schema(d)
elif modifier:
schema = And(value, modifier)
else:
schema = value
return schema
return _to(schema_dict) | [
"def",
"dict_to_schema",
"(",
"schema_dict",
",",
"required",
",",
"allow_custom_keys",
"=",
"True",
",",
"modifier",
"=",
"None",
")",
":",
"if",
"modifier",
":",
"modifier",
"=",
"Use",
"(",
"modifier",
")",
"def",
"_to",
"(",
"value",
")",
":",
"if",
... | Convert a dict of Schemas into a Schema.
Args:
required (bool): Whether to make schema keys optional or required.
allow_custom_keys (bool, optional): If True, creates a schema that
allows custom items in dicts.
modifier (callable): Functor to apply to dict values - it is applied
via `Schema.Use`.
Returns:
A `Schema` object. | [
"Convert",
"a",
"dict",
"of",
"Schemas",
"into",
"a",
"Schema",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/schema.py#L40-L72 | train | 227,171 |
nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.enter_diff_mode | def enter_diff_mode(self, context_model=None):
"""Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used.
"""
assert not self.diff_mode
self.diff_mode = True
if context_model is None:
self.diff_from_source = True
self.diff_context_model = self.context_model.copy()
else:
self.diff_from_source = False
self.diff_context_model = context_model
self.clear()
self.setColumnCount(5)
self.refresh() | python | def enter_diff_mode(self, context_model=None):
"""Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used.
"""
assert not self.diff_mode
self.diff_mode = True
if context_model is None:
self.diff_from_source = True
self.diff_context_model = self.context_model.copy()
else:
self.diff_from_source = False
self.diff_context_model = context_model
self.clear()
self.setColumnCount(5)
self.refresh() | [
"def",
"enter_diff_mode",
"(",
"self",
",",
"context_model",
"=",
"None",
")",
":",
"assert",
"not",
"self",
".",
"diff_mode",
"self",
".",
"diff_mode",
"=",
"True",
"if",
"context_model",
"is",
"None",
":",
"self",
".",
"diff_from_source",
"=",
"True",
"s... | Enter diff mode.
Args:
context_model (`ContextModel`): Context to diff against. If None, a
copy of the current context is used. | [
"Enter",
"diff",
"mode",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L349-L368 | train | 227,172 |
nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.leave_diff_mode | def leave_diff_mode(self):
"""Leave diff mode."""
assert self.diff_mode
self.diff_mode = False
self.diff_context_model = None
self.diff_from_source = False
self.setColumnCount(2)
self.refresh() | python | def leave_diff_mode(self):
"""Leave diff mode."""
assert self.diff_mode
self.diff_mode = False
self.diff_context_model = None
self.diff_from_source = False
self.setColumnCount(2)
self.refresh() | [
"def",
"leave_diff_mode",
"(",
"self",
")",
":",
"assert",
"self",
".",
"diff_mode",
"self",
".",
"diff_mode",
"=",
"False",
"self",
".",
"diff_context_model",
"=",
"None",
"self",
".",
"diff_from_source",
"=",
"False",
"self",
".",
"setColumnCount",
"(",
"2... | Leave diff mode. | [
"Leave",
"diff",
"mode",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L370-L377 | train | 227,173 |
nerdvegas/rez | src/rezgui/widgets/ContextTableWidget.py | ContextTableWidget.get_title | def get_title(self):
"""Returns a string suitable for titling a window containing this table."""
def _title(context_model):
context = context_model.context()
if context is None:
return "new context*"
title = os.path.basename(context.load_path) if context.load_path \
else "new context"
if context_model.is_modified():
title += '*'
return title
if self.diff_mode:
diff_title = _title(self.diff_context_model)
if self.diff_from_source:
diff_title += "'"
return "%s %s %s" % (_title(self.context_model),
self.short_double_arrow, diff_title)
else:
return _title(self.context_model) | python | def get_title(self):
"""Returns a string suitable for titling a window containing this table."""
def _title(context_model):
context = context_model.context()
if context is None:
return "new context*"
title = os.path.basename(context.load_path) if context.load_path \
else "new context"
if context_model.is_modified():
title += '*'
return title
if self.diff_mode:
diff_title = _title(self.diff_context_model)
if self.diff_from_source:
diff_title += "'"
return "%s %s %s" % (_title(self.context_model),
self.short_double_arrow, diff_title)
else:
return _title(self.context_model) | [
"def",
"get_title",
"(",
"self",
")",
":",
"def",
"_title",
"(",
"context_model",
")",
":",
"context",
"=",
"context_model",
".",
"context",
"(",
")",
"if",
"context",
"is",
"None",
":",
"return",
"\"new context*\"",
"title",
"=",
"os",
".",
"path",
".",... | Returns a string suitable for titling a window containing this table. | [
"Returns",
"a",
"string",
"suitable",
"for",
"titling",
"a",
"window",
"containing",
"this",
"table",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ContextTableWidget.py#L390-L409 | train | 227,174 |
nerdvegas/rez | src/rez/utils/colorize.py | _color_level | def _color_level(str_, level):
""" Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences.
"""
fore_color, back_color, styles = _get_style_from_config(level)
return _color(str_, fore_color, back_color, styles) | python | def _color_level(str_, level):
""" Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences.
"""
fore_color, back_color, styles = _get_style_from_config(level)
return _color(str_, fore_color, back_color, styles) | [
"def",
"_color_level",
"(",
"str_",
",",
"level",
")",
":",
"fore_color",
",",
"back_color",
",",
"styles",
"=",
"_get_style_from_config",
"(",
"level",
")",
"return",
"_color",
"(",
"str_",
",",
"fore_color",
",",
"back_color",
",",
"styles",
")"
] | Return the string wrapped with the appropriate styling for the message
level. The styling will be determined based on the rez configuration.
Args:
str_ (str): The string to be wrapped.
level (str): The message level. Should be one of 'critical', 'error',
'warning', 'info' or 'debug'.
Returns:
str: The string styled with the appropriate escape sequences. | [
"Return",
"the",
"string",
"wrapped",
"with",
"the",
"appropriate",
"styling",
"for",
"the",
"message",
"level",
".",
"The",
"styling",
"will",
"be",
"determined",
"based",
"on",
"the",
"rez",
"configuration",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/colorize.py#L160-L173 | train | 227,175 |
nerdvegas/rez | src/rez/utils/colorize.py | _color | def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama
"""
# TODO: Colorama is documented to work on Windows and trivial test case
# proves this to be the case, but it doesn't work in Rez. If the initialise
# is called in sec/rez/__init__.py then it does work, however as discussed
# in the following comment this is not always desirable. So until we can
# work out why we forcibly turn it off.
if not config.get("color_enabled", False) or platform_.name == "windows":
return str_
# lazily init colorama. This is important - we don't want to init at startup,
# because colorama prints a RESET_ALL character atexit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
_init_colorama()
colored = ""
if not styles:
styles = []
if fore_color:
colored += getattr(colorama.Fore, fore_color.upper(), '')
if back_color:
colored += getattr(colorama.Back, back_color.upper(), '')
for style in styles:
colored += getattr(colorama.Style, style.upper(), '')
return colored + str_ + colorama.Style.RESET_ALL | python | def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama
"""
# TODO: Colorama is documented to work on Windows and trivial test case
# proves this to be the case, but it doesn't work in Rez. If the initialise
# is called in sec/rez/__init__.py then it does work, however as discussed
# in the following comment this is not always desirable. So until we can
# work out why we forcibly turn it off.
if not config.get("color_enabled", False) or platform_.name == "windows":
return str_
# lazily init colorama. This is important - we don't want to init at startup,
# because colorama prints a RESET_ALL character atexit. This in turn adds
# unexpected output when capturing the output of a command run in a
# ResolvedContext, for example.
_init_colorama()
colored = ""
if not styles:
styles = []
if fore_color:
colored += getattr(colorama.Fore, fore_color.upper(), '')
if back_color:
colored += getattr(colorama.Back, back_color.upper(), '')
for style in styles:
colored += getattr(colorama.Style, style.upper(), '')
return colored + str_ + colorama.Style.RESET_ALL | [
"def",
"_color",
"(",
"str_",
",",
"fore_color",
"=",
"None",
",",
"back_color",
"=",
"None",
",",
"styles",
"=",
"None",
")",
":",
"# TODO: Colorama is documented to work on Windows and trivial test case",
"# proves this to be the case, but it doesn't work in Rez. If the init... | Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ module.
styles (list of str, optional): Any styles supported by the `Colorama`_
module.
Returns:
str: The string styled with the appropriate escape sequences.
.. _Colorama:
https://pypi.python.org/pypi/colorama | [
"Return",
"the",
"string",
"wrapped",
"with",
"the",
"appropriate",
"styling",
"escape",
"sequences",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/colorize.py#L176-L219 | train | 227,176 |
nerdvegas/rez | src/rez/utils/sourcecode.py | late | def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function.
"""
from rez.package_resources_ import package_rex_keys
def decorated(fn):
# this is done here rather than in standard schema validation because
# the latter causes a very obfuscated error message
if fn.__name__ in package_rex_keys:
raise ValueError("Cannot use @late decorator on function '%s'"
% fn.__name__)
setattr(fn, "_late", True)
_add_decorator(fn, "late")
return fn
return decorated | python | def late():
"""Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function.
"""
from rez.package_resources_ import package_rex_keys
def decorated(fn):
# this is done here rather than in standard schema validation because
# the latter causes a very obfuscated error message
if fn.__name__ in package_rex_keys:
raise ValueError("Cannot use @late decorator on function '%s'"
% fn.__name__)
setattr(fn, "_late", True)
_add_decorator(fn, "late")
return fn
return decorated | [
"def",
"late",
"(",
")",
":",
"from",
"rez",
".",
"package_resources_",
"import",
"package_rex_keys",
"def",
"decorated",
"(",
"fn",
")",
":",
"# this is done here rather than in standard schema validation because",
"# the latter causes a very obfuscated error message",
"if",
... | Used by functions in package.py that are evaluated lazily.
The term 'late' refers to the fact these package attributes are evaluated
late, ie when the attribute is queried for the first time.
If you want to implement a package.py attribute as a function, you MUST use
this decorator - otherwise it is understood that you want your attribute to
be a function, not the return value of that function. | [
"Used",
"by",
"functions",
"in",
"package",
".",
"py",
"that",
"are",
"evaluated",
"lazily",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/sourcecode.py#L25-L49 | train | 227,177 |
nerdvegas/rez | src/rez/utils/sourcecode.py | include | def include(module_name, *module_names):
"""Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
"""
def decorated(fn):
_add_decorator(fn, "include", nargs=[module_name] + list(module_names))
return fn
return decorated | python | def include(module_name, *module_names):
"""Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info.
"""
def decorated(fn):
_add_decorator(fn, "include", nargs=[module_name] + list(module_names))
return fn
return decorated | [
"def",
"include",
"(",
"module_name",
",",
"*",
"module_names",
")",
":",
"def",
"decorated",
"(",
"fn",
")",
":",
"_add_decorator",
"(",
"fn",
",",
"\"include\"",
",",
"nargs",
"=",
"[",
"module_name",
"]",
"+",
"list",
"(",
"module_names",
")",
")",
... | Used by functions in package.py to have access to named modules.
See the 'package_definition_python_path' config setting for more info. | [
"Used",
"by",
"functions",
"in",
"package",
".",
"py",
"to",
"have",
"access",
"to",
"named",
"modules",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/sourcecode.py#L52-L61 | train | 227,178 |
nerdvegas/rez | src/rez/packages_.py | iter_package_families | def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator.
"""
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
yield PackageFamily(resource) | python | def iter_package_families(paths=None):
"""Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator.
"""
for path in (paths or config.packages_path):
repo = package_repository_manager.get_repository(path)
for resource in repo.iter_package_families():
yield PackageFamily(resource) | [
"def",
"iter_package_families",
"(",
"paths",
"=",
"None",
")",
":",
"for",
"path",
"in",
"(",
"paths",
"or",
"config",
".",
"packages_path",
")",
":",
"repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"path",
")",
"for",
"resource",
"in... | Iterate over package families, in no particular order.
Note that multiple package families with the same name can be returned.
Unlike packages, families later in the searchpath are not hidden by earlier
families.
Args:
paths (list of str, optional): paths to search for package families,
defaults to `config.packages_path`.
Returns:
`PackageFamily` iterator. | [
"Iterate",
"over",
"package",
"families",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L465-L482 | train | 227,179 |
nerdvegas/rez | src/rez/packages_.py | iter_packages | def iter_packages(name, range_=None, paths=None):
"""Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
entries = _get_families(name, paths)
seen = set()
for repo, family_resource in entries:
for package_resource in repo.iter_packages(family_resource):
key = (package_resource.name, package_resource.version)
if key in seen:
continue
seen.add(key)
if range_:
if isinstance(range_, basestring):
range_ = VersionRange(range_)
if package_resource.version not in range_:
continue
yield Package(package_resource) | python | def iter_packages(name, range_=None, paths=None):
"""Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator.
"""
entries = _get_families(name, paths)
seen = set()
for repo, family_resource in entries:
for package_resource in repo.iter_packages(family_resource):
key = (package_resource.name, package_resource.version)
if key in seen:
continue
seen.add(key)
if range_:
if isinstance(range_, basestring):
range_ = VersionRange(range_)
if package_resource.version not in range_:
continue
yield Package(package_resource) | [
"def",
"iter_packages",
"(",
"name",
",",
"range_",
"=",
"None",
",",
"paths",
"=",
"None",
")",
":",
"entries",
"=",
"_get_families",
"(",
"name",
",",
"paths",
")",
"seen",
"=",
"set",
"(",
")",
"for",
"repo",
",",
"family_resource",
"in",
"entries",... | Iterate over `Package` instances, in no particular order.
Packages of the same name and version earlier in the search path take
precedence - equivalent packages later in the paths are ignored. Packages
are not returned in any specific order.
Args:
name (str): Name of the package, eg 'maya'.
range_ (VersionRange or str): If provided, limits the versions returned
to those in `range_`.
paths (list of str, optional): paths to search for packages, defaults
to `config.packages_path`.
Returns:
`Package` iterator. | [
"Iterate",
"over",
"Package",
"instances",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L485-L518 | train | 227,180 |
nerdvegas/rez | src/rez/packages_.py | get_package | def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found.
"""
if isinstance(version, basestring):
range_ = VersionRange("==%s" % version)
else:
range_ = VersionRange.from_version(version, "==")
it = iter_packages(name, range_, paths)
try:
return it.next()
except StopIteration:
return None | python | def get_package(name, version, paths=None):
"""Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found.
"""
if isinstance(version, basestring):
range_ = VersionRange("==%s" % version)
else:
range_ = VersionRange.from_version(version, "==")
it = iter_packages(name, range_, paths)
try:
return it.next()
except StopIteration:
return None | [
"def",
"get_package",
"(",
"name",
",",
"version",
",",
"paths",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"version",
",",
"basestring",
")",
":",
"range_",
"=",
"VersionRange",
"(",
"\"==%s\"",
"%",
"version",
")",
"else",
":",
"range_",
"=",
"V... | Get an exact version of a package.
Args:
name (str): Name of the package, eg 'maya'.
version (Version or str): Version of the package, eg '1.0.0'
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` object, or None if the package was not found. | [
"Get",
"an",
"exact",
"version",
"of",
"a",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L521-L542 | train | 227,181 |
nerdvegas/rez | src/rez/packages_.py | get_package_from_string | def get_package_from_string(txt, paths=None):
"""Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found.
"""
o = VersionedObject(txt)
return get_package(o.name, o.version, paths=paths) | python | def get_package_from_string(txt, paths=None):
"""Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found.
"""
o = VersionedObject(txt)
return get_package(o.name, o.version, paths=paths) | [
"def",
"get_package_from_string",
"(",
"txt",
",",
"paths",
"=",
"None",
")",
":",
"o",
"=",
"VersionedObject",
"(",
"txt",
")",
"return",
"get_package",
"(",
"o",
".",
"name",
",",
"o",
".",
"version",
",",
"paths",
"=",
"paths",
")"
] | Get a package given a string.
Args:
txt (str): String such as 'foo', 'bah-1.3'.
paths (list of str, optional): paths to search for package, defaults
to `config.packages_path`.
Returns:
`Package` instance, or None if no package was found. | [
"Get",
"a",
"package",
"given",
"a",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L563-L575 | train | 227,182 |
nerdvegas/rez | src/rez/packages_.py | get_developer_package | def get_developer_package(path, format=None):
"""Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`.
"""
from rez.developer_package import DeveloperPackage
return DeveloperPackage.from_path(path, format=format) | python | def get_developer_package(path, format=None):
"""Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`.
"""
from rez.developer_package import DeveloperPackage
return DeveloperPackage.from_path(path, format=format) | [
"def",
"get_developer_package",
"(",
"path",
",",
"format",
"=",
"None",
")",
":",
"from",
"rez",
".",
"developer_package",
"import",
"DeveloperPackage",
"return",
"DeveloperPackage",
".",
"from_path",
"(",
"path",
",",
"format",
"=",
"format",
")"
] | Create a developer package.
Args:
path (str): Path to dir containing package definition file.
format (str): Package definition file format, detected if None.
Returns:
`DeveloperPackage`. | [
"Create",
"a",
"developer",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L578-L589 | train | 227,183 |
nerdvegas/rez | src/rez/packages_.py | create_package | def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
maker = PackageMaker(name, data, package_cls=package_cls)
return maker.get_package() | python | def create_package(name, data, package_cls=None):
"""Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object.
"""
from rez.package_maker__ import PackageMaker
maker = PackageMaker(name, data, package_cls=package_cls)
return maker.get_package() | [
"def",
"create_package",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"None",
")",
":",
"from",
"rez",
".",
"package_maker__",
"import",
"PackageMaker",
"maker",
"=",
"PackageMaker",
"(",
"name",
",",
"data",
",",
"package_cls",
"=",
"package_cls",
")"... | Create a package given package data.
Args:
name (str): Package name.
data (dict): Package data. Must conform to `package_maker.package_schema`.
Returns:
`Package` object. | [
"Create",
"a",
"package",
"given",
"package",
"data",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L592-L604 | train | 227,184 |
nerdvegas/rez | src/rez/packages_.py | get_last_release_time | def get_last_release_time(name, paths=None):
"""Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined.
"""
entries = _get_families(name, paths)
max_time = 0
for repo, family_resource in entries:
time_ = repo.get_last_release_time(family_resource)
if time_ == 0:
return 0
max_time = max(max_time, time_)
return max_time | python | def get_last_release_time(name, paths=None):
"""Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined.
"""
entries = _get_families(name, paths)
max_time = 0
for repo, family_resource in entries:
time_ = repo.get_last_release_time(family_resource)
if time_ == 0:
return 0
max_time = max(max_time, time_)
return max_time | [
"def",
"get_last_release_time",
"(",
"name",
",",
"paths",
"=",
"None",
")",
":",
"entries",
"=",
"_get_families",
"(",
"name",
",",
"paths",
")",
"max_time",
"=",
"0",
"for",
"repo",
",",
"family_resource",
"in",
"entries",
":",
"time_",
"=",
"repo",
".... | Returns the most recent time this package was released.
Note that releasing a variant into an already-released package is also
considered a package release.
Returns:
int: Epoch time of last package release, or zero if this cannot be
determined. | [
"Returns",
"the",
"most",
"recent",
"time",
"this",
"package",
"was",
"released",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L628-L646 | train | 227,185 |
nerdvegas/rez | src/rez/packages_.py | get_completions | def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty.
"""
op = None
if prefix:
if prefix[0] in ('!', '~'):
if family_only:
return set()
op = prefix[0]
prefix = prefix[1:]
fam = None
for ch in ('-', '@', '#'):
if ch in prefix:
if family_only:
return set()
fam = prefix.split(ch)[0]
break
words = set()
if not fam:
words = set(x.name for x in iter_package_families(paths=paths)
if x.name.startswith(prefix))
if len(words) == 1:
fam = iter(words).next()
if family_only:
return words
if fam:
it = iter_packages(fam, paths=paths)
words.update(x.qualified_name for x in it
if x.qualified_name.startswith(prefix))
if op:
words = set(op + x for x in words)
return words | python | def get_completions(prefix, paths=None, family_only=False):
"""Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty.
"""
op = None
if prefix:
if prefix[0] in ('!', '~'):
if family_only:
return set()
op = prefix[0]
prefix = prefix[1:]
fam = None
for ch in ('-', '@', '#'):
if ch in prefix:
if family_only:
return set()
fam = prefix.split(ch)[0]
break
words = set()
if not fam:
words = set(x.name for x in iter_package_families(paths=paths)
if x.name.startswith(prefix))
if len(words) == 1:
fam = iter(words).next()
if family_only:
return words
if fam:
it = iter_packages(fam, paths=paths)
words.update(x.qualified_name for x in it
if x.qualified_name.startswith(prefix))
if op:
words = set(op + x for x in words)
return words | [
"def",
"get_completions",
"(",
"prefix",
",",
"paths",
"=",
"None",
",",
"family_only",
"=",
"False",
")",
":",
"op",
"=",
"None",
"if",
"prefix",
":",
"if",
"prefix",
"[",
"0",
"]",
"in",
"(",
"'!'",
",",
"'~'",
")",
":",
"if",
"family_only",
":",... | Get autocompletion options given a prefix string.
Example:
>>> get_completions("may")
set(["maya", "maya_utils"])
>>> get_completions("maya-")
set(["maya-2013.1", "maya-2015.0.sp1"])
Args:
prefix (str): Prefix to match.
paths (list of str): paths to search for packages, defaults to
`config.packages_path`.
family_only (bool): If True, only match package names, do not include
version component.
Returns:
Set of strings, may be empty. | [
"Get",
"autocompletion",
"options",
"given",
"a",
"prefix",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L649-L702 | train | 227,186 |
nerdvegas/rez | src/rez/packages_.py | PackageFamily.iter_packages | def iter_packages(self):
"""Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator.
"""
for package in self.repository.iter_packages(self.resource):
yield Package(package) | python | def iter_packages(self):
"""Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator.
"""
for package in self.repository.iter_packages(self.resource):
yield Package(package) | [
"def",
"iter_packages",
"(",
"self",
")",
":",
"for",
"package",
"in",
"self",
".",
"repository",
".",
"iter_packages",
"(",
"self",
".",
"resource",
")",
":",
"yield",
"Package",
"(",
"package",
")"
] | Iterate over the packages within this family, in no particular order.
Returns:
`Package` iterator. | [
"Iterate",
"over",
"the",
"packages",
"within",
"this",
"family",
"in",
"no",
"particular",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L55-L62 | train | 227,187 |
nerdvegas/rez | src/rez/packages_.py | PackageBaseResourceWrapper.is_local | def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | python | def is_local(self):
"""Returns True if the package is in the local package repository"""
local_repo = package_repository_manager.get_repository(
self.config.local_packages_path)
return (self.resource._repository.uid == local_repo.uid) | [
"def",
"is_local",
"(",
"self",
")",
":",
"local_repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"self",
".",
"config",
".",
"local_packages_path",
")",
"return",
"(",
"self",
".",
"resource",
".",
"_repository",
".",
"uid",
"==",
"local_... | Returns True if the package is in the local package repository | [
"Returns",
"True",
"if",
"the",
"package",
"is",
"in",
"the",
"local",
"package",
"repository"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L99-L103 | train | 227,188 |
nerdvegas/rez | src/rez/packages_.py | PackageBaseResourceWrapper.print_info | def print_info(self, buf=None, format_=FileFormat.yaml,
skip_attributes=None, include_release=False):
"""Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog'
"""
data = self.validated_data().copy()
# config is a special case. We only really want to show any config settings
# that were in the package.py, not the entire Config contents that get
# grafted onto the Package/Variant instance. However Variant has an empy
# 'data' dict property, since it forwards data from its parent package.
data.pop("config", None)
if self.config:
if isinstance(self, Package):
config_dict = self.data.get("config")
else:
config_dict = self.parent.data.get("config")
data["config"] = config_dict
if not include_release:
skip_attributes = list(skip_attributes or []) + list(package_release_keys)
buf = buf or sys.stdout
dump_package_data(data, buf=buf, format_=format_,
skip_attributes=skip_attributes) | python | def print_info(self, buf=None, format_=FileFormat.yaml,
skip_attributes=None, include_release=False):
"""Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog'
"""
data = self.validated_data().copy()
# config is a special case. We only really want to show any config settings
# that were in the package.py, not the entire Config contents that get
# grafted onto the Package/Variant instance. However Variant has an empy
# 'data' dict property, since it forwards data from its parent package.
data.pop("config", None)
if self.config:
if isinstance(self, Package):
config_dict = self.data.get("config")
else:
config_dict = self.parent.data.get("config")
data["config"] = config_dict
if not include_release:
skip_attributes = list(skip_attributes or []) + list(package_release_keys)
buf = buf or sys.stdout
dump_package_data(data, buf=buf, format_=format_,
skip_attributes=skip_attributes) | [
"def",
"print_info",
"(",
"self",
",",
"buf",
"=",
"None",
",",
"format_",
"=",
"FileFormat",
".",
"yaml",
",",
"skip_attributes",
"=",
"None",
",",
"include_release",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"validated_data",
"(",
")",
".",
"... | Print the contents of the package.
Args:
buf (file-like object): Stream to write to.
format_ (`FileFormat`): Format to write in.
skip_attributes (list of str): List of attributes to not print.
include_release (bool): If True, include release-related attributes,
such as 'timestamp' and 'changelog' | [
"Print",
"the",
"contents",
"of",
"the",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L105-L135 | train | 227,189 |
nerdvegas/rez | src/rez/packages_.py | Package.qualified_name | def qualified_name(self):
"""Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1".
"""
o = VersionedObject.construct(self.name, self.version)
return str(o) | python | def qualified_name(self):
"""Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1".
"""
o = VersionedObject.construct(self.name, self.version)
return str(o) | [
"def",
"qualified_name",
"(",
"self",
")",
":",
"o",
"=",
"VersionedObject",
".",
"construct",
"(",
"self",
".",
"name",
",",
"self",
".",
"version",
")",
"return",
"str",
"(",
"o",
")"
] | Get the qualified name of the package.
Returns:
str: Name of the package with version, eg "maya-2016.1". | [
"Get",
"the",
"qualified",
"name",
"of",
"the",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L218-L225 | train | 227,190 |
nerdvegas/rez | src/rez/packages_.py | Package.parent | def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None | python | def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None | [
"def",
"parent",
"(",
"self",
")",
":",
"family",
"=",
"self",
".",
"repository",
".",
"get_parent_package_family",
"(",
"self",
".",
"resource",
")",
"return",
"PackageFamily",
"(",
"family",
")",
"if",
"family",
"else",
"None"
] | Get the parent package family.
Returns:
`PackageFamily`. | [
"Get",
"the",
"parent",
"package",
"family",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L228-L235 | train | 227,191 |
nerdvegas/rez | src/rez/packages_.py | Package.iter_variants | def iter_variants(self):
"""Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator.
"""
for variant in self.repository.iter_variants(self.resource):
yield Variant(variant, context=self.context, parent=self) | python | def iter_variants(self):
"""Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator.
"""
for variant in self.repository.iter_variants(self.resource):
yield Variant(variant, context=self.context, parent=self) | [
"def",
"iter_variants",
"(",
"self",
")",
":",
"for",
"variant",
"in",
"self",
".",
"repository",
".",
"iter_variants",
"(",
"self",
".",
"resource",
")",
":",
"yield",
"Variant",
"(",
"variant",
",",
"context",
"=",
"self",
".",
"context",
",",
"parent"... | Iterate over the variants within this package, in index order.
Returns:
`Variant` iterator. | [
"Iterate",
"over",
"the",
"variants",
"within",
"this",
"package",
"in",
"index",
"order",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L250-L257 | train | 227,192 |
nerdvegas/rez | src/rez/packages_.py | Package.get_variant | def get_variant(self, index=None):
"""Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists.
"""
for variant in self.iter_variants():
if variant.index == index:
return variant | python | def get_variant(self, index=None):
"""Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists.
"""
for variant in self.iter_variants():
if variant.index == index:
return variant | [
"def",
"get_variant",
"(",
"self",
",",
"index",
"=",
"None",
")",
":",
"for",
"variant",
"in",
"self",
".",
"iter_variants",
"(",
")",
":",
"if",
"variant",
".",
"index",
"==",
"index",
":",
"return",
"variant"
] | Get the variant with the associated index.
Returns:
`Variant` object, or None if no variant with the given index exists. | [
"Get",
"the",
"variant",
"with",
"the",
"associated",
"index",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L259-L267 | train | 227,193 |
nerdvegas/rez | src/rez/packages_.py | Variant.qualified_name | def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr) | python | def qualified_name(self):
"""Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]".
"""
idxstr = '' if self.index is None else str(self.index)
return "%s[%s]" % (self.qualified_package_name, idxstr) | [
"def",
"qualified_name",
"(",
"self",
")",
":",
"idxstr",
"=",
"''",
"if",
"self",
".",
"index",
"is",
"None",
"else",
"str",
"(",
"self",
".",
"index",
")",
"return",
"\"%s[%s]\"",
"%",
"(",
"self",
".",
"qualified_package_name",
",",
"idxstr",
")"
] | Get the qualified name of the variant.
Returns:
str: Name of the variant with version and index, eg "maya-2016.1[1]". | [
"Get",
"the",
"qualified",
"name",
"of",
"the",
"variant",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L305-L312 | train | 227,194 |
nerdvegas/rez | src/rez/packages_.py | Variant.parent | def parent(self):
"""Get the parent package.
Returns:
`Package`.
"""
if self._parent is not None:
return self._parent
try:
package = self.repository.get_parent_package(self.resource)
self._parent = Package(package, context=self.context)
except AttributeError as e:
reraise(e, ValueError)
return self._parent | python | def parent(self):
"""Get the parent package.
Returns:
`Package`.
"""
if self._parent is not None:
return self._parent
try:
package = self.repository.get_parent_package(self.resource)
self._parent = Package(package, context=self.context)
except AttributeError as e:
reraise(e, ValueError)
return self._parent | [
"def",
"parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_parent",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_parent",
"try",
":",
"package",
"=",
"self",
".",
"repository",
".",
"get_parent_package",
"(",
"self",
".",
"resource",
")",
"self... | Get the parent package.
Returns:
`Package`. | [
"Get",
"the",
"parent",
"package",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L315-L330 | train | 227,195 |
nerdvegas/rez | src/rez/packages_.py | Variant.get_requires | def get_requires(self, build_requires=False, private_build_requires=False):
"""Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects.
"""
requires = self.requires or []
if build_requires:
requires = requires + (self.build_requires or [])
if private_build_requires:
requires = requires + (self.private_build_requires or [])
return requires | python | def get_requires(self, build_requires=False, private_build_requires=False):
"""Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects.
"""
requires = self.requires or []
if build_requires:
requires = requires + (self.build_requires or [])
if private_build_requires:
requires = requires + (self.private_build_requires or [])
return requires | [
"def",
"get_requires",
"(",
"self",
",",
"build_requires",
"=",
"False",
",",
"private_build_requires",
"=",
"False",
")",
":",
"requires",
"=",
"self",
".",
"requires",
"or",
"[",
"]",
"if",
"build_requires",
":",
"requires",
"=",
"requires",
"+",
"(",
"s... | Get the requirements of the variant.
Args:
build_requires (bool): If True, include build requirements.
private_build_requires (bool): If True, include private build
requirements.
Returns:
List of `Requirement` objects. | [
"Get",
"the",
"requirements",
"of",
"the",
"variant",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L358-L376 | train | 227,196 |
nerdvegas/rez | src/rez/packages_.py | Variant.install | def install(self, path, dry_run=False, overrides=None):
"""Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned.
"""
repo = package_repository_manager.get_repository(path)
resource = repo.install_variant(self.resource,
dry_run=dry_run,
overrides=overrides)
if resource is None:
return None
elif resource is self.resource:
return self
else:
return Variant(resource) | python | def install(self, path, dry_run=False, overrides=None):
"""Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned.
"""
repo = package_repository_manager.get_repository(path)
resource = repo.install_variant(self.resource,
dry_run=dry_run,
overrides=overrides)
if resource is None:
return None
elif resource is self.resource:
return self
else:
return Variant(resource) | [
"def",
"install",
"(",
"self",
",",
"path",
",",
"dry_run",
"=",
"False",
",",
"overrides",
"=",
"None",
")",
":",
"repo",
"=",
"package_repository_manager",
".",
"get_repository",
"(",
"path",
")",
"resource",
"=",
"repo",
".",
"install_variant",
"(",
"se... | Install this variant into another package repository.
If the package already exists, this variant will be correctly merged
into the package. If the variant already exists in this package, the
existing variant is returned.
Args:
path (str): Path to destination package repository.
dry_run (bool): If True, do not actually install the variant. In this
mode, a `Variant` instance is only returned if the equivalent
variant already exists in this repository; otherwise, None is
returned.
overrides (dict): Use this to change or add attributes to the
installed variant.
Returns:
`Variant` object - the (existing or newly created) variant in the
specified repository. If `dry_run` is True, None may be returned. | [
"Install",
"this",
"variant",
"into",
"another",
"package",
"repository",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/packages_.py#L378-L407 | train | 227,197 |
nerdvegas/rez | src/rez/serialise.py | open_file_for_write | def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object.
"""
stream = StringIO()
yield stream
content = stream.getvalue()
filepath = os.path.realpath(filepath)
tmpdir = tmpdir_manager.mkdtemp()
cache_filepath = os.path.join(tmpdir, os.path.basename(filepath))
debug_print("Writing to %s (local cache of %s)", cache_filepath, filepath)
with atomic_write(filepath, overwrite=True) as f:
f.write(content)
if mode is not None:
os.chmod(filepath, mode)
with open(cache_filepath, 'w') as f:
f.write(content)
file_cache[filepath] = cache_filepath | python | def open_file_for_write(filepath, mode=None):
"""Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object.
"""
stream = StringIO()
yield stream
content = stream.getvalue()
filepath = os.path.realpath(filepath)
tmpdir = tmpdir_manager.mkdtemp()
cache_filepath = os.path.join(tmpdir, os.path.basename(filepath))
debug_print("Writing to %s (local cache of %s)", cache_filepath, filepath)
with atomic_write(filepath, overwrite=True) as f:
f.write(content)
if mode is not None:
os.chmod(filepath, mode)
with open(cache_filepath, 'w') as f:
f.write(content)
file_cache[filepath] = cache_filepath | [
"def",
"open_file_for_write",
"(",
"filepath",
",",
"mode",
"=",
"None",
")",
":",
"stream",
"=",
"StringIO",
"(",
")",
"yield",
"stream",
"content",
"=",
"stream",
".",
"getvalue",
"(",
")",
"filepath",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"f... | Writes both to given filepath, and tmpdir location.
This is to get around the problem with some NFS's where immediately reading
a file that has just been written is problematic. Instead, any files that we
write, we also write to /tmp, and reads of these files are redirected there.
Args:
filepath (str): File to write.
mode (int): Same mode arg as you would pass to `os.chmod`.
Yields:
File-like object. | [
"Writes",
"both",
"to",
"given",
"filepath",
"and",
"tmpdir",
"location",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L43-L76 | train | 227,198 |
nerdvegas/rez | src/rez/serialise.py | load_py | def load_py(stream, filepath=None):
"""Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
with add_sys_paths(config.package_definition_build_python_paths):
return _load_py(stream, filepath=filepath) | python | def load_py(stream, filepath=None):
"""Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict.
"""
with add_sys_paths(config.package_definition_build_python_paths):
return _load_py(stream, filepath=filepath) | [
"def",
"load_py",
"(",
"stream",
",",
"filepath",
"=",
"None",
")",
":",
"with",
"add_sys_paths",
"(",
"config",
".",
"package_definition_build_python_paths",
")",
":",
"return",
"_load_py",
"(",
"stream",
",",
"filepath",
"=",
"filepath",
")"
] | Load python-formatted data from a stream.
Args:
stream (file-like object).
Returns:
dict. | [
"Load",
"python",
"-",
"formatted",
"data",
"from",
"a",
"stream",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/serialise.py#L193-L203 | train | 227,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.