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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.fill_stroke | def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None):
"""fill and stroke the drawn area in one go"""
if line_width: self.set_line_style(line_width)
if fill and stroke:
self.fill_preserve(fill, opacity)
elif fill:
self.fill(fill, opacity)
if stroke:
self.stroke(stroke) | python | def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None):
"""fill and stroke the drawn area in one go"""
if line_width: self.set_line_style(line_width)
if fill and stroke:
self.fill_preserve(fill, opacity)
elif fill:
self.fill(fill, opacity)
if stroke:
self.stroke(stroke) | [
"def",
"fill_stroke",
"(",
"self",
",",
"fill",
"=",
"None",
",",
"stroke",
"=",
"None",
",",
"opacity",
"=",
"1",
",",
"line_width",
"=",
"None",
")",
":",
"if",
"line_width",
":",
"self",
".",
"set_line_style",
"(",
"line_width",
")",
"if",
"fill",
... | fill and stroke the drawn area in one go | [
"fill",
"and",
"stroke",
"the",
"drawn",
"area",
"in",
"one",
"go"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L453-L463 | train | 226,900 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.create_layout | def create_layout(self, size = None):
"""utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout"""
if not self.context:
# TODO - this is rather sloppy as far as exception goes
# should explain better
raise Exception("Can not create layout without existing context!")
layout = pangocairo.create_layout(self.context)
font_desc = pango.FontDescription(_font_desc)
if size: font_desc.set_absolute_size(size * pango.SCALE)
layout.set_font_description(font_desc)
return layout | python | def create_layout(self, size = None):
"""utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout"""
if not self.context:
# TODO - this is rather sloppy as far as exception goes
# should explain better
raise Exception("Can not create layout without existing context!")
layout = pangocairo.create_layout(self.context)
font_desc = pango.FontDescription(_font_desc)
if size: font_desc.set_absolute_size(size * pango.SCALE)
layout.set_font_description(font_desc)
return layout | [
"def",
"create_layout",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"context",
":",
"# TODO - this is rather sloppy as far as exception goes",
"# should explain better",
"raise",
"Exception",
"(",
"\"Can not create layout without existi... | utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout | [
"utility",
"function",
"to",
"create",
"layout",
"with",
"the",
"default",
"font",
".",
"Size",
"and",
"alignment",
"parameters",
"are",
"shortcuts",
"to",
"according",
"functions",
"of",
"the",
"pango",
".",
"Layout"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L465-L479 | train | 226,901 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics.show_label | def show_label(self, text, size = None, color = None, font_desc = None):
"""display text. unless font_desc is provided, will use system's default font"""
font_desc = pango.FontDescription(font_desc or _font_desc)
if color: self.set_color(color)
if size: font_desc.set_absolute_size(size * pango.SCALE)
self.show_layout(text, font_desc) | python | def show_label(self, text, size = None, color = None, font_desc = None):
"""display text. unless font_desc is provided, will use system's default font"""
font_desc = pango.FontDescription(font_desc or _font_desc)
if color: self.set_color(color)
if size: font_desc.set_absolute_size(size * pango.SCALE)
self.show_layout(text, font_desc) | [
"def",
"show_label",
"(",
"self",
",",
"text",
",",
"size",
"=",
"None",
",",
"color",
"=",
"None",
",",
"font_desc",
"=",
"None",
")",
":",
"font_desc",
"=",
"pango",
".",
"FontDescription",
"(",
"font_desc",
"or",
"_font_desc",
")",
"if",
"color",
":... | display text. unless font_desc is provided, will use system's default font | [
"display",
"text",
".",
"unless",
"font_desc",
"is",
"provided",
"will",
"use",
"system",
"s",
"default",
"font"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L481-L486 | train | 226,902 |
projecthamster/hamster | src/hamster/lib/graphics.py | Graphics._draw | def _draw(self, context, opacity):
"""draw accumulated instructions in context"""
# if we have been moved around, we should update bounds
fresh_draw = len(self.__new_instructions or []) > 0
if fresh_draw: #new stuff!
self.paths = []
self.__instruction_cache = self.__new_instructions
self.__new_instructions = []
else:
if not self.__instruction_cache:
return
for instruction, args in self.__instruction_cache:
if fresh_draw:
if instruction in ("new_path", "stroke", "fill", "clip"):
self.paths.append((instruction, "path", context.copy_path()))
elif instruction in ("save", "restore", "translate", "scale", "rotate"):
self.paths.append((instruction, "transform", args))
if instruction == "set_color":
self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
elif instruction == "show_layout":
self._show_layout(context, *args)
elif opacity < 1 and instruction == "paint":
context.paint_with_alpha(opacity)
else:
getattr(context, instruction)(*args) | python | def _draw(self, context, opacity):
"""draw accumulated instructions in context"""
# if we have been moved around, we should update bounds
fresh_draw = len(self.__new_instructions or []) > 0
if fresh_draw: #new stuff!
self.paths = []
self.__instruction_cache = self.__new_instructions
self.__new_instructions = []
else:
if not self.__instruction_cache:
return
for instruction, args in self.__instruction_cache:
if fresh_draw:
if instruction in ("new_path", "stroke", "fill", "clip"):
self.paths.append((instruction, "path", context.copy_path()))
elif instruction in ("save", "restore", "translate", "scale", "rotate"):
self.paths.append((instruction, "transform", args))
if instruction == "set_color":
self._set_color(context, args[0], args[1], args[2], args[3] * opacity)
elif instruction == "show_layout":
self._show_layout(context, *args)
elif opacity < 1 and instruction == "paint":
context.paint_with_alpha(opacity)
else:
getattr(context, instruction)(*args) | [
"def",
"_draw",
"(",
"self",
",",
"context",
",",
"opacity",
")",
":",
"# if we have been moved around, we should update bounds",
"fresh_draw",
"=",
"len",
"(",
"self",
".",
"__new_instructions",
"or",
"[",
"]",
")",
">",
"0",
"if",
"fresh_draw",
":",
"#new stuf... | draw accumulated instructions in context | [
"draw",
"accumulated",
"instructions",
"in",
"context"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L538-L566 | train | 226,903 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.find | def find(self, id):
"""breadth-first sprite search by ID"""
for sprite in self.sprites:
if sprite.id == id:
return sprite
for sprite in self.sprites:
found = sprite.find(id)
if found:
return found | python | def find(self, id):
"""breadth-first sprite search by ID"""
for sprite in self.sprites:
if sprite.id == id:
return sprite
for sprite in self.sprites:
found = sprite.find(id)
if found:
return found | [
"def",
"find",
"(",
"self",
",",
"id",
")",
":",
"for",
"sprite",
"in",
"self",
".",
"sprites",
":",
"if",
"sprite",
".",
"id",
"==",
"id",
":",
"return",
"sprite",
"for",
"sprite",
"in",
"self",
".",
"sprites",
":",
"found",
"=",
"sprite",
".",
... | breadth-first sprite search by ID | [
"breadth",
"-",
"first",
"sprite",
"search",
"by",
"ID"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L674-L683 | train | 226,904 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.traverse | def traverse(self, attr_name = None, attr_value = None):
"""traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute
"""
for sprite in self.sprites:
if (attr_name is None) or \
(attr_value is None and hasattr(sprite, attr_name)) or \
(attr_value is not None and getattr(sprite, attr_name, None) == attr_value):
yield sprite
for child in sprite.traverse(attr_name, attr_value):
yield child | python | def traverse(self, attr_name = None, attr_value = None):
"""traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute
"""
for sprite in self.sprites:
if (attr_name is None) or \
(attr_value is None and hasattr(sprite, attr_name)) or \
(attr_value is not None and getattr(sprite, attr_name, None) == attr_value):
yield sprite
for child in sprite.traverse(attr_name, attr_value):
yield child | [
"def",
"traverse",
"(",
"self",
",",
"attr_name",
"=",
"None",
",",
"attr_value",
"=",
"None",
")",
":",
"for",
"sprite",
"in",
"self",
".",
"sprites",
":",
"if",
"(",
"attr_name",
"is",
"None",
")",
"or",
"(",
"attr_value",
"is",
"None",
"and",
"has... | traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute | [
"traverse",
"the",
"whole",
"sprite",
"tree",
"and",
"return",
"child",
"sprites",
"which",
"have",
"the",
"attribute",
"and",
"it",
"s",
"set",
"to",
"the",
"specified",
"value",
".",
"If",
"falue",
"is",
"None",
"will",
"return",
"all",
"sprites",
"that"... | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L688-L700 | train | 226,905 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.log | def log(self, *lines):
"""will print out the lines in console if debug is enabled for the
specific sprite"""
if getattr(self, "debug", False):
print(dt.datetime.now().time(), end=' ')
for line in lines:
print(line, end=' ')
print() | python | def log(self, *lines):
"""will print out the lines in console if debug is enabled for the
specific sprite"""
if getattr(self, "debug", False):
print(dt.datetime.now().time(), end=' ')
for line in lines:
print(line, end=' ')
print() | [
"def",
"log",
"(",
"self",
",",
"*",
"lines",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"\"debug\"",
",",
"False",
")",
":",
"print",
"(",
"dt",
".",
"datetime",
".",
"now",
"(",
")",
".",
"time",
"(",
")",
",",
"end",
"=",
"' '",
")",
"fo... | will print out the lines in console if debug is enabled for the
specific sprite | [
"will",
"print",
"out",
"the",
"lines",
"in",
"console",
"if",
"debug",
"is",
"enabled",
"for",
"the",
"specific",
"sprite"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L702-L709 | train | 226,906 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent._add | def _add(self, sprite, index = None):
"""add one sprite at a time. used by add_child. split them up so that
it would be possible specify the index externally"""
if sprite == self:
raise Exception("trying to add sprite to itself")
if sprite.parent:
sprite.x, sprite.y = self.from_scene_coords(*sprite.to_scene_coords())
sprite.parent.remove_child(sprite)
if index is not None:
self.sprites.insert(index, sprite)
else:
self.sprites.append(sprite)
sprite.parent = self | python | def _add(self, sprite, index = None):
"""add one sprite at a time. used by add_child. split them up so that
it would be possible specify the index externally"""
if sprite == self:
raise Exception("trying to add sprite to itself")
if sprite.parent:
sprite.x, sprite.y = self.from_scene_coords(*sprite.to_scene_coords())
sprite.parent.remove_child(sprite)
if index is not None:
self.sprites.insert(index, sprite)
else:
self.sprites.append(sprite)
sprite.parent = self | [
"def",
"_add",
"(",
"self",
",",
"sprite",
",",
"index",
"=",
"None",
")",
":",
"if",
"sprite",
"==",
"self",
":",
"raise",
"Exception",
"(",
"\"trying to add sprite to itself\"",
")",
"if",
"sprite",
".",
"parent",
":",
"sprite",
".",
"x",
",",
"sprite"... | add one sprite at a time. used by add_child. split them up so that
it would be possible specify the index externally | [
"add",
"one",
"sprite",
"at",
"a",
"time",
".",
"used",
"by",
"add_child",
".",
"split",
"them",
"up",
"so",
"that",
"it",
"would",
"be",
"possible",
"specify",
"the",
"index",
"externally"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L711-L725 | train | 226,907 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent._sort | def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order) | python | def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order) | [
"def",
"_sort",
"(",
"self",
")",
":",
"self",
".",
"__dict__",
"[",
"'_z_ordered_sprites'",
"]",
"=",
"sorted",
"(",
"self",
".",
"sprites",
",",
"key",
"=",
"lambda",
"sprite",
":",
"sprite",
".",
"z_order",
")"
] | sort sprites by z_order | [
"sort",
"sprites",
"by",
"z_order"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L728-L730 | train | 226,908 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.add_child | def add_child(self, *sprites):
"""Add child sprite. Child will be nested within parent"""
for sprite in sprites:
self._add(sprite)
self._sort()
self.redraw() | python | def add_child(self, *sprites):
"""Add child sprite. Child will be nested within parent"""
for sprite in sprites:
self._add(sprite)
self._sort()
self.redraw() | [
"def",
"add_child",
"(",
"self",
",",
"*",
"sprites",
")",
":",
"for",
"sprite",
"in",
"sprites",
":",
"self",
".",
"_add",
"(",
"sprite",
")",
"self",
".",
"_sort",
"(",
")",
"self",
".",
"redraw",
"(",
")"
] | Add child sprite. Child will be nested within parent | [
"Add",
"child",
"sprite",
".",
"Child",
"will",
"be",
"nested",
"within",
"parent"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L732-L737 | train | 226,909 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.all_child_sprites | def all_child_sprites(self):
"""returns all child and grandchild sprites in a flat list"""
for sprite in self.sprites:
for child_sprite in sprite.all_child_sprites():
yield child_sprite
yield sprite | python | def all_child_sprites(self):
"""returns all child and grandchild sprites in a flat list"""
for sprite in self.sprites:
for child_sprite in sprite.all_child_sprites():
yield child_sprite
yield sprite | [
"def",
"all_child_sprites",
"(",
"self",
")",
":",
"for",
"sprite",
"in",
"self",
".",
"sprites",
":",
"for",
"child_sprite",
"in",
"sprite",
".",
"all_child_sprites",
"(",
")",
":",
"yield",
"child_sprite",
"yield",
"sprite"
] | returns all child and grandchild sprites in a flat list | [
"returns",
"all",
"child",
"and",
"grandchild",
"sprites",
"in",
"a",
"flat",
"list"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L774-L779 | train | 226,910 |
projecthamster/hamster | src/hamster/lib/graphics.py | Parent.disconnect_child | def disconnect_child(self, sprite, *handlers):
"""disconnects from child event. if handler is not specified, will
disconnect from all the child sprite events"""
handlers = handlers or self._child_handlers.get(sprite, [])
for handler in list(handlers):
if sprite.handler_is_connected(handler):
sprite.disconnect(handler)
if handler in self._child_handlers.get(sprite, []):
self._child_handlers[sprite].remove(handler)
if not self._child_handlers[sprite]:
del self._child_handlers[sprite] | python | def disconnect_child(self, sprite, *handlers):
"""disconnects from child event. if handler is not specified, will
disconnect from all the child sprite events"""
handlers = handlers or self._child_handlers.get(sprite, [])
for handler in list(handlers):
if sprite.handler_is_connected(handler):
sprite.disconnect(handler)
if handler in self._child_handlers.get(sprite, []):
self._child_handlers[sprite].remove(handler)
if not self._child_handlers[sprite]:
del self._child_handlers[sprite] | [
"def",
"disconnect_child",
"(",
"self",
",",
"sprite",
",",
"*",
"handlers",
")",
":",
"handlers",
"=",
"handlers",
"or",
"self",
".",
"_child_handlers",
".",
"get",
"(",
"sprite",
",",
"[",
"]",
")",
"for",
"handler",
"in",
"list",
"(",
"handlers",
")... | disconnects from child event. if handler is not specified, will
disconnect from all the child sprite events | [
"disconnects",
"from",
"child",
"event",
".",
"if",
"handler",
"is",
"not",
"specified",
"will",
"disconnect",
"from",
"all",
"the",
"child",
"sprite",
"events"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L807-L818 | train | 226,911 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite._get_mouse_cursor | def _get_mouse_cursor(self):
"""Determine mouse cursor.
By default look for self.mouse_cursor is defined and take that.
Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for
interactive sprites. Defaults to scenes cursor.
"""
if self.mouse_cursor is not None:
return self.mouse_cursor
elif self.interactive and self.draggable:
return gdk.CursorType.FLEUR
elif self.interactive:
return gdk.CursorType.HAND2 | python | def _get_mouse_cursor(self):
"""Determine mouse cursor.
By default look for self.mouse_cursor is defined and take that.
Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for
interactive sprites. Defaults to scenes cursor.
"""
if self.mouse_cursor is not None:
return self.mouse_cursor
elif self.interactive and self.draggable:
return gdk.CursorType.FLEUR
elif self.interactive:
return gdk.CursorType.HAND2 | [
"def",
"_get_mouse_cursor",
"(",
"self",
")",
":",
"if",
"self",
".",
"mouse_cursor",
"is",
"not",
"None",
":",
"return",
"self",
".",
"mouse_cursor",
"elif",
"self",
".",
"interactive",
"and",
"self",
".",
"draggable",
":",
"return",
"gdk",
".",
"CursorTy... | Determine mouse cursor.
By default look for self.mouse_cursor is defined and take that.
Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for
interactive sprites. Defaults to scenes cursor. | [
"Determine",
"mouse",
"cursor",
".",
"By",
"default",
"look",
"for",
"self",
".",
"mouse_cursor",
"is",
"defined",
"and",
"take",
"that",
".",
"Otherwise",
"use",
"gdk",
".",
"CursorType",
".",
"FLEUR",
"for",
"draggable",
"sprites",
"and",
"gdk",
".",
"Cu... | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1026-L1037 | train | 226,912 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.bring_to_front | def bring_to_front(self):
"""adjusts sprite's z-order so that the sprite is on top of it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1 | python | def bring_to_front(self):
"""adjusts sprite's z-order so that the sprite is on top of it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1 | [
"def",
"bring_to_front",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"self",
".",
"z_order",
"=",
"self",
".",
"parent",
".",
"_z_ordered_sprites",
"[",
"-",
"1",
"]",
".",
"z_order",
"+",
"1"
] | adjusts sprite's z-order so that the sprite is on top of it's
siblings | [
"adjusts",
"sprite",
"s",
"z",
"-",
"order",
"so",
"that",
"the",
"sprite",
"is",
"on",
"top",
"of",
"it",
"s",
"siblings"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1039-L1044 | train | 226,913 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.send_to_back | def send_to_back(self):
"""adjusts sprite's z-order so that the sprite is behind it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[0].z_order - 1 | python | def send_to_back(self):
"""adjusts sprite's z-order so that the sprite is behind it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[0].z_order - 1 | [
"def",
"send_to_back",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"parent",
":",
"return",
"self",
".",
"z_order",
"=",
"self",
".",
"parent",
".",
"_z_ordered_sprites",
"[",
"0",
"]",
".",
"z_order",
"-",
"1"
] | adjusts sprite's z-order so that the sprite is behind it's
siblings | [
"adjusts",
"sprite",
"s",
"z",
"-",
"order",
"so",
"that",
"the",
"sprite",
"is",
"behind",
"it",
"s",
"siblings"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1046-L1051 | train | 226,914 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.blur | def blur(self):
"""removes focus from the current element if it has it"""
scene = self.get_scene()
if scene and scene._focus_sprite == self:
scene._focus_sprite = None | python | def blur(self):
"""removes focus from the current element if it has it"""
scene = self.get_scene()
if scene and scene._focus_sprite == self:
scene._focus_sprite = None | [
"def",
"blur",
"(",
"self",
")",
":",
"scene",
"=",
"self",
".",
"get_scene",
"(",
")",
"if",
"scene",
"and",
"scene",
".",
"_focus_sprite",
"==",
"self",
":",
"scene",
".",
"_focus_sprite",
"=",
"None"
] | removes focus from the current element if it has it | [
"removes",
"focus",
"from",
"the",
"current",
"element",
"if",
"it",
"has",
"it"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1067-L1071 | train | 226,915 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.get_parents | def get_parents(self):
"""returns all the parent sprites up until scene"""
res = []
parent = self.parent
while parent and isinstance(parent, Scene) == False:
res.insert(0, parent)
parent = parent.parent
return res | python | def get_parents(self):
"""returns all the parent sprites up until scene"""
res = []
parent = self.parent
while parent and isinstance(parent, Scene) == False:
res.insert(0, parent)
parent = parent.parent
return res | [
"def",
"get_parents",
"(",
"self",
")",
":",
"res",
"=",
"[",
"]",
"parent",
"=",
"self",
".",
"parent",
"while",
"parent",
"and",
"isinstance",
"(",
"parent",
",",
"Scene",
")",
"==",
"False",
":",
"res",
".",
"insert",
"(",
"0",
",",
"parent",
")... | returns all the parent sprites up until scene | [
"returns",
"all",
"the",
"parent",
"sprites",
"up",
"until",
"scene"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1077-L1085 | train | 226,916 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.get_extents | def get_extents(self):
"""measure the extents of the sprite's graphics."""
if self._sprite_dirty:
# redrawing merely because we need fresh extents of the sprite
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
context.transform(self.get_matrix())
self.emit("on-render")
self.__dict__["_sprite_dirty"] = False
self.graphics._draw(context, 1)
if not self.graphics.paths:
self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1)
if not self.graphics.paths:
return None
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
# bit of a hack around the problem - looking for clip instructions in parent
# so extents would not get out of it
clip_extents = None
for parent in self.get_parents():
context.transform(parent.get_local_matrix())
if parent.graphics.paths:
clip_regions = []
for instruction, type, path in parent.graphics.paths:
if instruction == "clip":
context.append_path(path)
context.save()
context.identity_matrix()
clip_regions.append(context.fill_extents())
context.restore()
context.new_path()
elif instruction == "restore" and clip_regions:
clip_regions.pop()
for ext in clip_regions:
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1]))
intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext)
context.transform(self.get_local_matrix())
for instruction, type, path in self.graphics.paths:
if type == "path":
context.append_path(path)
else:
getattr(context, instruction)(*path)
context.identity_matrix()
ext = context.path_extents()
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]),
int(ext[2] - ext[0]), int(ext[3] - ext[1]))
if clip_extents:
intersect, ext = gdk.rectangle_intersect(clip_extents, ext)
if not ext.width and not ext.height:
ext = None
self.__dict__['_stroke_context'] = context
return ext | python | def get_extents(self):
"""measure the extents of the sprite's graphics."""
if self._sprite_dirty:
# redrawing merely because we need fresh extents of the sprite
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
context.transform(self.get_matrix())
self.emit("on-render")
self.__dict__["_sprite_dirty"] = False
self.graphics._draw(context, 1)
if not self.graphics.paths:
self.graphics._draw(cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0)), 1)
if not self.graphics.paths:
return None
context = cairo.Context(cairo.ImageSurface(cairo.FORMAT_A1, 0, 0))
# bit of a hack around the problem - looking for clip instructions in parent
# so extents would not get out of it
clip_extents = None
for parent in self.get_parents():
context.transform(parent.get_local_matrix())
if parent.graphics.paths:
clip_regions = []
for instruction, type, path in parent.graphics.paths:
if instruction == "clip":
context.append_path(path)
context.save()
context.identity_matrix()
clip_regions.append(context.fill_extents())
context.restore()
context.new_path()
elif instruction == "restore" and clip_regions:
clip_regions.pop()
for ext in clip_regions:
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]), int(ext[2] - ext[0]), int(ext[3] - ext[1]))
intersect, clip_extents = gdk.rectangle_intersect((clip_extents or ext), ext)
context.transform(self.get_local_matrix())
for instruction, type, path in self.graphics.paths:
if type == "path":
context.append_path(path)
else:
getattr(context, instruction)(*path)
context.identity_matrix()
ext = context.path_extents()
ext = get_gdk_rectangle(int(ext[0]), int(ext[1]),
int(ext[2] - ext[0]), int(ext[3] - ext[1]))
if clip_extents:
intersect, ext = gdk.rectangle_intersect(clip_extents, ext)
if not ext.width and not ext.height:
ext = None
self.__dict__['_stroke_context'] = context
return ext | [
"def",
"get_extents",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sprite_dirty",
":",
"# redrawing merely because we need fresh extents of the sprite",
"context",
"=",
"cairo",
".",
"Context",
"(",
"cairo",
".",
"ImageSurface",
"(",
"cairo",
".",
"FORMAT_A1",
",",
... | measure the extents of the sprite's graphics. | [
"measure",
"the",
"extents",
"of",
"the",
"sprite",
"s",
"graphics",
"."
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1088-L1152 | train | 226,917 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.check_hit | def check_hit(self, x, y):
"""check if the given coordinates are inside the sprite's fill or stroke path"""
extents = self.get_extents()
if not extents:
return False
if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height:
return self._stroke_context is None or self._stroke_context.in_fill(x, y)
else:
return False | python | def check_hit(self, x, y):
"""check if the given coordinates are inside the sprite's fill or stroke path"""
extents = self.get_extents()
if not extents:
return False
if extents.x <= x <= extents.x + extents.width and extents.y <= y <= extents.y + extents.height:
return self._stroke_context is None or self._stroke_context.in_fill(x, y)
else:
return False | [
"def",
"check_hit",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"extents",
"=",
"self",
".",
"get_extents",
"(",
")",
"if",
"not",
"extents",
":",
"return",
"False",
"if",
"extents",
".",
"x",
"<=",
"x",
"<=",
"extents",
".",
"x",
"+",
"extents",
... | check if the given coordinates are inside the sprite's fill or stroke path | [
"check",
"if",
"the",
"given",
"coordinates",
"are",
"inside",
"the",
"sprite",
"s",
"fill",
"or",
"stroke",
"path"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1155-L1165 | train | 226,918 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.get_matrix | def get_matrix(self):
"""return sprite's current transformation matrix"""
if self.parent:
return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix())
else:
return self.get_local_matrix() | python | def get_matrix(self):
"""return sprite's current transformation matrix"""
if self.parent:
return self.get_local_matrix() * (self._prev_parent_matrix or self.parent.get_matrix())
else:
return self.get_local_matrix() | [
"def",
"get_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"return",
"self",
".",
"get_local_matrix",
"(",
")",
"*",
"(",
"self",
".",
"_prev_parent_matrix",
"or",
"self",
".",
"parent",
".",
"get_matrix",
"(",
")",
")",
"else",
":",... | return sprite's current transformation matrix | [
"return",
"sprite",
"s",
"current",
"transformation",
"matrix"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1238-L1243 | train | 226,919 |
projecthamster/hamster | src/hamster/lib/graphics.py | Sprite.from_scene_coords | def from_scene_coords(self, x=0, y=0):
"""Converts x, y given in the scene coordinates to sprite's local ones
coordinates"""
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y) | python | def from_scene_coords(self, x=0, y=0):
"""Converts x, y given in the scene coordinates to sprite's local ones
coordinates"""
matrix = self.get_matrix()
matrix.invert()
return matrix.transform_point(x, y) | [
"def",
"from_scene_coords",
"(",
"self",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"matrix",
"=",
"self",
".",
"get_matrix",
"(",
")",
"matrix",
".",
"invert",
"(",
")",
"return",
"matrix",
".",
"transform_point",
"(",
"x",
",",
"y",
")"
] | Converts x, y given in the scene coordinates to sprite's local ones
coordinates | [
"Converts",
"x",
"y",
"given",
"in",
"the",
"scene",
"coordinates",
"to",
"sprite",
"s",
"local",
"ones",
"coordinates"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1246-L1251 | train | 226,920 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.stop_animation | def stop_animation(self, sprites):
"""stop animation without firing on_complete"""
if isinstance(sprites, list) is False:
sprites = [sprites]
for sprite in sprites:
self.tweener.kill_tweens(sprite) | python | def stop_animation(self, sprites):
"""stop animation without firing on_complete"""
if isinstance(sprites, list) is False:
sprites = [sprites]
for sprite in sprites:
self.tweener.kill_tweens(sprite) | [
"def",
"stop_animation",
"(",
"self",
",",
"sprites",
")",
":",
"if",
"isinstance",
"(",
"sprites",
",",
"list",
")",
"is",
"False",
":",
"sprites",
"=",
"[",
"sprites",
"]",
"for",
"sprite",
"in",
"sprites",
":",
"self",
".",
"tweener",
".",
"kill_twe... | stop animation without firing on_complete | [
"stop",
"animation",
"without",
"firing",
"on_complete"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1950-L1956 | train | 226,921 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.redraw | def redraw(self):
"""Queue redraw. The redraw will be performed not more often than
the `framerate` allows"""
if self.__drawing_queued == False: #if we are moving, then there is a timeout somewhere already
self.__drawing_queued = True
self._last_frame_time = dt.datetime.now()
gobject.timeout_add(1000 / self.framerate, self.__redraw_loop) | python | def redraw(self):
"""Queue redraw. The redraw will be performed not more often than
the `framerate` allows"""
if self.__drawing_queued == False: #if we are moving, then there is a timeout somewhere already
self.__drawing_queued = True
self._last_frame_time = dt.datetime.now()
gobject.timeout_add(1000 / self.framerate, self.__redraw_loop) | [
"def",
"redraw",
"(",
"self",
")",
":",
"if",
"self",
".",
"__drawing_queued",
"==",
"False",
":",
"#if we are moving, then there is a timeout somewhere already",
"self",
".",
"__drawing_queued",
"=",
"True",
"self",
".",
"_last_frame_time",
"=",
"dt",
".",
"datetim... | Queue redraw. The redraw will be performed not more often than
the `framerate` allows | [
"Queue",
"redraw",
".",
"The",
"redraw",
"will",
"be",
"performed",
"not",
"more",
"often",
"than",
"the",
"framerate",
"allows"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1959-L1965 | train | 226,922 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.__redraw_loop | def __redraw_loop(self):
"""loop until there is nothing more to tween"""
self.queue_draw() # this will trigger do_expose_event when the current events have been flushed
self.__drawing_queued = self.tweener and self.tweener.has_tweens()
return self.__drawing_queued | python | def __redraw_loop(self):
"""loop until there is nothing more to tween"""
self.queue_draw() # this will trigger do_expose_event when the current events have been flushed
self.__drawing_queued = self.tweener and self.tweener.has_tweens()
return self.__drawing_queued | [
"def",
"__redraw_loop",
"(",
"self",
")",
":",
"self",
".",
"queue_draw",
"(",
")",
"# this will trigger do_expose_event when the current events have been flushed",
"self",
".",
"__drawing_queued",
"=",
"self",
".",
"tweener",
"and",
"self",
".",
"tweener",
".",
"has_... | loop until there is nothing more to tween | [
"loop",
"until",
"there",
"is",
"nothing",
"more",
"to",
"tween"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L1967-L1972 | train | 226,923 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.all_mouse_sprites | def all_mouse_sprites(self):
"""Returns flat list of the sprite tree for simplified iteration"""
def all_recursive(sprites):
if not sprites:
return
for sprite in sprites:
if sprite.visible:
yield sprite
for child in all_recursive(sprite.get_mouse_sprites()):
yield child
return all_recursive(self.get_mouse_sprites()) | python | def all_mouse_sprites(self):
"""Returns flat list of the sprite tree for simplified iteration"""
def all_recursive(sprites):
if not sprites:
return
for sprite in sprites:
if sprite.visible:
yield sprite
for child in all_recursive(sprite.get_mouse_sprites()):
yield child
return all_recursive(self.get_mouse_sprites()) | [
"def",
"all_mouse_sprites",
"(",
"self",
")",
":",
"def",
"all_recursive",
"(",
"sprites",
")",
":",
"if",
"not",
"sprites",
":",
"return",
"for",
"sprite",
"in",
"sprites",
":",
"if",
"sprite",
".",
"visible",
":",
"yield",
"sprite",
"for",
"child",
"in... | Returns flat list of the sprite tree for simplified iteration | [
"Returns",
"flat",
"list",
"of",
"the",
"sprite",
"tree",
"for",
"simplified",
"iteration"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2024-L2037 | train | 226,924 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.get_sprite_at_position | def get_sprite_at_position(self, x, y):
"""Returns the topmost visible interactive sprite for given coordinates"""
over = None
for sprite in self.all_mouse_sprites():
if sprite.interactive and sprite.check_hit(x, y):
over = sprite
return over | python | def get_sprite_at_position(self, x, y):
"""Returns the topmost visible interactive sprite for given coordinates"""
over = None
for sprite in self.all_mouse_sprites():
if sprite.interactive and sprite.check_hit(x, y):
over = sprite
return over | [
"def",
"get_sprite_at_position",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"over",
"=",
"None",
"for",
"sprite",
"in",
"self",
".",
"all_mouse_sprites",
"(",
")",
":",
"if",
"sprite",
".",
"interactive",
"and",
"sprite",
".",
"check_hit",
"(",
"x",
",... | Returns the topmost visible interactive sprite for given coordinates | [
"Returns",
"the",
"topmost",
"visible",
"interactive",
"sprite",
"for",
"given",
"coordinates"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2040-L2047 | train | 226,925 |
projecthamster/hamster | src/hamster/lib/graphics.py | Scene.start_drag | def start_drag(self, sprite, cursor_x = None, cursor_y = None):
"""start dragging given sprite"""
cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y
self._mouse_down_sprite = self._drag_sprite = sprite
sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y
self.__drag_start_x, self.__drag_start_y = cursor_x, cursor_y
self.__drag_started = True | python | def start_drag(self, sprite, cursor_x = None, cursor_y = None):
"""start dragging given sprite"""
cursor_x, cursor_y = cursor_x or sprite.x, cursor_y or sprite.y
self._mouse_down_sprite = self._drag_sprite = sprite
sprite.drag_x, sprite.drag_y = self._drag_sprite.x, self._drag_sprite.y
self.__drag_start_x, self.__drag_start_y = cursor_x, cursor_y
self.__drag_started = True | [
"def",
"start_drag",
"(",
"self",
",",
"sprite",
",",
"cursor_x",
"=",
"None",
",",
"cursor_y",
"=",
"None",
")",
":",
"cursor_x",
",",
"cursor_y",
"=",
"cursor_x",
"or",
"sprite",
".",
"x",
",",
"cursor_y",
"or",
"sprite",
".",
"y",
"self",
".",
"_m... | start dragging given sprite | [
"start",
"dragging",
"given",
"sprite"
] | ca5254eff53172796ddafc72226c394ed1858245 | https://github.com/projecthamster/hamster/blob/ca5254eff53172796ddafc72226c394ed1858245/src/hamster/lib/graphics.py#L2158-L2165 | train | 226,926 |
readbeyond/aeneas | aeneas/logger.py | Logger.pretty_print | def pretty_print(self, as_list=False, show_datetime=True):
"""
Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string or list of strings
"""
ppl = [entry.pretty_print(show_datetime) for entry in self.entries]
if as_list:
return ppl
return u"\n".join(ppl) | python | def pretty_print(self, as_list=False, show_datetime=True):
"""
Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string or list of strings
"""
ppl = [entry.pretty_print(show_datetime) for entry in self.entries]
if as_list:
return ppl
return u"\n".join(ppl) | [
"def",
"pretty_print",
"(",
"self",
",",
"as_list",
"=",
"False",
",",
"show_datetime",
"=",
"True",
")",
":",
"ppl",
"=",
"[",
"entry",
".",
"pretty_print",
"(",
"show_datetime",
")",
"for",
"entry",
"in",
"self",
".",
"entries",
"]",
"if",
"as_list",
... | Return a Unicode string pretty print of the log entries.
:param bool as_list: if ``True``, return a list of Unicode strings,
one for each entry, instead of a Unicode string
:param bool show_datetime: if ``True``, show the date and time of the entries
:rtype: string or list of strings | [
"Return",
"a",
"Unicode",
"string",
"pretty",
"print",
"of",
"the",
"log",
"entries",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L130-L142 | train | 226,927 |
readbeyond/aeneas | aeneas/logger.py | Logger.log | def log(self, message, severity=INFO, tag=u""):
"""
Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param string tag: the tag associated with the message;
usually, the name of the class generating the entry
:rtype: datetime
"""
entry = _LogEntry(
severity=severity,
time=datetime.datetime.now(),
tag=tag,
indentation=self.indentation,
message=self._sanitize(message)
)
self.entries.append(entry)
if self.tee:
gf.safe_print(entry.pretty_print(show_datetime=self.tee_show_datetime))
return entry.time | python | def log(self, message, severity=INFO, tag=u""):
"""
Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param string tag: the tag associated with the message;
usually, the name of the class generating the entry
:rtype: datetime
"""
entry = _LogEntry(
severity=severity,
time=datetime.datetime.now(),
tag=tag,
indentation=self.indentation,
message=self._sanitize(message)
)
self.entries.append(entry)
if self.tee:
gf.safe_print(entry.pretty_print(show_datetime=self.tee_show_datetime))
return entry.time | [
"def",
"log",
"(",
"self",
",",
"message",
",",
"severity",
"=",
"INFO",
",",
"tag",
"=",
"u\"\"",
")",
":",
"entry",
"=",
"_LogEntry",
"(",
"severity",
"=",
"severity",
",",
"time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
",",
"tag... | Add a given message to the log, and return its time.
:param string message: the message to be added
:param severity: the severity of the message
:type severity: :class:`~aeneas.logger.Logger`
:param string tag: the tag associated with the message;
usually, the name of the class generating the entry
:rtype: datetime | [
"Add",
"a",
"given",
"message",
"to",
"the",
"log",
"and",
"return",
"its",
"time",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L144-L165 | train | 226,928 |
readbeyond/aeneas | aeneas/logger.py | Logger.write | def write(self, path):
"""
Output the log to file.
:param string path: the path of the log file to be written
"""
with io.open(path, "w", encoding="utf-8") as log_file:
log_file.write(self.pretty_print()) | python | def write(self, path):
"""
Output the log to file.
:param string path: the path of the log file to be written
"""
with io.open(path, "w", encoding="utf-8") as log_file:
log_file.write(self.pretty_print()) | [
"def",
"write",
"(",
"self",
",",
"path",
")",
":",
"with",
"io",
".",
"open",
"(",
"path",
",",
"\"w\"",
",",
"encoding",
"=",
"\"utf-8\"",
")",
"as",
"log_file",
":",
"log_file",
".",
"write",
"(",
"self",
".",
"pretty_print",
"(",
")",
")"
] | Output the log to file.
:param string path: the path of the log file to be written | [
"Output",
"the",
"log",
"to",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L173-L180 | train | 226,929 |
readbeyond/aeneas | aeneas/logger.py | _LogEntry.pretty_print | def pretty_print(self, show_datetime=True):
"""
Returns a Unicode string containing
the pretty printing of a given log entry.
:param bool show_datetime: if ``True``, print the date and time of the entry
:rtype: string
"""
if show_datetime:
return u"[%s] %s %s%s: %s" % (
self.severity,
gf.object_to_unicode(self.time),
u" " * self.indentation,
self.tag,
self.message
)
return u"[%s] %s%s: %s" % (
self.severity,
u" " * self.indentation,
self.tag,
self.message
) | python | def pretty_print(self, show_datetime=True):
"""
Returns a Unicode string containing
the pretty printing of a given log entry.
:param bool show_datetime: if ``True``, print the date and time of the entry
:rtype: string
"""
if show_datetime:
return u"[%s] %s %s%s: %s" % (
self.severity,
gf.object_to_unicode(self.time),
u" " * self.indentation,
self.tag,
self.message
)
return u"[%s] %s%s: %s" % (
self.severity,
u" " * self.indentation,
self.tag,
self.message
) | [
"def",
"pretty_print",
"(",
"self",
",",
"show_datetime",
"=",
"True",
")",
":",
"if",
"show_datetime",
":",
"return",
"u\"[%s] %s %s%s: %s\"",
"%",
"(",
"self",
".",
"severity",
",",
"gf",
".",
"object_to_unicode",
"(",
"self",
".",
"time",
")",
",",
"u\"... | Returns a Unicode string containing
the pretty printing of a given log entry.
:param bool show_datetime: if ``True``, print the date and time of the entry
:rtype: string | [
"Returns",
"a",
"Unicode",
"string",
"containing",
"the",
"pretty",
"printing",
"of",
"a",
"given",
"log",
"entry",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L219-L240 | train | 226,930 |
readbeyond/aeneas | aeneas/logger.py | Loggable._log | def _log(self, message, severity=Logger.DEBUG):
"""
Log generic message
:param string message: the message to log
:param string severity: the message severity
:rtype: datetime
"""
return self.logger.log(message, severity, self.TAG) | python | def _log(self, message, severity=Logger.DEBUG):
"""
Log generic message
:param string message: the message to log
:param string severity: the message severity
:rtype: datetime
"""
return self.logger.log(message, severity, self.TAG) | [
"def",
"_log",
"(",
"self",
",",
"message",
",",
"severity",
"=",
"Logger",
".",
"DEBUG",
")",
":",
"return",
"self",
".",
"logger",
".",
"log",
"(",
"message",
",",
"severity",
",",
"self",
".",
"TAG",
")"
] | Log generic message
:param string message: the message to log
:param string severity: the message severity
:rtype: datetime | [
"Log",
"generic",
"message"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L323-L331 | train | 226,931 |
readbeyond/aeneas | aeneas/logger.py | Loggable.log_exc | def log_exc(self, message, exc=None, critical=True, raise_type=None):
"""
Log exception, and possibly raise exception.
:param string message: the message to log
:param Exception exc: the original exception
:param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`;
otherwise as :data:`aeneas.logger.Logger.WARNING`
:param Exception raise_type: if not ``None``, raise this Exception type
"""
log_function = self.log_crit if critical else self.log_warn
log_function(message)
if exc is not None:
log_function([u"%s", exc])
if raise_type is not None:
raise_message = message
if exc is not None:
raise_message = u"%s : %s" % (message, exc)
raise raise_type(raise_message) | python | def log_exc(self, message, exc=None, critical=True, raise_type=None):
"""
Log exception, and possibly raise exception.
:param string message: the message to log
:param Exception exc: the original exception
:param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`;
otherwise as :data:`aeneas.logger.Logger.WARNING`
:param Exception raise_type: if not ``None``, raise this Exception type
"""
log_function = self.log_crit if critical else self.log_warn
log_function(message)
if exc is not None:
log_function([u"%s", exc])
if raise_type is not None:
raise_message = message
if exc is not None:
raise_message = u"%s : %s" % (message, exc)
raise raise_type(raise_message) | [
"def",
"log_exc",
"(",
"self",
",",
"message",
",",
"exc",
"=",
"None",
",",
"critical",
"=",
"True",
",",
"raise_type",
"=",
"None",
")",
":",
"log_function",
"=",
"self",
".",
"log_crit",
"if",
"critical",
"else",
"self",
".",
"log_warn",
"log_function... | Log exception, and possibly raise exception.
:param string message: the message to log
:param Exception exc: the original exception
:param bool critical: if ``True``, log as :data:`aeneas.logger.Logger.CRITICAL`;
otherwise as :data:`aeneas.logger.Logger.WARNING`
:param Exception raise_type: if not ``None``, raise this Exception type | [
"Log",
"exception",
"and",
"possibly",
"raise",
"exception",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/logger.py#L333-L351 | train | 226,932 |
readbeyond/aeneas | aeneas/plotter.py | Plotter.add_waveform | def add_waveform(self, waveform):
"""
Add a waveform to the plot.
:param waveform: the waveform to be added
:type waveform: :class:`~aeneas.plotter.PlotWaveform`
:raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`
"""
if not isinstance(waveform, PlotWaveform):
self.log_exc(u"waveform must be an instance of PlotWaveform", None, True, TypeError)
self.waveform = waveform
self.log(u"Added waveform") | python | def add_waveform(self, waveform):
"""
Add a waveform to the plot.
:param waveform: the waveform to be added
:type waveform: :class:`~aeneas.plotter.PlotWaveform`
:raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform`
"""
if not isinstance(waveform, PlotWaveform):
self.log_exc(u"waveform must be an instance of PlotWaveform", None, True, TypeError)
self.waveform = waveform
self.log(u"Added waveform") | [
"def",
"add_waveform",
"(",
"self",
",",
"waveform",
")",
":",
"if",
"not",
"isinstance",
"(",
"waveform",
",",
"PlotWaveform",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"waveform must be an instance of PlotWaveform\"",
",",
"None",
",",
"True",
",",
"TypeError"... | Add a waveform to the plot.
:param waveform: the waveform to be added
:type waveform: :class:`~aeneas.plotter.PlotWaveform`
:raises: TypeError: if ``waveform`` is not an instance of :class:`~aeneas.plotter.PlotWaveform` | [
"Add",
"a",
"waveform",
"to",
"the",
"plot",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L100-L111 | train | 226,933 |
readbeyond/aeneas | aeneas/plotter.py | Plotter.add_timescale | def add_timescale(self, timescale):
"""
Add a time scale to the plot.
:param timescale: the timescale to be added
:type timescale: :class:`~aeneas.plotter.PlotTimeScale`
:raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale`
"""
if not isinstance(timescale, PlotTimeScale):
self.log_exc(u"timescale must be an instance of PlotTimeScale", None, True, TypeError)
self.timescale = timescale
self.log(u"Added timescale") | python | def add_timescale(self, timescale):
"""
Add a time scale to the plot.
:param timescale: the timescale to be added
:type timescale: :class:`~aeneas.plotter.PlotTimeScale`
:raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale`
"""
if not isinstance(timescale, PlotTimeScale):
self.log_exc(u"timescale must be an instance of PlotTimeScale", None, True, TypeError)
self.timescale = timescale
self.log(u"Added timescale") | [
"def",
"add_timescale",
"(",
"self",
",",
"timescale",
")",
":",
"if",
"not",
"isinstance",
"(",
"timescale",
",",
"PlotTimeScale",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"timescale must be an instance of PlotTimeScale\"",
",",
"None",
",",
"True",
",",
"Type... | Add a time scale to the plot.
:param timescale: the timescale to be added
:type timescale: :class:`~aeneas.plotter.PlotTimeScale`
:raises: TypeError: if ``timescale`` is not an instance of :class:`~aeneas.plotter.PlotTimeScale` | [
"Add",
"a",
"time",
"scale",
"to",
"the",
"plot",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L113-L124 | train | 226,934 |
readbeyond/aeneas | aeneas/plotter.py | Plotter.add_labelset | def add_labelset(self, labelset):
"""
Add a set of labels to the plot.
:param labelset: the set of labels to be added
:type labelset: :class:`~aeneas.plotter.PlotLabelset`
:raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset`
"""
if not isinstance(labelset, PlotLabelset):
self.log_exc(u"labelset must be an instance of PlotLabelset", None, True, TypeError)
self.labelsets.append(labelset)
self.log(u"Added labelset") | python | def add_labelset(self, labelset):
"""
Add a set of labels to the plot.
:param labelset: the set of labels to be added
:type labelset: :class:`~aeneas.plotter.PlotLabelset`
:raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset`
"""
if not isinstance(labelset, PlotLabelset):
self.log_exc(u"labelset must be an instance of PlotLabelset", None, True, TypeError)
self.labelsets.append(labelset)
self.log(u"Added labelset") | [
"def",
"add_labelset",
"(",
"self",
",",
"labelset",
")",
":",
"if",
"not",
"isinstance",
"(",
"labelset",
",",
"PlotLabelset",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"labelset must be an instance of PlotLabelset\"",
",",
"None",
",",
"True",
",",
"TypeError"... | Add a set of labels to the plot.
:param labelset: the set of labels to be added
:type labelset: :class:`~aeneas.plotter.PlotLabelset`
:raises: TypeError: if ``labelset`` is not an instance of :class:`~aeneas.plotter.PlotLabelset` | [
"Add",
"a",
"set",
"of",
"labels",
"to",
"the",
"plot",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L126-L137 | train | 226,935 |
readbeyond/aeneas | aeneas/plotter.py | Plotter.draw_png | def draw_png(self, output_file_path, h_zoom=5, v_zoom=30):
"""
Draw the current plot to a PNG file.
:param string output_path: the path of the output file to be written
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:raises: ImportError: if module ``PIL`` cannot be imported
:raises: OSError: if ``output_file_path`` cannot be written
"""
# 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)
# get widths and cumulative height, in modules
widths = [ls.width for ls in self.labelsets]
sum_height = sum([ls.height for ls in self.labelsets])
if self.waveform is not None:
widths.append(self.waveform.width)
sum_height += self.waveform.height
if self.timescale is not None:
sum_height += self.timescale.height
# in modules
image_width = max(widths)
image_height = sum_height
# in pixels
image_width_px = image_width * h_zoom
image_height_px = image_height * v_zoom
# build image object
self.log([u"Building image with size (modules): %d %d", image_width, image_height])
self.log([u"Building image with size (px): %d %d", image_width_px, image_height_px])
image_obj = Image.new("RGB", (image_width_px, image_height_px), color=PlotterColors.AUDACITY_BACKGROUND_GREY)
current_y = 0
if self.waveform is not None:
self.log(u"Drawing waveform")
self.waveform.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += self.waveform.height
timescale_y = current_y
if self.timescale is not None:
# NOTE draw as the last thing
# COMMENTED self.log(u"Drawing timescale")
# COMMENTED self.timescale.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += self.timescale.height
for labelset in self.labelsets:
self.log(u"Drawing labelset")
labelset.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += labelset.height
if self.timescale is not None:
self.log(u"Drawing timescale")
self.timescale.draw_png(image_obj, h_zoom, v_zoom, timescale_y)
self.log([u"Saving to file '%s'", output_file_path])
image_obj.save(output_file_path) | python | def draw_png(self, output_file_path, h_zoom=5, v_zoom=30):
"""
Draw the current plot to a PNG file.
:param string output_path: the path of the output file to be written
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:raises: ImportError: if module ``PIL`` cannot be imported
:raises: OSError: if ``output_file_path`` cannot be written
"""
# 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)
# get widths and cumulative height, in modules
widths = [ls.width for ls in self.labelsets]
sum_height = sum([ls.height for ls in self.labelsets])
if self.waveform is not None:
widths.append(self.waveform.width)
sum_height += self.waveform.height
if self.timescale is not None:
sum_height += self.timescale.height
# in modules
image_width = max(widths)
image_height = sum_height
# in pixels
image_width_px = image_width * h_zoom
image_height_px = image_height * v_zoom
# build image object
self.log([u"Building image with size (modules): %d %d", image_width, image_height])
self.log([u"Building image with size (px): %d %d", image_width_px, image_height_px])
image_obj = Image.new("RGB", (image_width_px, image_height_px), color=PlotterColors.AUDACITY_BACKGROUND_GREY)
current_y = 0
if self.waveform is not None:
self.log(u"Drawing waveform")
self.waveform.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += self.waveform.height
timescale_y = current_y
if self.timescale is not None:
# NOTE draw as the last thing
# COMMENTED self.log(u"Drawing timescale")
# COMMENTED self.timescale.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += self.timescale.height
for labelset in self.labelsets:
self.log(u"Drawing labelset")
labelset.draw_png(image_obj, h_zoom, v_zoom, current_y)
current_y += labelset.height
if self.timescale is not None:
self.log(u"Drawing timescale")
self.timescale.draw_png(image_obj, h_zoom, v_zoom, timescale_y)
self.log([u"Saving to file '%s'", output_file_path])
image_obj.save(output_file_path) | [
"def",
"draw_png",
"(",
"self",
",",
"output_file_path",
",",
"h_zoom",
"=",
"5",
",",
"v_zoom",
"=",
"30",
")",
":",
"# check that output_file_path can be written",
"if",
"not",
"gf",
".",
"file_can_be_written",
"(",
"output_file_path",
")",
":",
"self",
".",
... | Draw the current plot to a PNG file.
:param string output_path: the path of the output file to be written
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:raises: ImportError: if module ``PIL`` cannot be imported
:raises: OSError: if ``output_file_path`` cannot be written | [
"Draw",
"the",
"current",
"plot",
"to",
"a",
"PNG",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L139-L191 | train | 226,936 |
readbeyond/aeneas | aeneas/plotter.py | PlotElement.text_bounding_box | def text_bounding_box(self, size_pt, text):
"""
Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height)
"""
if size_pt == 12:
mult = {"h": 9, "w_digit": 5, "w_space": 2}
elif size_pt == 18:
mult = {"h": 14, "w_digit": 9, "w_space": 2}
num_chars = len(text)
return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["w_space"] + 1, mult["h"]) | python | def text_bounding_box(self, size_pt, text):
"""
Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height)
"""
if size_pt == 12:
mult = {"h": 9, "w_digit": 5, "w_space": 2}
elif size_pt == 18:
mult = {"h": 14, "w_digit": 9, "w_space": 2}
num_chars = len(text)
return (num_chars * mult["w_digit"] + (num_chars - 1) * mult["w_space"] + 1, mult["h"]) | [
"def",
"text_bounding_box",
"(",
"self",
",",
"size_pt",
",",
"text",
")",
":",
"if",
"size_pt",
"==",
"12",
":",
"mult",
"=",
"{",
"\"h\"",
":",
"9",
",",
"\"w_digit\"",
":",
"5",
",",
"\"w_space\"",
":",
"2",
"}",
"elif",
"size_pt",
"==",
"18",
"... | Return the bounding box of the given text
at the given font size.
:param int size_pt: the font size in points
:param string text: the text
:rtype: tuple (width, height) | [
"Return",
"the",
"bounding",
"box",
"of",
"the",
"given",
"text",
"at",
"the",
"given",
"font",
"size",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L237-L252 | train | 226,937 |
readbeyond/aeneas | aeneas/plotter.py | PlotTimeScale.draw_png | def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this time scale to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image`
"""
# PIL object
draw = ImageDraw.Draw(image)
mws = self.rconf.mws
pixels_per_second = int(h_zoom / mws)
current_y_px = current_y * v_zoom
# create font, as tall as possible
font_height_pt = 18
font = ImageFont.truetype(self.FONT_PATH, font_height_pt)
# draw a tick every self.time_step seconds
for i in range(0, 1 + int(self.max_time), self.time_step):
# base x position
begin_px = i * pixels_per_second
# tick
left_px = begin_px - self.TICK_WIDTH
right_px = begin_px + self.TICK_WIDTH
top_px = current_y_px
bottom_px = current_y_px + v_zoom
draw.rectangle((left_px, top_px, right_px, bottom_px), fill=PlotterColors.BLACK)
# text
time_text = self._time_string(i)
left_px = begin_px + self.TICK_WIDTH + self.TEXT_MARGIN
top_px = current_y_px + (v_zoom - self.text_bounding_box(font_height_pt, time_text)[1]) // 2
draw.text((left_px, top_px), time_text, PlotterColors.BLACK, font=font) | python | def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this time scale to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image`
"""
# PIL object
draw = ImageDraw.Draw(image)
mws = self.rconf.mws
pixels_per_second = int(h_zoom / mws)
current_y_px = current_y * v_zoom
# create font, as tall as possible
font_height_pt = 18
font = ImageFont.truetype(self.FONT_PATH, font_height_pt)
# draw a tick every self.time_step seconds
for i in range(0, 1 + int(self.max_time), self.time_step):
# base x position
begin_px = i * pixels_per_second
# tick
left_px = begin_px - self.TICK_WIDTH
right_px = begin_px + self.TICK_WIDTH
top_px = current_y_px
bottom_px = current_y_px + v_zoom
draw.rectangle((left_px, top_px, right_px, bottom_px), fill=PlotterColors.BLACK)
# text
time_text = self._time_string(i)
left_px = begin_px + self.TICK_WIDTH + self.TEXT_MARGIN
top_px = current_y_px + (v_zoom - self.text_bounding_box(font_height_pt, time_text)[1]) // 2
draw.text((left_px, top_px), time_text, PlotterColors.BLACK, font=font) | [
"def",
"draw_png",
"(",
"self",
",",
"image",
",",
"h_zoom",
",",
"v_zoom",
",",
"current_y",
")",
":",
"# PIL object",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"mws",
"=",
"self",
".",
"rconf",
".",
"mws",
"pixels_per_second",
"=",
"i... | Draw this time scale to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image` | [
"Draw",
"this",
"time",
"scale",
"to",
"PNG",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L305-L341 | train | 226,938 |
readbeyond/aeneas | aeneas/plotter.py | PlotWaveform.draw_png | def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this waveform to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image`
"""
draw = ImageDraw.Draw(image)
mws = self.rconf.mws
rate = self.audio_file.audio_sample_rate
samples = self.audio_file.audio_samples
duration = self.audio_file.audio_length
current_y_px = current_y * v_zoom
half_waveform_px = (self.height // 2) * v_zoom
zero_y_px = current_y_px + half_waveform_px
samples_per_pixel = int(rate * mws / h_zoom)
pixels_per_second = int(h_zoom / mws)
windows = len(samples) // samples_per_pixel
if self.label is not None:
font_height_pt = 18
font = ImageFont.truetype(self.FONT_PATH, font_height_pt)
draw.text((0, current_y_px), self.label, PlotterColors.BLACK, font=font)
for i in range(windows):
x = i * samples_per_pixel
pos = numpy.clip(samples[x:(x + samples_per_pixel)], 0.0, 1.0)
mpos = numpy.max(pos) * half_waveform_px
if self.fast:
# just draw a simple version, mirroring max positive samples
draw.line((i, zero_y_px + mpos, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1)
else:
# draw a better version, taking min and std of positive and negative samples
neg = numpy.clip(samples[x:(x + samples_per_pixel)], -1.0, 0.0)
spos = numpy.std(pos) * half_waveform_px
sneg = numpy.std(neg) * half_waveform_px
mneg = numpy.min(neg) * half_waveform_px
draw.line((i, zero_y_px - mneg, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1)
draw.line((i, zero_y_px + sneg, i, zero_y_px - spos), fill=PlotterColors.AUDACITY_LIGHT_BLUE, width=1) | python | def draw_png(self, image, h_zoom, v_zoom, current_y):
"""
Draw this waveform to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image`
"""
draw = ImageDraw.Draw(image)
mws = self.rconf.mws
rate = self.audio_file.audio_sample_rate
samples = self.audio_file.audio_samples
duration = self.audio_file.audio_length
current_y_px = current_y * v_zoom
half_waveform_px = (self.height // 2) * v_zoom
zero_y_px = current_y_px + half_waveform_px
samples_per_pixel = int(rate * mws / h_zoom)
pixels_per_second = int(h_zoom / mws)
windows = len(samples) // samples_per_pixel
if self.label is not None:
font_height_pt = 18
font = ImageFont.truetype(self.FONT_PATH, font_height_pt)
draw.text((0, current_y_px), self.label, PlotterColors.BLACK, font=font)
for i in range(windows):
x = i * samples_per_pixel
pos = numpy.clip(samples[x:(x + samples_per_pixel)], 0.0, 1.0)
mpos = numpy.max(pos) * half_waveform_px
if self.fast:
# just draw a simple version, mirroring max positive samples
draw.line((i, zero_y_px + mpos, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1)
else:
# draw a better version, taking min and std of positive and negative samples
neg = numpy.clip(samples[x:(x + samples_per_pixel)], -1.0, 0.0)
spos = numpy.std(pos) * half_waveform_px
sneg = numpy.std(neg) * half_waveform_px
mneg = numpy.min(neg) * half_waveform_px
draw.line((i, zero_y_px - mneg, i, zero_y_px - mpos), fill=PlotterColors.AUDACITY_DARK_BLUE, width=1)
draw.line((i, zero_y_px + sneg, i, zero_y_px - spos), fill=PlotterColors.AUDACITY_LIGHT_BLUE, width=1) | [
"def",
"draw_png",
"(",
"self",
",",
"image",
",",
"h_zoom",
",",
"v_zoom",
",",
"current_y",
")",
":",
"draw",
"=",
"ImageDraw",
".",
"Draw",
"(",
"image",
")",
"mws",
"=",
"self",
".",
"rconf",
".",
"mws",
"rate",
"=",
"self",
".",
"audio_file",
... | Draw this waveform to PNG.
:param image: the image to draw onto
:param int h_zoom: the horizontal zoom
:param int v_zoom: the vertical zoom
:param int current_y: the current y offset, in modules
:type image: :class:`PIL.Image` | [
"Draw",
"this",
"waveform",
"to",
"PNG",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/plotter.py#L524-L567 | train | 226,939 |
readbeyond/aeneas | aeneas/tools/run_sd.py | RunSDCLI.print_result | def print_result(self, audio_len, start, end):
"""
Print result of SD.
:param audio_len: the length of the entire audio file, in seconds
:type audio_len: float
:param start: the start position of the spoken text
:type start: float
:param end: the end position of the spoken text
:type end: float
"""
msg = []
zero = 0
head_len = start
text_len = end - start
tail_len = audio_len - end
msg.append(u"")
msg.append(u"Head: %.3f %.3f (%.3f)" % (zero, start, head_len))
msg.append(u"Text: %.3f %.3f (%.3f)" % (start, end, text_len))
msg.append(u"Tail: %.3f %.3f (%.3f)" % (end, audio_len, tail_len))
msg.append(u"")
zero_h = gf.time_to_hhmmssmmm(0)
start_h = gf.time_to_hhmmssmmm(start)
end_h = gf.time_to_hhmmssmmm(end)
audio_len_h = gf.time_to_hhmmssmmm(audio_len)
head_len_h = gf.time_to_hhmmssmmm(head_len)
text_len_h = gf.time_to_hhmmssmmm(text_len)
tail_len_h = gf.time_to_hhmmssmmm(tail_len)
msg.append("Head: %s %s (%s)" % (zero_h, start_h, head_len_h))
msg.append("Text: %s %s (%s)" % (start_h, end_h, text_len_h))
msg.append("Tail: %s %s (%s)" % (end_h, audio_len_h, tail_len_h))
msg.append(u"")
self.print_info(u"\n".join(msg)) | python | def print_result(self, audio_len, start, end):
"""
Print result of SD.
:param audio_len: the length of the entire audio file, in seconds
:type audio_len: float
:param start: the start position of the spoken text
:type start: float
:param end: the end position of the spoken text
:type end: float
"""
msg = []
zero = 0
head_len = start
text_len = end - start
tail_len = audio_len - end
msg.append(u"")
msg.append(u"Head: %.3f %.3f (%.3f)" % (zero, start, head_len))
msg.append(u"Text: %.3f %.3f (%.3f)" % (start, end, text_len))
msg.append(u"Tail: %.3f %.3f (%.3f)" % (end, audio_len, tail_len))
msg.append(u"")
zero_h = gf.time_to_hhmmssmmm(0)
start_h = gf.time_to_hhmmssmmm(start)
end_h = gf.time_to_hhmmssmmm(end)
audio_len_h = gf.time_to_hhmmssmmm(audio_len)
head_len_h = gf.time_to_hhmmssmmm(head_len)
text_len_h = gf.time_to_hhmmssmmm(text_len)
tail_len_h = gf.time_to_hhmmssmmm(tail_len)
msg.append("Head: %s %s (%s)" % (zero_h, start_h, head_len_h))
msg.append("Text: %s %s (%s)" % (start_h, end_h, text_len_h))
msg.append("Tail: %s %s (%s)" % (end_h, audio_len_h, tail_len_h))
msg.append(u"")
self.print_info(u"\n".join(msg)) | [
"def",
"print_result",
"(",
"self",
",",
"audio_len",
",",
"start",
",",
"end",
")",
":",
"msg",
"=",
"[",
"]",
"zero",
"=",
"0",
"head_len",
"=",
"start",
"text_len",
"=",
"end",
"-",
"start",
"tail_len",
"=",
"audio_len",
"-",
"end",
"msg",
".",
... | Print result of SD.
:param audio_len: the length of the entire audio file, in seconds
:type audio_len: float
:param start: the start position of the spoken text
:type start: float
:param end: the end position of the spoken text
:type end: float | [
"Print",
"result",
"of",
"SD",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/run_sd.py#L171-L203 | train | 226,940 |
readbeyond/aeneas | aeneas/task.py | Task.sync_map_leaves | def sync_map_leaves(self, fragment_type=None):
"""
Return the list of non-empty leaves
in the sync map associated with the task.
If ``fragment_type`` has been specified,
return only leaves of that fragment type.
:param int fragment_type: type of fragment to return
:rtype: list
.. versionadded:: 1.7.0
"""
if (self.sync_map is None) or (self.sync_map.fragments_tree is None):
return []
return [f for f in self.sync_map.leaves(fragment_type)] | python | def sync_map_leaves(self, fragment_type=None):
"""
Return the list of non-empty leaves
in the sync map associated with the task.
If ``fragment_type`` has been specified,
return only leaves of that fragment type.
:param int fragment_type: type of fragment to return
:rtype: list
.. versionadded:: 1.7.0
"""
if (self.sync_map is None) or (self.sync_map.fragments_tree is None):
return []
return [f for f in self.sync_map.leaves(fragment_type)] | [
"def",
"sync_map_leaves",
"(",
"self",
",",
"fragment_type",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"sync_map",
"is",
"None",
")",
"or",
"(",
"self",
".",
"sync_map",
".",
"fragments_tree",
"is",
"None",
")",
":",
"return",
"[",
"]",
"return",
... | Return the list of non-empty leaves
in the sync map associated with the task.
If ``fragment_type`` has been specified,
return only leaves of that fragment type.
:param int fragment_type: type of fragment to return
:rtype: list
.. versionadded:: 1.7.0 | [
"Return",
"the",
"list",
"of",
"non",
"-",
"empty",
"leaves",
"in",
"the",
"sync",
"map",
"associated",
"with",
"the",
"task",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L149-L164 | train | 226,941 |
readbeyond/aeneas | aeneas/task.py | Task.output_sync_map_file | def output_sync_map_file(self, container_root_path=None):
"""
Output the sync map file for this task.
If ``container_root_path`` is specified,
the output sync map file will be created
at the path obtained by joining
the ``container_root_path`` and the relative path
of the sync map inside the container.
Otherwise, the sync map file will be created at the path
``self.sync_map_file_path_absolute``.
Return the the path of the sync map file created,
or ``None`` if an error occurred.
:param string container_root_path: the path to the root directory
for the output container
:rtype: string
"""
if self.sync_map is None:
self.log_exc(u"The sync_map object has not been set", None, True, TypeError)
if (container_root_path is not None) and (self.sync_map_file_path is None):
self.log_exc(u"The (internal) path of the sync map has been set", None, True, TypeError)
self.log([u"container_root_path is %s", container_root_path])
self.log([u"self.sync_map_file_path is %s", self.sync_map_file_path])
self.log([u"self.sync_map_file_path_absolute is %s", self.sync_map_file_path_absolute])
if (container_root_path is not None) and (self.sync_map_file_path is not None):
path = os.path.join(container_root_path, self.sync_map_file_path)
elif self.sync_map_file_path_absolute:
path = self.sync_map_file_path_absolute
gf.ensure_parent_directory(path)
self.log([u"Output sync map to %s", path])
eaf_audio_ref = self.configuration["o_eaf_audio_ref"]
head_tail_format = self.configuration["o_h_t_format"]
levels = self.configuration["o_levels"]
smil_audio_ref = self.configuration["o_smil_audio_ref"]
smil_page_ref = self.configuration["o_smil_page_ref"]
sync_map_format = self.configuration["o_format"]
self.log([u"eaf_audio_ref is %s", eaf_audio_ref])
self.log([u"head_tail_format is %s", head_tail_format])
self.log([u"levels is %s", levels])
self.log([u"smil_audio_ref is %s", smil_audio_ref])
self.log([u"smil_page_ref is %s", smil_page_ref])
self.log([u"sync_map_format is %s", sync_map_format])
self.log(u"Calling sync_map.write...")
parameters = {
gc.PPN_TASK_OS_FILE_EAF_AUDIO_REF: eaf_audio_ref,
gc.PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT: head_tail_format,
gc.PPN_TASK_OS_FILE_LEVELS: levels,
gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF: smil_audio_ref,
gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF: smil_page_ref,
}
self.sync_map.write(sync_map_format, path, parameters)
self.log(u"Calling sync_map.write... done")
return path | python | def output_sync_map_file(self, container_root_path=None):
"""
Output the sync map file for this task.
If ``container_root_path`` is specified,
the output sync map file will be created
at the path obtained by joining
the ``container_root_path`` and the relative path
of the sync map inside the container.
Otherwise, the sync map file will be created at the path
``self.sync_map_file_path_absolute``.
Return the the path of the sync map file created,
or ``None`` if an error occurred.
:param string container_root_path: the path to the root directory
for the output container
:rtype: string
"""
if self.sync_map is None:
self.log_exc(u"The sync_map object has not been set", None, True, TypeError)
if (container_root_path is not None) and (self.sync_map_file_path is None):
self.log_exc(u"The (internal) path of the sync map has been set", None, True, TypeError)
self.log([u"container_root_path is %s", container_root_path])
self.log([u"self.sync_map_file_path is %s", self.sync_map_file_path])
self.log([u"self.sync_map_file_path_absolute is %s", self.sync_map_file_path_absolute])
if (container_root_path is not None) and (self.sync_map_file_path is not None):
path = os.path.join(container_root_path, self.sync_map_file_path)
elif self.sync_map_file_path_absolute:
path = self.sync_map_file_path_absolute
gf.ensure_parent_directory(path)
self.log([u"Output sync map to %s", path])
eaf_audio_ref = self.configuration["o_eaf_audio_ref"]
head_tail_format = self.configuration["o_h_t_format"]
levels = self.configuration["o_levels"]
smil_audio_ref = self.configuration["o_smil_audio_ref"]
smil_page_ref = self.configuration["o_smil_page_ref"]
sync_map_format = self.configuration["o_format"]
self.log([u"eaf_audio_ref is %s", eaf_audio_ref])
self.log([u"head_tail_format is %s", head_tail_format])
self.log([u"levels is %s", levels])
self.log([u"smil_audio_ref is %s", smil_audio_ref])
self.log([u"smil_page_ref is %s", smil_page_ref])
self.log([u"sync_map_format is %s", sync_map_format])
self.log(u"Calling sync_map.write...")
parameters = {
gc.PPN_TASK_OS_FILE_EAF_AUDIO_REF: eaf_audio_ref,
gc.PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT: head_tail_format,
gc.PPN_TASK_OS_FILE_LEVELS: levels,
gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF: smil_audio_ref,
gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF: smil_page_ref,
}
self.sync_map.write(sync_map_format, path, parameters)
self.log(u"Calling sync_map.write... done")
return path | [
"def",
"output_sync_map_file",
"(",
"self",
",",
"container_root_path",
"=",
"None",
")",
":",
"if",
"self",
".",
"sync_map",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The sync_map object has not been set\"",
",",
"None",
",",
"True",
",",
"TypeError",... | Output the sync map file for this task.
If ``container_root_path`` is specified,
the output sync map file will be created
at the path obtained by joining
the ``container_root_path`` and the relative path
of the sync map inside the container.
Otherwise, the sync map file will be created at the path
``self.sync_map_file_path_absolute``.
Return the the path of the sync map file created,
or ``None`` if an error occurred.
:param string container_root_path: the path to the root directory
for the output container
:rtype: string | [
"Output",
"the",
"sync",
"map",
"file",
"for",
"this",
"task",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L166-L227 | train | 226,942 |
readbeyond/aeneas | aeneas/task.py | Task._populate_audio_file | def _populate_audio_file(self):
"""
Create the ``self.audio_file`` object by reading
the audio file at ``self.audio_file_path_absolute``.
"""
self.log(u"Populate audio file...")
if self.audio_file_path_absolute is not None:
self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute])
self.audio_file = AudioFile(
file_path=self.audio_file_path_absolute,
logger=self.logger
)
self.audio_file.read_properties()
else:
self.log(u"audio_file_path_absolute is None")
self.log(u"Populate audio file... done") | python | def _populate_audio_file(self):
"""
Create the ``self.audio_file`` object by reading
the audio file at ``self.audio_file_path_absolute``.
"""
self.log(u"Populate audio file...")
if self.audio_file_path_absolute is not None:
self.log([u"audio_file_path_absolute is '%s'", self.audio_file_path_absolute])
self.audio_file = AudioFile(
file_path=self.audio_file_path_absolute,
logger=self.logger
)
self.audio_file.read_properties()
else:
self.log(u"audio_file_path_absolute is None")
self.log(u"Populate audio file... done") | [
"def",
"_populate_audio_file",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Populate audio file...\"",
")",
"if",
"self",
".",
"audio_file_path_absolute",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"[",
"u\"audio_file_path_absolute is '%s'\"",
",",
... | Create the ``self.audio_file`` object by reading
the audio file at ``self.audio_file_path_absolute``. | [
"Create",
"the",
"self",
".",
"audio_file",
"object",
"by",
"reading",
"the",
"audio",
"file",
"at",
"self",
".",
"audio_file_path_absolute",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L229-L244 | train | 226,943 |
readbeyond/aeneas | aeneas/task.py | Task._populate_text_file | def _populate_text_file(self):
"""
Create the ``self.text_file`` object by reading
the text file at ``self.text_file_path_absolute``.
"""
self.log(u"Populate text file...")
if (
(self.text_file_path_absolute is not None) and
(self.configuration["language"] is not None)
):
# the following values might be None
parameters = {
gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX: self.configuration["i_t_ignore_regex"],
gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP: self.configuration["i_t_transliterate_map"],
gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR: self.configuration["i_t_mplain_word_separator"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: self.configuration["i_t_munparsed_l1_id_regex"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: self.configuration["i_t_munparsed_l2_id_regex"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: self.configuration["i_t_munparsed_l3_id_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: self.configuration["i_t_unparsed_class_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: self.configuration["i_t_unparsed_id_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: self.configuration["i_t_unparsed_id_sort"],
gc.PPN_TASK_OS_FILE_ID_REGEX: self.configuration["o_id_regex"]
}
self.text_file = TextFile(
file_path=self.text_file_path_absolute,
file_format=self.configuration["i_t_format"],
parameters=parameters,
logger=self.logger
)
self.text_file.set_language(self.configuration["language"])
else:
self.log(u"text_file_path_absolute and/or language is None")
self.log(u"Populate text file... done") | python | def _populate_text_file(self):
"""
Create the ``self.text_file`` object by reading
the text file at ``self.text_file_path_absolute``.
"""
self.log(u"Populate text file...")
if (
(self.text_file_path_absolute is not None) and
(self.configuration["language"] is not None)
):
# the following values might be None
parameters = {
gc.PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX: self.configuration["i_t_ignore_regex"],
gc.PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP: self.configuration["i_t_transliterate_map"],
gc.PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR: self.configuration["i_t_mplain_word_separator"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: self.configuration["i_t_munparsed_l1_id_regex"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: self.configuration["i_t_munparsed_l2_id_regex"],
gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: self.configuration["i_t_munparsed_l3_id_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: self.configuration["i_t_unparsed_class_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: self.configuration["i_t_unparsed_id_regex"],
gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: self.configuration["i_t_unparsed_id_sort"],
gc.PPN_TASK_OS_FILE_ID_REGEX: self.configuration["o_id_regex"]
}
self.text_file = TextFile(
file_path=self.text_file_path_absolute,
file_format=self.configuration["i_t_format"],
parameters=parameters,
logger=self.logger
)
self.text_file.set_language(self.configuration["language"])
else:
self.log(u"text_file_path_absolute and/or language is None")
self.log(u"Populate text file... done") | [
"def",
"_populate_text_file",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Populate text file...\"",
")",
"if",
"(",
"(",
"self",
".",
"text_file_path_absolute",
"is",
"not",
"None",
")",
"and",
"(",
"self",
".",
"configuration",
"[",
"\"language\"",
... | Create the ``self.text_file`` object by reading
the text file at ``self.text_file_path_absolute``. | [
"Create",
"the",
"self",
".",
"text_file",
"object",
"by",
"reading",
"the",
"text",
"file",
"at",
"self",
".",
"text_file_path_absolute",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/task.py#L246-L278 | train | 226,944 |
readbeyond/aeneas | aeneas/syncmap/smfgxml.py | SyncMapFormatGenericXML._tree_to_string | def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):
"""
Return an ``lxml`` tree as a Unicode string.
"""
from lxml import etree
return gf.safe_unicode(etree.tostring(
root_element,
encoding="UTF-8",
method="xml",
xml_declaration=xml_declaration,
pretty_print=pretty_print
)) | python | def _tree_to_string(cls, root_element, xml_declaration=True, pretty_print=True):
"""
Return an ``lxml`` tree as a Unicode string.
"""
from lxml import etree
return gf.safe_unicode(etree.tostring(
root_element,
encoding="UTF-8",
method="xml",
xml_declaration=xml_declaration,
pretty_print=pretty_print
)) | [
"def",
"_tree_to_string",
"(",
"cls",
",",
"root_element",
",",
"xml_declaration",
"=",
"True",
",",
"pretty_print",
"=",
"True",
")",
":",
"from",
"lxml",
"import",
"etree",
"return",
"gf",
".",
"safe_unicode",
"(",
"etree",
".",
"tostring",
"(",
"root_elem... | Return an ``lxml`` tree as a Unicode string. | [
"Return",
"an",
"lxml",
"tree",
"as",
"a",
"Unicode",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/smfgxml.py#L63-L74 | train | 226,945 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.print_generic | def print_generic(self, msg, prefix=None):
"""
Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string
"""
if prefix is None:
self._log(msg, Logger.INFO)
else:
self._log(msg, prefix)
if self.use_sys:
if (prefix is not None) and (prefix in self.PREFIX_TO_PRINT_FUNCTION):
self.PREFIX_TO_PRINT_FUNCTION[prefix](msg)
else:
gf.safe_print(msg) | python | def print_generic(self, msg, prefix=None):
"""
Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string
"""
if prefix is None:
self._log(msg, Logger.INFO)
else:
self._log(msg, prefix)
if self.use_sys:
if (prefix is not None) and (prefix in self.PREFIX_TO_PRINT_FUNCTION):
self.PREFIX_TO_PRINT_FUNCTION[prefix](msg)
else:
gf.safe_print(msg) | [
"def",
"print_generic",
"(",
"self",
",",
"msg",
",",
"prefix",
"=",
"None",
")",
":",
"if",
"prefix",
"is",
"None",
":",
"self",
".",
"_log",
"(",
"msg",
",",
"Logger",
".",
"INFO",
")",
"else",
":",
"self",
".",
"_log",
"(",
"msg",
",",
"prefix... | Print a message and log it.
:param msg: the message
:type msg: Unicode string
:param prefix: the (optional) prefix
:type prefix: Unicode string | [
"Print",
"a",
"message",
"and",
"log",
"it",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L109-L126 | train | 226,946 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.print_name_version | def print_name_version(self):
"""
Print program name and version and exit.
:rtype: int
"""
if self.use_sys:
self.print_generic(u"%s v%s" % (self.NAME, aeneas_version))
return self.exit(self.HELP_EXIT_CODE) | python | def print_name_version(self):
"""
Print program name and version and exit.
:rtype: int
"""
if self.use_sys:
self.print_generic(u"%s v%s" % (self.NAME, aeneas_version))
return self.exit(self.HELP_EXIT_CODE) | [
"def",
"print_name_version",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_sys",
":",
"self",
".",
"print_generic",
"(",
"u\"%s v%s\"",
"%",
"(",
"self",
".",
"NAME",
",",
"aeneas_version",
")",
")",
"return",
"self",
".",
"exit",
"(",
"self",
".",
"H... | Print program name and version and exit.
:rtype: int | [
"Print",
"program",
"name",
"and",
"version",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L260-L268 | train | 226,947 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.print_rconf_parameters | def print_rconf_parameters(self):
"""
Print the list of runtime configuration parameters and exit.
"""
if self.use_sys:
self.print_info(u"Available runtime configuration parameters:")
self.print_generic(u"\n" + u"\n".join(self.RCONF_PARAMETERS) + u"\n")
return self.exit(self.HELP_EXIT_CODE) | python | def print_rconf_parameters(self):
"""
Print the list of runtime configuration parameters and exit.
"""
if self.use_sys:
self.print_info(u"Available runtime configuration parameters:")
self.print_generic(u"\n" + u"\n".join(self.RCONF_PARAMETERS) + u"\n")
return self.exit(self.HELP_EXIT_CODE) | [
"def",
"print_rconf_parameters",
"(",
"self",
")",
":",
"if",
"self",
".",
"use_sys",
":",
"self",
".",
"print_info",
"(",
"u\"Available runtime configuration parameters:\"",
")",
"self",
".",
"print_generic",
"(",
"u\"\\n\"",
"+",
"u\"\\n\"",
".",
"join",
"(",
... | Print the list of runtime configuration parameters and exit. | [
"Print",
"the",
"list",
"of",
"runtime",
"configuration",
"parameters",
"and",
"exit",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L270-L277 | train | 226,948 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.has_option | def has_option(self, target):
"""
Return ``True`` if the actual arguments include
the specified ``target`` option or,
if ``target`` is a list of options,
at least one of them.
:param target: the option or a list of options
:type target: Unicode string or list of Unicode strings
:rtype: bool
"""
if isinstance(target, list):
target_set = set(target)
else:
target_set = set([target])
return len(target_set & set(self.actual_arguments)) > 0 | python | def has_option(self, target):
"""
Return ``True`` if the actual arguments include
the specified ``target`` option or,
if ``target`` is a list of options,
at least one of them.
:param target: the option or a list of options
:type target: Unicode string or list of Unicode strings
:rtype: bool
"""
if isinstance(target, list):
target_set = set(target)
else:
target_set = set([target])
return len(target_set & set(self.actual_arguments)) > 0 | [
"def",
"has_option",
"(",
"self",
",",
"target",
")",
":",
"if",
"isinstance",
"(",
"target",
",",
"list",
")",
":",
"target_set",
"=",
"set",
"(",
"target",
")",
"else",
":",
"target_set",
"=",
"set",
"(",
"[",
"target",
"]",
")",
"return",
"len",
... | Return ``True`` if the actual arguments include
the specified ``target`` option or,
if ``target`` is a list of options,
at least one of them.
:param target: the option or a list of options
:type target: Unicode string or list of Unicode strings
:rtype: bool | [
"Return",
"True",
"if",
"the",
"actual",
"arguments",
"include",
"the",
"specified",
"target",
"option",
"or",
"if",
"target",
"is",
"a",
"list",
"of",
"options",
"at",
"least",
"one",
"of",
"them",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L387-L402 | train | 226,949 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.check_c_extensions | def check_c_extensions(self, name=None):
"""
If C extensions cannot be run, emit a warning
and return ``False``. Otherwise return ``True``.
If ``name`` is not ``None``, check just
the C extension with that name.
:param name: the name of the Python C extension to test
:type name: string
:rtype: bool
"""
if not gf.can_run_c_extension(name=name):
if name is None:
self.print_warning(u"Unable to load Python C Extensions")
else:
self.print_warning(u"Unable to load Python C Extension %s" % (name))
self.print_warning(u"Running the slower pure Python code")
self.print_warning(u"See the documentation for directions to compile the Python C Extensions")
return False
return True | python | def check_c_extensions(self, name=None):
"""
If C extensions cannot be run, emit a warning
and return ``False``. Otherwise return ``True``.
If ``name`` is not ``None``, check just
the C extension with that name.
:param name: the name of the Python C extension to test
:type name: string
:rtype: bool
"""
if not gf.can_run_c_extension(name=name):
if name is None:
self.print_warning(u"Unable to load Python C Extensions")
else:
self.print_warning(u"Unable to load Python C Extension %s" % (name))
self.print_warning(u"Running the slower pure Python code")
self.print_warning(u"See the documentation for directions to compile the Python C Extensions")
return False
return True | [
"def",
"check_c_extensions",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"if",
"not",
"gf",
".",
"can_run_c_extension",
"(",
"name",
"=",
"name",
")",
":",
"if",
"name",
"is",
"None",
":",
"self",
".",
"print_warning",
"(",
"u\"Unable to load Python C... | If C extensions cannot be run, emit a warning
and return ``False``. Otherwise return ``True``.
If ``name`` is not ``None``, check just
the C extension with that name.
:param name: the name of the Python C extension to test
:type name: string
:rtype: bool | [
"If",
"C",
"extensions",
"cannot",
"be",
"run",
"emit",
"a",
"warning",
"and",
"return",
"False",
".",
"Otherwise",
"return",
"True",
".",
"If",
"name",
"is",
"not",
"None",
"check",
"just",
"the",
"C",
"extension",
"with",
"that",
"name",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L437-L456 | train | 226,950 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.check_output_file | def check_output_file(self, path):
"""
If the given path cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output file
:type path: string (path)
:rtype: bool
"""
if not gf.file_can_be_written(path):
self.print_error(u"Unable to create file '%s'" % (path))
self.print_error(u"Make sure the file path is written/escaped correctly and that you have write permission on it")
return False
return True | python | def check_output_file(self, path):
"""
If the given path cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output file
:type path: string (path)
:rtype: bool
"""
if not gf.file_can_be_written(path):
self.print_error(u"Unable to create file '%s'" % (path))
self.print_error(u"Make sure the file path is written/escaped correctly and that you have write permission on it")
return False
return True | [
"def",
"check_output_file",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"gf",
".",
"file_can_be_written",
"(",
"path",
")",
":",
"self",
".",
"print_error",
"(",
"u\"Unable to create file '%s'\"",
"%",
"(",
"path",
")",
")",
"self",
".",
"print_error",
... | If the given path cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output file
:type path: string (path)
:rtype: bool | [
"If",
"the",
"given",
"path",
"cannot",
"be",
"written",
"emit",
"an",
"error",
"and",
"return",
"False",
".",
"Otherwise",
"return",
"True",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L488-L501 | train | 226,951 |
readbeyond/aeneas | aeneas/tools/abstract_cli_program.py | AbstractCLIProgram.check_output_directory | def check_output_directory(self, path):
"""
If the given directory cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output directory
:type path: string (path)
:rtype: bool
"""
if not os.path.isdir(path):
self.print_error(u"Directory '%s' does not exist" % (path))
return False
test_file = os.path.join(path, u"file.test")
if not gf.file_can_be_written(test_file):
self.print_error(u"Unable to write inside directory '%s'" % (path))
self.print_error(u"Make sure the directory path is written/escaped correctly and that you have write permission on it")
return False
return True | python | def check_output_directory(self, path):
"""
If the given directory cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output directory
:type path: string (path)
:rtype: bool
"""
if not os.path.isdir(path):
self.print_error(u"Directory '%s' does not exist" % (path))
return False
test_file = os.path.join(path, u"file.test")
if not gf.file_can_be_written(test_file):
self.print_error(u"Unable to write inside directory '%s'" % (path))
self.print_error(u"Make sure the directory path is written/escaped correctly and that you have write permission on it")
return False
return True | [
"def",
"check_output_directory",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"print_error",
"(",
"u\"Directory '%s' does not exist\"",
"%",
"(",
"path",
")",
")",
"return",
"False",
... | If the given directory cannot be written, emit an error
and return ``False``. Otherwise return ``True``.
:param path: the path of the output directory
:type path: string (path)
:rtype: bool | [
"If",
"the",
"given",
"directory",
"cannot",
"be",
"written",
"emit",
"an",
"error",
"and",
"return",
"False",
".",
"Otherwise",
"return",
"True",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/tools/abstract_cli_program.py#L503-L520 | train | 226,952 |
readbeyond/aeneas | aeneas/container.py | Container.is_safe | def is_safe(self):
"""
Return ``True`` if the container can be safely extracted,
that is, if all its entries are safe, ``False`` otherwise.
:rtype: bool
:raises: same as :func:`~aeneas.container.Container.entries`
"""
self.log(u"Checking if this container is safe")
for entry in self.entries:
if not self.is_entry_safe(entry):
self.log([u"This container is not safe: found unsafe entry '%s'", entry])
return False
self.log(u"This container is safe")
return True | python | def is_safe(self):
"""
Return ``True`` if the container can be safely extracted,
that is, if all its entries are safe, ``False`` otherwise.
:rtype: bool
:raises: same as :func:`~aeneas.container.Container.entries`
"""
self.log(u"Checking if this container is safe")
for entry in self.entries:
if not self.is_entry_safe(entry):
self.log([u"This container is not safe: found unsafe entry '%s'", entry])
return False
self.log(u"This container is safe")
return True | [
"def",
"is_safe",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Checking if this container is safe\"",
")",
"for",
"entry",
"in",
"self",
".",
"entries",
":",
"if",
"not",
"self",
".",
"is_entry_safe",
"(",
"entry",
")",
":",
"self",
".",
"log",
"(... | Return ``True`` if the container can be safely extracted,
that is, if all its entries are safe, ``False`` otherwise.
:rtype: bool
:raises: same as :func:`~aeneas.container.Container.entries` | [
"Return",
"True",
"if",
"the",
"container",
"can",
"be",
"safely",
"extracted",
"that",
"is",
"if",
"all",
"its",
"entries",
"are",
"safe",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L186-L200 | train | 226,953 |
readbeyond/aeneas | aeneas/container.py | Container.entries | def entries(self):
"""
Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.)
"""
self.log(u"Getting entries")
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
return self.actual_container.entries | python | def entries(self):
"""
Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.)
"""
self.log(u"Getting entries")
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
return self.actual_container.entries | [
"def",
"entries",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Getting entries\"",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"This container does not exist. Wrong path?\"",
",",
"None",
",",
"True",
",",
... | Return the sorted list of entries in this container,
each represented by its full path inside the container.
:rtype: list of strings (path)
:raises: TypeError: if this container does not exist
:raises: OSError: if an error occurred reading the given container
(e.g., empty file, damaged file, etc.) | [
"Return",
"the",
"sorted",
"list",
"of",
"entries",
"in",
"this",
"container",
"each",
"represented",
"by",
"its",
"full",
"path",
"inside",
"the",
"container",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L218-L233 | train | 226,954 |
readbeyond/aeneas | aeneas/container.py | Container.find_entry | def find_entry(self, entry, exact=True):
"""
Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if exact:
self.log([u"Finding entry '%s' with exact=True", entry])
if entry in self.entries:
self.log([u"Found entry '%s'", entry])
return entry
else:
self.log([u"Finding entry '%s' with exact=False", entry])
for ent in self.entries:
if os.path.basename(ent) == entry:
self.log([u"Found entry '%s'", ent])
return ent
self.log([u"Entry '%s' not found", entry])
return None | python | def find_entry(self, entry, exact=True):
"""
Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if exact:
self.log([u"Finding entry '%s' with exact=True", entry])
if entry in self.entries:
self.log([u"Found entry '%s'", entry])
return entry
else:
self.log([u"Finding entry '%s' with exact=False", entry])
for ent in self.entries:
if os.path.basename(ent) == entry:
self.log([u"Found entry '%s'", ent])
return ent
self.log([u"Entry '%s' not found", entry])
return None | [
"def",
"find_entry",
"(",
"self",
",",
"entry",
",",
"exact",
"=",
"True",
")",
":",
"if",
"exact",
":",
"self",
".",
"log",
"(",
"[",
"u\"Finding entry '%s' with exact=True\"",
",",
"entry",
"]",
")",
"if",
"entry",
"in",
"self",
".",
"entries",
":",
... | Return the full path to the first entry whose file name equals
the given ``entry`` path.
Return ``None`` if the entry cannot be found.
If ``exact`` is ``True``, the path must be exact,
otherwise the comparison is done only on the file name.
Example: ::
entry = "config.txt"
matches: ::
config.txt (if exact == True or exact == False)
foo/config.txt (if exact == False)
foo/bar/config.txt (if exact == False)
:param string entry: the entry name to be searched for
:param bool exact: look for the exact entry path
:rtype: string
:raises: same as :func:`~aeneas.container.Container.entries` | [
"Return",
"the",
"full",
"path",
"to",
"the",
"first",
"entry",
"whose",
"file",
"name",
"equals",
"the",
"given",
"entry",
"path",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L235-L272 | train | 226,955 |
readbeyond/aeneas | aeneas/container.py | Container.read_entry | def read_entry(self, entry):
"""
Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if not self.is_entry_safe(entry):
self.log([u"Accessing entry '%s' is not safe", entry])
return None
if entry not in self.entries:
self.log([u"Entry '%s' not found in this container", entry])
return None
self.log([u"Reading contents of entry '%s'", entry])
try:
return self.actual_container.read_entry(entry)
except:
self.log([u"An error occurred while reading the contents of '%s'", entry])
return None | python | def read_entry(self, entry):
"""
Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries`
"""
if not self.is_entry_safe(entry):
self.log([u"Accessing entry '%s' is not safe", entry])
return None
if entry not in self.entries:
self.log([u"Entry '%s' not found in this container", entry])
return None
self.log([u"Reading contents of entry '%s'", entry])
try:
return self.actual_container.read_entry(entry)
except:
self.log([u"An error occurred while reading the contents of '%s'", entry])
return None | [
"def",
"read_entry",
"(",
"self",
",",
"entry",
")",
":",
"if",
"not",
"self",
".",
"is_entry_safe",
"(",
"entry",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Accessing entry '%s' is not safe\"",
",",
"entry",
"]",
")",
"return",
"None",
"if",
"entry",
"... | Read the contents of an entry in this container,
and return them as a byte string.
Return ``None`` if the entry is not safe
or it cannot be found.
:rtype: byte string
:raises: same as :func:`~aeneas.container.Container.entries` | [
"Read",
"the",
"contents",
"of",
"an",
"entry",
"in",
"this",
"container",
"and",
"return",
"them",
"as",
"a",
"byte",
"string",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L274-L298 | train | 226,956 |
readbeyond/aeneas | aeneas/container.py | Container.decompress | def decompress(self, output_path):
"""
Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Decompressing the container into '%s'", output_path])
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(output_path):
self.log_exc(u"The output path is not an existing directory", None, True, ValueError)
if not self.is_safe:
self.log_exc(u"This container contains unsafe entries", None, True, ValueError)
self.actual_container.decompress(output_path) | python | def decompress(self, output_path):
"""
Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Decompressing the container into '%s'", output_path])
if not self.exists():
self.log_exc(u"This container does not exist. Wrong path?", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(output_path):
self.log_exc(u"The output path is not an existing directory", None, True, ValueError)
if not self.is_safe:
self.log_exc(u"This container contains unsafe entries", None, True, ValueError)
self.actual_container.decompress(output_path) | [
"def",
"decompress",
"(",
"self",
",",
"output_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Decompressing the container into '%s'\"",
",",
"output_path",
"]",
")",
"if",
"not",
"self",
".",
"exists",
"(",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"Th... | Decompress the entire container into the given directory.
:param string output_path: path of the destination directory
:raises: TypeError: if this container does not exist
:raises: ValueError: if this container contains unsafe entries,
or ``output_path`` is not an existing directory
:raises: OSError: if an error occurred decompressing the given container
(e.g., empty file, damaged file, etc.) | [
"Decompress",
"the",
"entire",
"container",
"into",
"the",
"given",
"directory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L300-L320 | train | 226,957 |
readbeyond/aeneas | aeneas/container.py | Container.compress | def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Compressing '%s' into this container", input_path])
if self.file_path is None:
self.log_exc(u"The container path has not been set", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(input_path):
self.log_exc(u"The input path is not an existing directory", None, True, ValueError)
gf.ensure_parent_directory(input_path)
self.actual_container.compress(input_path) | python | def compress(self, input_path):
"""
Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.)
"""
self.log([u"Compressing '%s' into this container", input_path])
if self.file_path is None:
self.log_exc(u"The container path has not been set", None, True, TypeError)
if self.actual_container is None:
self.log_exc(u"The actual container object has not been set", None, True, TypeError)
if not gf.directory_exists(input_path):
self.log_exc(u"The input path is not an existing directory", None, True, ValueError)
gf.ensure_parent_directory(input_path)
self.actual_container.compress(input_path) | [
"def",
"compress",
"(",
"self",
",",
"input_path",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Compressing '%s' into this container\"",
",",
"input_path",
"]",
")",
"if",
"self",
".",
"file_path",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The conta... | Compress the contents of the given directory.
:param string input_path: path of the input directory
:raises: TypeError: if the container path has not been set
:raises: ValueError: if ``input_path`` is not an existing directory
:raises: OSError: if an error occurred compressing the given container
(e.g., empty file, damaged file, etc.) | [
"Compress",
"the",
"contents",
"of",
"the",
"given",
"directory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L322-L341 | train | 226,958 |
readbeyond/aeneas | aeneas/container.py | Container.exists | def exists(self):
"""
Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean
"""
return gf.file_exists(self.file_path) or gf.directory_exists(self.file_path) | python | def exists(self):
"""
Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean
"""
return gf.file_exists(self.file_path) or gf.directory_exists(self.file_path) | [
"def",
"exists",
"(",
"self",
")",
":",
"return",
"gf",
".",
"file_exists",
"(",
"self",
".",
"file_path",
")",
"or",
"gf",
".",
"directory_exists",
"(",
"self",
".",
"file_path",
")"
] | Return ``True`` if the container has its path set and it exists,
``False`` otherwise.
:rtype: boolean | [
"Return",
"True",
"if",
"the",
"container",
"has",
"its",
"path",
"set",
"and",
"it",
"exists",
"False",
"otherwise",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L343-L350 | train | 226,959 |
readbeyond/aeneas | aeneas/container.py | Container._set_actual_container | def _set_actual_container(self):
"""
Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory).
"""
# infer container format
if self.container_format is None:
self.log(u"Inferring actual container format...")
path_lowercased = self.file_path.lower()
self.log([u"Lowercased file path: '%s'", path_lowercased])
self.container_format = ContainerFormat.UNPACKED
for fmt in ContainerFormat.ALLOWED_FILE_VALUES:
if path_lowercased.endswith(fmt):
self.container_format = fmt
break
self.log(u"Inferring actual container format... done")
self.log([u"Inferred format: '%s'", self.container_format])
# set the actual container
self.log(u"Setting actual container...")
class_map = {
ContainerFormat.ZIP: (_ContainerZIP, None),
ContainerFormat.EPUB: (_ContainerZIP, None),
ContainerFormat.TAR: (_ContainerTAR, ""),
ContainerFormat.TAR_GZ: (_ContainerTAR, ":gz"),
ContainerFormat.TAR_BZ2: (_ContainerTAR, ":bz2"),
ContainerFormat.UNPACKED: (_ContainerUnpacked, None)
}
actual_class, variant = class_map[self.container_format]
self.actual_container = actual_class(
file_path=self.file_path,
variant=variant,
rconf=self.rconf,
logger=self.logger
)
self.log([u"Actual container format: '%s'", self.container_format])
self.log(u"Setting actual container... done") | python | def _set_actual_container(self):
"""
Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory).
"""
# infer container format
if self.container_format is None:
self.log(u"Inferring actual container format...")
path_lowercased = self.file_path.lower()
self.log([u"Lowercased file path: '%s'", path_lowercased])
self.container_format = ContainerFormat.UNPACKED
for fmt in ContainerFormat.ALLOWED_FILE_VALUES:
if path_lowercased.endswith(fmt):
self.container_format = fmt
break
self.log(u"Inferring actual container format... done")
self.log([u"Inferred format: '%s'", self.container_format])
# set the actual container
self.log(u"Setting actual container...")
class_map = {
ContainerFormat.ZIP: (_ContainerZIP, None),
ContainerFormat.EPUB: (_ContainerZIP, None),
ContainerFormat.TAR: (_ContainerTAR, ""),
ContainerFormat.TAR_GZ: (_ContainerTAR, ":gz"),
ContainerFormat.TAR_BZ2: (_ContainerTAR, ":bz2"),
ContainerFormat.UNPACKED: (_ContainerUnpacked, None)
}
actual_class, variant = class_map[self.container_format]
self.actual_container = actual_class(
file_path=self.file_path,
variant=variant,
rconf=self.rconf,
logger=self.logger
)
self.log([u"Actual container format: '%s'", self.container_format])
self.log(u"Setting actual container... done") | [
"def",
"_set_actual_container",
"(",
"self",
")",
":",
"# infer container format",
"if",
"self",
".",
"container_format",
"is",
"None",
":",
"self",
".",
"log",
"(",
"u\"Inferring actual container format...\"",
")",
"path_lowercased",
"=",
"self",
".",
"file_path",
... | Set the actual container, based on the specified container format.
If the container format is not specified,
infer it from the (lowercased) extension of the file path.
If the format cannot be inferred, it is assumed to be
of type :class:`~aeneas.container.ContainerFormat.UNPACKED`
(unpacked directory). | [
"Set",
"the",
"actual",
"container",
"based",
"on",
"the",
"specified",
"container",
"format",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/container.py#L352-L393 | train | 226,960 |
readbeyond/aeneas | aeneas/extra/ctw_speect.py | CustomTTSWrapper._synthesize_single_python_helper | def _synthesize_single_python_helper(
self,
text,
voice_code,
output_file_path=None,
return_audio_data=True
):
"""
This is an helper function to synthesize a single text fragment via a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data))
"""
# return zero if text is the empty string
if len(text) == 0:
#
# NOTE values of sample_rate, encoding, data
# do not matter if the duration is 0.000,
# so set them to None instead of the more precise:
# return (True, (TimeValue("0.000"), 16000, "pcm_s16le", numpy.array([])))
#
self.log(u"len(text) is zero: returning 0.000")
return (True, (TimeValue("0.000"), None, None, None))
#
# NOTE in this example, we assume that the Speect voice data files
# are located in the same directory of this .py source file
# and that the voice JSON file is called "voice.json"
#
# NOTE the voice_code value is ignored in this example,
# since we have only one TTS voice,
# but in general one might select a voice file to load,
# depending on voice_code;
# in fact, we could have created the ``voice`` object
# only once, in the constructor, instead of creating it
# each time this function is invoked,
# achieving slightly faster synthesis
#
voice_json_path = gf.safe_str(gf.absolute_path("voice.json", __file__))
voice = speect.SVoice(voice_json_path)
utt = voice.synth(text)
audio = utt.features["audio"]
if output_file_path is None:
self.log(u"output_file_path is None => not saving to file")
else:
self.log(u"output_file_path is not None => saving to file...")
# NOTE apparently, save_riff needs the path to be a byte string
audio.save_riff(gf.safe_str(output_file_path))
self.log(u"output_file_path is not None => saving to file... done")
# return immediately if returning audio data is not needed
if not return_audio_data:
self.log(u"return_audio_data is True => return immediately")
return (True, None)
# get length and data using speect Python API
self.log(u"return_audio_data is True => read and return audio data")
waveform = audio.get_audio_waveform()
audio_sample_rate = int(waveform["samplerate"])
audio_length = TimeValue(audio.num_samples() / audio_sample_rate)
audio_format = "pcm16"
audio_samples = numpy.fromstring(
waveform["samples"],
dtype=numpy.int16
).astype("float64") / 32768
return (True, (
audio_length,
audio_sample_rate,
audio_format,
audio_samples
)) | python | def _synthesize_single_python_helper(
self,
text,
voice_code,
output_file_path=None,
return_audio_data=True
):
"""
This is an helper function to synthesize a single text fragment via a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data))
"""
# return zero if text is the empty string
if len(text) == 0:
#
# NOTE values of sample_rate, encoding, data
# do not matter if the duration is 0.000,
# so set them to None instead of the more precise:
# return (True, (TimeValue("0.000"), 16000, "pcm_s16le", numpy.array([])))
#
self.log(u"len(text) is zero: returning 0.000")
return (True, (TimeValue("0.000"), None, None, None))
#
# NOTE in this example, we assume that the Speect voice data files
# are located in the same directory of this .py source file
# and that the voice JSON file is called "voice.json"
#
# NOTE the voice_code value is ignored in this example,
# since we have only one TTS voice,
# but in general one might select a voice file to load,
# depending on voice_code;
# in fact, we could have created the ``voice`` object
# only once, in the constructor, instead of creating it
# each time this function is invoked,
# achieving slightly faster synthesis
#
voice_json_path = gf.safe_str(gf.absolute_path("voice.json", __file__))
voice = speect.SVoice(voice_json_path)
utt = voice.synth(text)
audio = utt.features["audio"]
if output_file_path is None:
self.log(u"output_file_path is None => not saving to file")
else:
self.log(u"output_file_path is not None => saving to file...")
# NOTE apparently, save_riff needs the path to be a byte string
audio.save_riff(gf.safe_str(output_file_path))
self.log(u"output_file_path is not None => saving to file... done")
# return immediately if returning audio data is not needed
if not return_audio_data:
self.log(u"return_audio_data is True => return immediately")
return (True, None)
# get length and data using speect Python API
self.log(u"return_audio_data is True => read and return audio data")
waveform = audio.get_audio_waveform()
audio_sample_rate = int(waveform["samplerate"])
audio_length = TimeValue(audio.num_samples() / audio_sample_rate)
audio_format = "pcm16"
audio_samples = numpy.fromstring(
waveform["samples"],
dtype=numpy.int16
).astype("float64") / 32768
return (True, (
audio_length,
audio_sample_rate,
audio_format,
audio_samples
)) | [
"def",
"_synthesize_single_python_helper",
"(",
"self",
",",
"text",
",",
"voice_code",
",",
"output_file_path",
"=",
"None",
",",
"return_audio_data",
"=",
"True",
")",
":",
"# return zero if text is the empty string",
"if",
"len",
"(",
"text",
")",
"==",
"0",
":... | This is an helper function to synthesize a single text fragment via a Python call.
If ``output_file_path`` is ``None``,
the audio data will not persist to file at the end of the method.
:rtype: tuple (result, (duration, sample_rate, encoding, data)) | [
"This",
"is",
"an",
"helper",
"function",
"to",
"synthesize",
"a",
"single",
"text",
"fragment",
"via",
"a",
"Python",
"call",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/extra/ctw_speect.py#L91-L163 | train | 226,961 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer.analyze | def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
"""
try:
if config_string is not None:
self.log(u"Analyzing container with the given config string")
return self._analyze_txt_config(config_string=config_string)
elif self.container.has_config_xml:
self.log(u"Analyzing container with XML config file")
return self._analyze_xml_config(config_contents=None)
elif self.container.has_config_txt:
self.log(u"Analyzing container with TXT config file")
return self._analyze_txt_config(config_string=None)
else:
self.log(u"No configuration file in this container, returning None")
except (OSError, KeyError, TypeError) as exc:
self.log_exc(u"An unexpected error occurred while analyzing", exc, True, None)
return None | python | def analyze(self, config_string=None):
"""
Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None``
"""
try:
if config_string is not None:
self.log(u"Analyzing container with the given config string")
return self._analyze_txt_config(config_string=config_string)
elif self.container.has_config_xml:
self.log(u"Analyzing container with XML config file")
return self._analyze_xml_config(config_contents=None)
elif self.container.has_config_txt:
self.log(u"Analyzing container with TXT config file")
return self._analyze_txt_config(config_string=None)
else:
self.log(u"No configuration file in this container, returning None")
except (OSError, KeyError, TypeError) as exc:
self.log_exc(u"An unexpected error occurred while analyzing", exc, True, None)
return None | [
"def",
"analyze",
"(",
"self",
",",
"config_string",
"=",
"None",
")",
":",
"try",
":",
"if",
"config_string",
"is",
"not",
"None",
":",
"self",
".",
"log",
"(",
"u\"Analyzing container with the given config string\"",
")",
"return",
"self",
".",
"_analyze_txt_c... | Analyze the given container and
return the corresponding job object.
On error, it will return ``None``.
:param string config_string: the configuration string generated by wizard
:rtype: :class:`~aeneas.job.Job` or ``None`` | [
"Analyze",
"the",
"given",
"container",
"and",
"return",
"the",
"corresponding",
"job",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L72-L96 | train | 226,962 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._create_task | def _create_task(
self,
task_info,
config_string,
sync_map_root_directory,
job_os_hierarchy_type
):
"""
Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task`
"""
self.log(u"Converting config string to config dict")
parameters = gf.config_string_to_dict(config_string)
self.log(u"Creating task")
task = Task(config_string, logger=self.logger)
task.configuration["description"] = "Task %s" % task_info[0]
self.log([u"Task description: %s", task.configuration["description"]])
try:
task.configuration["language"] = parameters[gc.PPN_TASK_LANGUAGE]
self.log([u"Set language from task: '%s'", task.configuration["language"]])
except KeyError:
task.configuration["language"] = parameters[gc.PPN_JOB_LANGUAGE]
self.log([u"Set language from job: '%s'", task.configuration["language"]])
custom_id = task_info[0]
task.configuration["custom_id"] = custom_id
self.log([u"Task custom_id: %s", task.configuration["custom_id"]])
task.text_file_path = task_info[1]
self.log([u"Task text file path: %s", task.text_file_path])
task.audio_file_path = task_info[2]
self.log([u"Task audio file path: %s", task.audio_file_path])
task.sync_map_file_path = self._compute_sync_map_file_path(
sync_map_root_directory,
job_os_hierarchy_type,
custom_id,
task.configuration["o_name"]
)
self.log([u"Task sync map file path: %s", task.sync_map_file_path])
self.log(u"Replacing placeholder in os_file_smil_audio_ref")
task.configuration["o_smil_audio_ref"] = self._replace_placeholder(
task.configuration["o_smil_audio_ref"],
custom_id
)
self.log(u"Replacing placeholder in os_file_smil_page_ref")
task.configuration["o_smil_page_ref"] = self._replace_placeholder(
task.configuration["o_smil_page_ref"],
custom_id
)
self.log(u"Returning task")
return task | python | def _create_task(
self,
task_info,
config_string,
sync_map_root_directory,
job_os_hierarchy_type
):
"""
Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task`
"""
self.log(u"Converting config string to config dict")
parameters = gf.config_string_to_dict(config_string)
self.log(u"Creating task")
task = Task(config_string, logger=self.logger)
task.configuration["description"] = "Task %s" % task_info[0]
self.log([u"Task description: %s", task.configuration["description"]])
try:
task.configuration["language"] = parameters[gc.PPN_TASK_LANGUAGE]
self.log([u"Set language from task: '%s'", task.configuration["language"]])
except KeyError:
task.configuration["language"] = parameters[gc.PPN_JOB_LANGUAGE]
self.log([u"Set language from job: '%s'", task.configuration["language"]])
custom_id = task_info[0]
task.configuration["custom_id"] = custom_id
self.log([u"Task custom_id: %s", task.configuration["custom_id"]])
task.text_file_path = task_info[1]
self.log([u"Task text file path: %s", task.text_file_path])
task.audio_file_path = task_info[2]
self.log([u"Task audio file path: %s", task.audio_file_path])
task.sync_map_file_path = self._compute_sync_map_file_path(
sync_map_root_directory,
job_os_hierarchy_type,
custom_id,
task.configuration["o_name"]
)
self.log([u"Task sync map file path: %s", task.sync_map_file_path])
self.log(u"Replacing placeholder in os_file_smil_audio_ref")
task.configuration["o_smil_audio_ref"] = self._replace_placeholder(
task.configuration["o_smil_audio_ref"],
custom_id
)
self.log(u"Replacing placeholder in os_file_smil_page_ref")
task.configuration["o_smil_page_ref"] = self._replace_placeholder(
task.configuration["o_smil_page_ref"],
custom_id
)
self.log(u"Returning task")
return task | [
"def",
"_create_task",
"(",
"self",
",",
"task_info",
",",
"config_string",
",",
"sync_map_root_directory",
",",
"job_os_hierarchy_type",
")",
":",
"self",
".",
"log",
"(",
"u\"Converting config string to config dict\"",
")",
"parameters",
"=",
"gf",
".",
"config_stri... | Create a task object from
1. the ``task_info`` found analyzing the container entries, and
2. the given ``config_string``.
:param list task_info: the task information: ``[prefix, text_path, audio_path]``
:param string config_string: the configuration string
:param string sync_map_root_directory: the root directory for the sync map files
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:rtype: :class:`~aeneas.task.Task` | [
"Create",
"a",
"task",
"object",
"from"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L330-L388 | train | 226,963 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._compute_sync_map_file_path | def _compute_sync_map_file_path(
self,
root,
hierarchy_type,
custom_id,
file_name
):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string
"""
prefix = root
if hierarchy_type == HierarchyType.PAGED:
prefix = gf.norm_join(prefix, custom_id)
file_name_joined = gf.norm_join(prefix, file_name)
return self._replace_placeholder(file_name_joined, custom_id) | python | def _compute_sync_map_file_path(
self,
root,
hierarchy_type,
custom_id,
file_name
):
"""
Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string
"""
prefix = root
if hierarchy_type == HierarchyType.PAGED:
prefix = gf.norm_join(prefix, custom_id)
file_name_joined = gf.norm_join(prefix, file_name)
return self._replace_placeholder(file_name_joined, custom_id) | [
"def",
"_compute_sync_map_file_path",
"(",
"self",
",",
"root",
",",
"hierarchy_type",
",",
"custom_id",
",",
"file_name",
")",
":",
"prefix",
"=",
"root",
"if",
"hierarchy_type",
"==",
"HierarchyType",
".",
"PAGED",
":",
"prefix",
"=",
"gf",
".",
"norm_join",... | Compute the sync map file path inside the output container.
:param string root: the root of the sync map files inside the container
:param job_os_hierarchy_type: type of job output hierarchy
:type job_os_hierarchy_type: :class:`~aeneas.hierarchytype.HierarchyType`
:param string custom_id: the task custom id (flat) or
page directory name (paged)
:param string file_name: the output file name for the sync map
:rtype: string | [
"Compute",
"the",
"sync",
"map",
"file",
"path",
"inside",
"the",
"output",
"container",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L403-L425 | train | 226,964 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._find_files | def _find_files(self, entries, root, relative_path, file_name_regex):
"""
Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path)
"""
self.log([u"Finding files within root: '%s'", root])
target = root
if relative_path is not None:
self.log([u"Joining relative path: '%s'", relative_path])
target = gf.norm_join(root, relative_path)
self.log([u"Finding files within target: '%s'", target])
files = []
target_len = len(target)
for entry in entries:
if entry.startswith(target):
self.log([u"Examining entry: '%s'", entry])
entry_suffix = entry[target_len + 1:]
self.log([u"Examining entry suffix: '%s'", entry_suffix])
if re.search(file_name_regex, entry_suffix) is not None:
self.log([u"Match: '%s'", entry])
files.append(entry)
else:
self.log([u"No match: '%s'", entry])
return sorted(files) | python | def _find_files(self, entries, root, relative_path, file_name_regex):
"""
Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path)
"""
self.log([u"Finding files within root: '%s'", root])
target = root
if relative_path is not None:
self.log([u"Joining relative path: '%s'", relative_path])
target = gf.norm_join(root, relative_path)
self.log([u"Finding files within target: '%s'", target])
files = []
target_len = len(target)
for entry in entries:
if entry.startswith(target):
self.log([u"Examining entry: '%s'", entry])
entry_suffix = entry[target_len + 1:]
self.log([u"Examining entry suffix: '%s'", entry_suffix])
if re.search(file_name_regex, entry_suffix) is not None:
self.log([u"Match: '%s'", entry])
files.append(entry)
else:
self.log([u"No match: '%s'", entry])
return sorted(files) | [
"def",
"_find_files",
"(",
"self",
",",
"entries",
",",
"root",
",",
"relative_path",
",",
"file_name_regex",
")",
":",
"self",
".",
"log",
"(",
"[",
"u\"Finding files within root: '%s'\"",
",",
"root",
"]",
")",
"target",
"=",
"root",
"if",
"relative_path",
... | Return the elements in entries that
1. are in ``root/relative_path``, and
2. match ``file_name_regex``.
:param list entries: the list of entries (file paths) in the container
:param string root: the root directory of the container
:param string relative_path: the relative path in which we must search
:param regex file_name_regex: the regex matching the desired file names
:rtype: list of strings (path) | [
"Return",
"the",
"elements",
"in",
"entries",
"that"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L427-L458 | train | 226,965 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._match_files_flat_hierarchy | def _match_files_flat_hierarchy(self, text_files, audio_files):
"""
Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above)
"""
self.log(u"Matching files in flat hierarchy")
self.log([u"Text files: '%s'", text_files])
self.log([u"Audio files: '%s'", audio_files])
d_text = {}
d_audio = {}
for text_file in text_files:
text_file_no_ext = gf.file_name_without_extension(text_file)
d_text[text_file_no_ext] = text_file
self.log([u"Added text file '%s' to key '%s'", text_file, text_file_no_ext])
for audio_file in audio_files:
audio_file_no_ext = gf.file_name_without_extension(audio_file)
d_audio[audio_file_no_ext] = audio_file
self.log([u"Added audio file '%s' to key '%s'", audio_file, audio_file_no_ext])
tasks = []
for key in d_text.keys():
self.log([u"Examining text key '%s'", key])
if key in d_audio:
self.log([u"Key '%s' is also in audio", key])
tasks.append([key, d_text[key], d_audio[key]])
self.log([u"Added pair ('%s', '%s')", d_text[key], d_audio[key]])
return tasks | python | def _match_files_flat_hierarchy(self, text_files, audio_files):
"""
Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above)
"""
self.log(u"Matching files in flat hierarchy")
self.log([u"Text files: '%s'", text_files])
self.log([u"Audio files: '%s'", audio_files])
d_text = {}
d_audio = {}
for text_file in text_files:
text_file_no_ext = gf.file_name_without_extension(text_file)
d_text[text_file_no_ext] = text_file
self.log([u"Added text file '%s' to key '%s'", text_file, text_file_no_ext])
for audio_file in audio_files:
audio_file_no_ext = gf.file_name_without_extension(audio_file)
d_audio[audio_file_no_ext] = audio_file
self.log([u"Added audio file '%s' to key '%s'", audio_file, audio_file_no_ext])
tasks = []
for key in d_text.keys():
self.log([u"Examining text key '%s'", key])
if key in d_audio:
self.log([u"Key '%s' is also in audio", key])
tasks.append([key, d_text[key], d_audio[key]])
self.log([u"Added pair ('%s', '%s')", d_text[key], d_audio[key]])
return tasks | [
"def",
"_match_files_flat_hierarchy",
"(",
"self",
",",
"text_files",
",",
"audio_files",
")",
":",
"self",
".",
"log",
"(",
"u\"Matching files in flat hierarchy\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Text files: '%s'\"",
",",
"text_files",
"]",
")",
"self",
... | Match audio and text files in flat hierarchies.
Two files match if their names,
once removed the file extension,
are the same.
Examples: ::
foo/text/a.txt foo/audio/a.mp3 => match: ["a", "foo/text/a.txt", "foo/audio/a.mp3"]
foo/text/a.txt foo/audio/b.mp3 => no match
foo/res/c.txt foo/res/c.mp3 => match: ["c", "foo/res/c.txt", "foo/res/c.mp3"]
foo/res/d.txt foo/res/e.mp3 => no match
:param list text_files: the entries corresponding to text files
:param list audio_files: the entries corresponding to audio files
:rtype: list of lists (see above) | [
"Match",
"audio",
"and",
"text",
"files",
"in",
"flat",
"hierarchies",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L460-L499 | train | 226,966 |
readbeyond/aeneas | aeneas/analyzecontainer.py | AnalyzeContainer._match_directories | def _match_directories(self, entries, root, regex_string):
"""
Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories
"""
self.log(u"Matching directory names in paged hierarchy")
self.log([u"Matching within '%s'", root])
self.log([u"Matching regex '%s'", regex_string])
regex = re.compile(r"" + regex_string)
directories = set()
root_len = len(root)
for entry in entries:
# look only inside root dir
if entry.startswith(root):
self.log([u"Examining '%s'", entry])
# remove common prefix root/
entry = entry[root_len + 1:]
# split path
entry_splitted = entry.split(os.sep)
# match regex
if ((len(entry_splitted) >= 2) and
(re.match(regex, entry_splitted[0]) is not None)):
directories.add(entry_splitted[0])
self.log([u"Match: '%s'", entry_splitted[0]])
else:
self.log([u"No match: '%s'", entry])
return sorted(directories) | python | def _match_directories(self, entries, root, regex_string):
"""
Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories
"""
self.log(u"Matching directory names in paged hierarchy")
self.log([u"Matching within '%s'", root])
self.log([u"Matching regex '%s'", regex_string])
regex = re.compile(r"" + regex_string)
directories = set()
root_len = len(root)
for entry in entries:
# look only inside root dir
if entry.startswith(root):
self.log([u"Examining '%s'", entry])
# remove common prefix root/
entry = entry[root_len + 1:]
# split path
entry_splitted = entry.split(os.sep)
# match regex
if ((len(entry_splitted) >= 2) and
(re.match(regex, entry_splitted[0]) is not None)):
directories.add(entry_splitted[0])
self.log([u"Match: '%s'", entry_splitted[0]])
else:
self.log([u"No match: '%s'", entry])
return sorted(directories) | [
"def",
"_match_directories",
"(",
"self",
",",
"entries",
",",
"root",
",",
"regex_string",
")",
":",
"self",
".",
"log",
"(",
"u\"Matching directory names in paged hierarchy\"",
")",
"self",
".",
"log",
"(",
"[",
"u\"Matching within '%s'\"",
",",
"root",
"]",
"... | Match directory names in paged hierarchies.
Example: ::
root = /foo/bar
regex_string = [0-9]+
/foo/bar/
1/
bar
baz
2/
bar
3/
foo
=> ["/foo/bar/1", "/foo/bar/2", "/foo/bar/3"]
:param list entries: the list of entries (paths) of a container
:param string root: the root directory to search within
:param string regex_string: regex string to match directory names
:rtype: list of matched directories | [
"Match",
"directory",
"names",
"in",
"paged",
"hierarchies",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/analyzecontainer.py#L501-L547 | train | 226,967 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask.load_task | def load_task(self, task):
"""
Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task`
"""
if not isinstance(task, Task):
self.log_exc(u"task is not an instance of Task", None, True, ExecuteTaskInputError)
self.task = task | python | def load_task(self, task):
"""
Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task`
"""
if not isinstance(task, Task):
self.log_exc(u"task is not an instance of Task", None, True, ExecuteTaskInputError)
self.task = task | [
"def",
"load_task",
"(",
"self",
",",
"task",
")",
":",
"if",
"not",
"isinstance",
"(",
"task",
",",
"Task",
")",
":",
"self",
".",
"log_exc",
"(",
"u\"task is not an instance of Task\"",
",",
"None",
",",
"True",
",",
"ExecuteTaskInputError",
")",
"self",
... | Load the task from the given ``Task`` object.
:param task: the task to load
:type task: :class:`~aeneas.task.Task`
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if ``task`` is not an instance of :class:`~aeneas.task.Task` | [
"Load",
"the",
"task",
"from",
"the",
"given",
"Task",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L97-L107 | train | 226,968 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_begin | def _step_begin(self, label, log=True):
""" Log begin of a step """
if log:
self.step_label = label
self.step_begin_time = self.log(u"STEP %d BEGIN (%s)" % (self.step_index, label)) | python | def _step_begin(self, label, log=True):
""" Log begin of a step """
if log:
self.step_label = label
self.step_begin_time = self.log(u"STEP %d BEGIN (%s)" % (self.step_index, label)) | [
"def",
"_step_begin",
"(",
"self",
",",
"label",
",",
"log",
"=",
"True",
")",
":",
"if",
"log",
":",
"self",
".",
"step_label",
"=",
"label",
"self",
".",
"step_begin_time",
"=",
"self",
".",
"log",
"(",
"u\"STEP %d BEGIN (%s)\"",
"%",
"(",
"self",
".... | Log begin of a step | [
"Log",
"begin",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L109-L113 | train | 226,969 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_end | def _step_end(self, log=True):
""" Log end of a step """
if log:
step_end_time = self.log(u"STEP %d END (%s)" % (self.step_index, self.step_label))
diff = (step_end_time - self.step_begin_time)
diff = float(diff.seconds + diff.microseconds / 1000000.0)
self.step_total += diff
self.log(u"STEP %d DURATION %.3f (%s)" % (self.step_index, diff, self.step_label))
self.step_index += 1 | python | def _step_end(self, log=True):
""" Log end of a step """
if log:
step_end_time = self.log(u"STEP %d END (%s)" % (self.step_index, self.step_label))
diff = (step_end_time - self.step_begin_time)
diff = float(diff.seconds + diff.microseconds / 1000000.0)
self.step_total += diff
self.log(u"STEP %d DURATION %.3f (%s)" % (self.step_index, diff, self.step_label))
self.step_index += 1 | [
"def",
"_step_end",
"(",
"self",
",",
"log",
"=",
"True",
")",
":",
"if",
"log",
":",
"step_end_time",
"=",
"self",
".",
"log",
"(",
"u\"STEP %d END (%s)\"",
"%",
"(",
"self",
".",
"step_index",
",",
"self",
".",
"step_label",
")",
")",
"diff",
"=",
... | Log end of a step | [
"Log",
"end",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L115-L123 | train | 226,970 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._step_failure | def _step_failure(self, exc):
""" Log failure of a step """
self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
self.step_index += 1
self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError) | python | def _step_failure(self, exc):
""" Log failure of a step """
self.log_crit(u"STEP %d (%s) FAILURE" % (self.step_index, self.step_label))
self.step_index += 1
self.log_exc(u"Unexpected error while executing task", exc, True, ExecuteTaskExecutionError) | [
"def",
"_step_failure",
"(",
"self",
",",
"exc",
")",
":",
"self",
".",
"log_crit",
"(",
"u\"STEP %d (%s) FAILURE\"",
"%",
"(",
"self",
".",
"step_index",
",",
"self",
".",
"step_label",
")",
")",
"self",
".",
"step_index",
"+=",
"1",
"self",
".",
"log_e... | Log failure of a step | [
"Log",
"failure",
"of",
"a",
"step"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L125-L129 | train | 226,971 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask.execute | def execute(self):
"""
Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution
"""
self.log(u"Executing task...")
# check that we have the AudioFile object
if self.task.audio_file is None:
self.log_exc(u"The task does not seem to have its audio file set", None, True, ExecuteTaskInputError)
if (
(self.task.audio_file.audio_length is None) or
(self.task.audio_file.audio_length <= 0)
):
self.log_exc(u"The task seems to have an invalid audio file", None, True, ExecuteTaskInputError)
task_max_audio_length = self.rconf[RuntimeConfiguration.TASK_MAX_AUDIO_LENGTH]
if (
(task_max_audio_length > 0) and
(self.task.audio_file.audio_length > task_max_audio_length)
):
self.log_exc(u"The audio file of the task has length %.3f, more than the maximum allowed (%.3f)." % (self.task.audio_file.audio_length, task_max_audio_length), None, True, ExecuteTaskInputError)
# check that we have the TextFile object
if self.task.text_file is None:
self.log_exc(u"The task does not seem to have its text file set", None, True, ExecuteTaskInputError)
if len(self.task.text_file) == 0:
self.log_exc(u"The task text file seems to have no text fragments", None, True, ExecuteTaskInputError)
task_max_text_length = self.rconf[RuntimeConfiguration.TASK_MAX_TEXT_LENGTH]
if (
(task_max_text_length > 0) and
(len(self.task.text_file) > task_max_text_length)
):
self.log_exc(u"The text file of the task has %d fragments, more than the maximum allowed (%d)." % (len(self.task.text_file), task_max_text_length), None, True, ExecuteTaskInputError)
if self.task.text_file.chars == 0:
self.log_exc(u"The task text file seems to have empty text", None, True, ExecuteTaskInputError)
self.log(u"Both audio and text input file are present")
# execute
self.step_index = 1
self.step_total = 0.000
if self.task.text_file.file_format in TextFileFormat.MULTILEVEL_VALUES:
self._execute_multi_level_task()
else:
self._execute_single_level_task()
self.log(u"Executing task... done") | python | def execute(self):
"""
Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution
"""
self.log(u"Executing task...")
# check that we have the AudioFile object
if self.task.audio_file is None:
self.log_exc(u"The task does not seem to have its audio file set", None, True, ExecuteTaskInputError)
if (
(self.task.audio_file.audio_length is None) or
(self.task.audio_file.audio_length <= 0)
):
self.log_exc(u"The task seems to have an invalid audio file", None, True, ExecuteTaskInputError)
task_max_audio_length = self.rconf[RuntimeConfiguration.TASK_MAX_AUDIO_LENGTH]
if (
(task_max_audio_length > 0) and
(self.task.audio_file.audio_length > task_max_audio_length)
):
self.log_exc(u"The audio file of the task has length %.3f, more than the maximum allowed (%.3f)." % (self.task.audio_file.audio_length, task_max_audio_length), None, True, ExecuteTaskInputError)
# check that we have the TextFile object
if self.task.text_file is None:
self.log_exc(u"The task does not seem to have its text file set", None, True, ExecuteTaskInputError)
if len(self.task.text_file) == 0:
self.log_exc(u"The task text file seems to have no text fragments", None, True, ExecuteTaskInputError)
task_max_text_length = self.rconf[RuntimeConfiguration.TASK_MAX_TEXT_LENGTH]
if (
(task_max_text_length > 0) and
(len(self.task.text_file) > task_max_text_length)
):
self.log_exc(u"The text file of the task has %d fragments, more than the maximum allowed (%d)." % (len(self.task.text_file), task_max_text_length), None, True, ExecuteTaskInputError)
if self.task.text_file.chars == 0:
self.log_exc(u"The task text file seems to have empty text", None, True, ExecuteTaskInputError)
self.log(u"Both audio and text input file are present")
# execute
self.step_index = 1
self.step_total = 0.000
if self.task.text_file.file_format in TextFileFormat.MULTILEVEL_VALUES:
self._execute_multi_level_task()
else:
self._execute_single_level_task()
self.log(u"Executing task... done") | [
"def",
"execute",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing task...\"",
")",
"# check that we have the AudioFile object",
"if",
"self",
".",
"task",
".",
"audio_file",
"is",
"None",
":",
"self",
".",
"log_exc",
"(",
"u\"The task does not seem t... | Execute the task.
The sync map produced will be stored inside the task object.
:raises: :class:`~aeneas.executetask.ExecuteTaskInputError`: if there is a problem with the input parameters
:raises: :class:`~aeneas.executetask.ExecuteTaskExecutionError`: if there is a problem during the task execution | [
"Execute",
"the",
"task",
".",
"The",
"sync",
"map",
"produced",
"will",
"be",
"stored",
"inside",
"the",
"task",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L135-L183 | train | 226,972 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_single_level_task | def _execute_single_level_task(self):
""" Execute a single-level task """
self.log(u"Executing single level task...")
try:
# load audio file, extract MFCCs from real wave, clear audio file
self._step_begin(u"extract MFCC real wave")
real_wave_mfcc = self._extract_mfcc(
file_path=self.task.audio_file_path_absolute,
file_format=None,
)
self._step_end()
# compute head and/or tail and set it
self._step_begin(u"compute head tail")
(head_length, process_length, tail_length) = self._compute_head_process_tail(real_wave_mfcc)
real_wave_mfcc.set_head_middle_tail(head_length, process_length, tail_length)
self._step_end()
# compute alignment, outputting a tree of time intervals
self._set_synthesizer()
sync_root = Tree()
self._execute_inner(
real_wave_mfcc,
self.task.text_file,
sync_root=sync_root,
force_aba_auto=False,
log=True,
leaf_level=True
)
self._clear_cache_synthesizer()
# create syncmap and add it to task
self._step_begin(u"create sync map")
self._create_sync_map(sync_root=sync_root)
self._step_end()
# log total
self._step_total()
self.log(u"Executing single level task... done")
except Exception as exc:
self._step_failure(exc) | python | def _execute_single_level_task(self):
""" Execute a single-level task """
self.log(u"Executing single level task...")
try:
# load audio file, extract MFCCs from real wave, clear audio file
self._step_begin(u"extract MFCC real wave")
real_wave_mfcc = self._extract_mfcc(
file_path=self.task.audio_file_path_absolute,
file_format=None,
)
self._step_end()
# compute head and/or tail and set it
self._step_begin(u"compute head tail")
(head_length, process_length, tail_length) = self._compute_head_process_tail(real_wave_mfcc)
real_wave_mfcc.set_head_middle_tail(head_length, process_length, tail_length)
self._step_end()
# compute alignment, outputting a tree of time intervals
self._set_synthesizer()
sync_root = Tree()
self._execute_inner(
real_wave_mfcc,
self.task.text_file,
sync_root=sync_root,
force_aba_auto=False,
log=True,
leaf_level=True
)
self._clear_cache_synthesizer()
# create syncmap and add it to task
self._step_begin(u"create sync map")
self._create_sync_map(sync_root=sync_root)
self._step_end()
# log total
self._step_total()
self.log(u"Executing single level task... done")
except Exception as exc:
self._step_failure(exc) | [
"def",
"_execute_single_level_task",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Executing single level task...\"",
")",
"try",
":",
"# load audio file, extract MFCCs from real wave, clear audio file",
"self",
".",
"_step_begin",
"(",
"u\"extract MFCC real wave\"",
")... | Execute a single-level task | [
"Execute",
"a",
"single",
"-",
"level",
"task"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L185-L225 | train | 226,973 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_level | def _execute_level(self, level, audio_file_mfcc, text_files, sync_roots, force_aba_auto=False):
"""
Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list)
"""
self._set_synthesizer()
next_level_text_files = []
next_level_sync_roots = []
for text_file_index, text_file in enumerate(text_files):
self.log([u"Text level %d, fragment %d", level, text_file_index])
self.log([u" Len: %d", len(text_file)])
sync_root = sync_roots[text_file_index]
if (level > 1) and (len(text_file) == 1):
self.log(u"Level > 1 and only one text fragment => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
elif (level > 1) and (sync_root.value.begin == sync_root.value.end):
self.log(u"Level > 1 and parent has begin == end => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
else:
self.log(u"Level == 1 or more than one text fragment with non-zero parent => compute tree")
if not sync_root.is_empty:
begin = sync_root.value.begin
end = sync_root.value.end
self.log([u" Setting begin: %.3f", begin])
self.log([u" Setting end: %.3f", end])
audio_file_mfcc.set_head_middle_tail(head_length=begin, middle_length=(end - begin))
else:
self.log(u" No begin or end to set")
self._execute_inner(
audio_file_mfcc,
text_file,
sync_root=sync_root,
force_aba_auto=force_aba_auto,
log=False,
leaf_level=(level == 3)
)
# store next level roots
next_level_text_files.extend(text_file.children_not_empty)
# we added head and tail, we must not pass them to the next level
next_level_sync_roots.extend(sync_root.children[1:-1])
self._clear_cache_synthesizer()
return (next_level_text_files, next_level_sync_roots) | python | def _execute_level(self, level, audio_file_mfcc, text_files, sync_roots, force_aba_auto=False):
"""
Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list)
"""
self._set_synthesizer()
next_level_text_files = []
next_level_sync_roots = []
for text_file_index, text_file in enumerate(text_files):
self.log([u"Text level %d, fragment %d", level, text_file_index])
self.log([u" Len: %d", len(text_file)])
sync_root = sync_roots[text_file_index]
if (level > 1) and (len(text_file) == 1):
self.log(u"Level > 1 and only one text fragment => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
elif (level > 1) and (sync_root.value.begin == sync_root.value.end):
self.log(u"Level > 1 and parent has begin == end => return trivial tree")
self._append_trivial_tree(text_file, sync_root)
else:
self.log(u"Level == 1 or more than one text fragment with non-zero parent => compute tree")
if not sync_root.is_empty:
begin = sync_root.value.begin
end = sync_root.value.end
self.log([u" Setting begin: %.3f", begin])
self.log([u" Setting end: %.3f", end])
audio_file_mfcc.set_head_middle_tail(head_length=begin, middle_length=(end - begin))
else:
self.log(u" No begin or end to set")
self._execute_inner(
audio_file_mfcc,
text_file,
sync_root=sync_root,
force_aba_auto=force_aba_auto,
log=False,
leaf_level=(level == 3)
)
# store next level roots
next_level_text_files.extend(text_file.children_not_empty)
# we added head and tail, we must not pass them to the next level
next_level_sync_roots.extend(sync_root.children[1:-1])
self._clear_cache_synthesizer()
return (next_level_text_files, next_level_sync_roots) | [
"def",
"_execute_level",
"(",
"self",
",",
"level",
",",
"audio_file_mfcc",
",",
"text_files",
",",
"sync_roots",
",",
"force_aba_auto",
"=",
"False",
")",
":",
"self",
".",
"_set_synthesizer",
"(",
")",
"next_level_text_files",
"=",
"[",
"]",
"next_level_sync_r... | Compute the alignment for all the nodes in the given level.
Return a pair (next_level_text_files, next_level_sync_roots),
containing two lists of text file subtrees and sync map subtrees
on the next level.
:param int level: the level
:param audio_file_mfcc: the audio MFCC representation for this level
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param list text_files: a list of :class:`~aeneas.textfile.TextFile` objects,
each representing a (sub)tree of the Task text file
:param list sync_roots: a list of :class:`~aeneas.tree.Tree` objects,
each representing a SyncMapFragment tree,
one for each element in ``text_files``
:param bool force_aba_auto: if ``True``, force using the AUTO ABA algorithm
:rtype: (list, list) | [
"Compute",
"the",
"alignment",
"for",
"all",
"the",
"nodes",
"in",
"the",
"given",
"level",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L303-L358 | train | 226,974 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._execute_inner | def _execute_inner(self, audio_file_mfcc, text_file, sync_root=None, force_aba_auto=False, log=True, leaf_level=False):
"""
Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree`
"""
self._step_begin(u"synthesize text", log=log)
synt_handler, synt_path, synt_anchors, synt_format = self._synthesize(text_file)
self._step_end(log=log)
self._step_begin(u"extract MFCC synt wave", log=log)
synt_wave_mfcc = self._extract_mfcc(
file_path=synt_path,
file_format=synt_format,
)
gf.delete_file(synt_handler, synt_path)
self._step_end(log=log)
self._step_begin(u"align waves", log=log)
indices = self._align_waves(audio_file_mfcc, synt_wave_mfcc, synt_anchors)
self._step_end(log=log)
self._step_begin(u"adjust boundaries", log=log)
self._adjust_boundaries(indices, text_file, audio_file_mfcc, sync_root, force_aba_auto, leaf_level)
self._step_end(log=log) | python | def _execute_inner(self, audio_file_mfcc, text_file, sync_root=None, force_aba_auto=False, log=True, leaf_level=False):
"""
Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree`
"""
self._step_begin(u"synthesize text", log=log)
synt_handler, synt_path, synt_anchors, synt_format = self._synthesize(text_file)
self._step_end(log=log)
self._step_begin(u"extract MFCC synt wave", log=log)
synt_wave_mfcc = self._extract_mfcc(
file_path=synt_path,
file_format=synt_format,
)
gf.delete_file(synt_handler, synt_path)
self._step_end(log=log)
self._step_begin(u"align waves", log=log)
indices = self._align_waves(audio_file_mfcc, synt_wave_mfcc, synt_anchors)
self._step_end(log=log)
self._step_begin(u"adjust boundaries", log=log)
self._adjust_boundaries(indices, text_file, audio_file_mfcc, sync_root, force_aba_auto, leaf_level)
self._step_end(log=log) | [
"def",
"_execute_inner",
"(",
"self",
",",
"audio_file_mfcc",
",",
"text_file",
",",
"sync_root",
"=",
"None",
",",
"force_aba_auto",
"=",
"False",
",",
"log",
"=",
"True",
",",
"leaf_level",
"=",
"False",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"syn... | Align a subinterval of the given AudioFileMFCC
with the given TextFile.
Return the computed tree of time intervals,
rooted at ``sync_root`` if the latter is not ``None``,
or as a new ``Tree`` otherwise.
The begin and end positions inside the AudioFileMFCC
must have been set ahead by the caller.
The text fragments being aligned are the vchildren of ``text_file``.
:param audio_file_mfcc: the audio file MFCC representation
:type audio_file_mfcc: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
:param text_file: the text file subtree to align
:type text_file: :class:`~aeneas.textfile.TextFile`
:param sync_root: the tree node to which fragments should be appended
:type sync_root: :class:`~aeneas.tree.Tree`
:param bool force_aba_auto: if ``True``, do not run aba algorithm
:param bool log: if ``True``, log steps
:param bool leaf_level: alert aba if the computation is at a leaf level
:rtype: :class:`~aeneas.tree.Tree` | [
"Align",
"a",
"subinterval",
"of",
"the",
"given",
"AudioFileMFCC",
"with",
"the",
"given",
"TextFile",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L360-L403 | train | 226,975 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._load_audio_file | def _load_audio_file(self):
"""
Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"load audio file")
# NOTE file_format=None forces conversion to
# PCM16 mono WAVE with default sample rate
audio_file = AudioFile(
file_path=self.task.audio_file_path_absolute,
file_format=None,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self._step_end()
return audio_file | python | def _load_audio_file(self):
"""
Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"load audio file")
# NOTE file_format=None forces conversion to
# PCM16 mono WAVE with default sample rate
audio_file = AudioFile(
file_path=self.task.audio_file_path_absolute,
file_format=None,
rconf=self.rconf,
logger=self.logger
)
audio_file.read_samples_from_file()
self._step_end()
return audio_file | [
"def",
"_load_audio_file",
"(",
"self",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"load audio file\"",
")",
"# NOTE file_format=None forces conversion to",
"# PCM16 mono WAVE with default sample rate",
"audio_file",
"=",
"AudioFile",
"(",
"file_path",
"=",
"self",
... | Load audio in memory.
:rtype: :class:`~aeneas.audiofile.AudioFile` | [
"Load",
"audio",
"in",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L405-L422 | train | 226,976 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._clear_audio_file | def _clear_audio_file(self, audio_file):
"""
Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"clear audio file")
audio_file.clear_data()
audio_file = None
self._step_end() | python | def _clear_audio_file(self, audio_file):
"""
Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile`
"""
self._step_begin(u"clear audio file")
audio_file.clear_data()
audio_file = None
self._step_end() | [
"def",
"_clear_audio_file",
"(",
"self",
",",
"audio_file",
")",
":",
"self",
".",
"_step_begin",
"(",
"u\"clear audio file\"",
")",
"audio_file",
".",
"clear_data",
"(",
")",
"audio_file",
"=",
"None",
"self",
".",
"_step_end",
"(",
")"
] | Clear audio from memory.
:param audio_file: the object to clear
:type audio_file: :class:`~aeneas.audiofile.AudioFile` | [
"Clear",
"audio",
"from",
"memory",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L424-L434 | train | 226,977 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._extract_mfcc | def _extract_mfcc(self, file_path=None, file_format=None, audio_file=None):
"""
Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
"""
audio_file_mfcc = AudioFileMFCC(
file_path=file_path,
file_format=file_format,
audio_file=audio_file,
rconf=self.rconf,
logger=self.logger
)
if self.rconf.mmn:
self.log(u"Running VAD inside _extract_mfcc...")
audio_file_mfcc.run_vad(
log_energy_threshold=self.rconf[RuntimeConfiguration.MFCC_MASK_LOG_ENERGY_THRESHOLD],
min_nonspeech_length=self.rconf[RuntimeConfiguration.MFCC_MASK_MIN_NONSPEECH_LENGTH],
extend_before=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_BEFORE],
extend_after=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_AFTER]
)
self.log(u"Running VAD inside _extract_mfcc... done")
return audio_file_mfcc | python | def _extract_mfcc(self, file_path=None, file_format=None, audio_file=None):
"""
Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
"""
audio_file_mfcc = AudioFileMFCC(
file_path=file_path,
file_format=file_format,
audio_file=audio_file,
rconf=self.rconf,
logger=self.logger
)
if self.rconf.mmn:
self.log(u"Running VAD inside _extract_mfcc...")
audio_file_mfcc.run_vad(
log_energy_threshold=self.rconf[RuntimeConfiguration.MFCC_MASK_LOG_ENERGY_THRESHOLD],
min_nonspeech_length=self.rconf[RuntimeConfiguration.MFCC_MASK_MIN_NONSPEECH_LENGTH],
extend_before=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_BEFORE],
extend_after=self.rconf[RuntimeConfiguration.MFCC_MASK_EXTEND_SPEECH_INTERVAL_AFTER]
)
self.log(u"Running VAD inside _extract_mfcc... done")
return audio_file_mfcc | [
"def",
"_extract_mfcc",
"(",
"self",
",",
"file_path",
"=",
"None",
",",
"file_format",
"=",
"None",
",",
"audio_file",
"=",
"None",
")",
":",
"audio_file_mfcc",
"=",
"AudioFileMFCC",
"(",
"file_path",
"=",
"file_path",
",",
"file_format",
"=",
"file_format",
... | Extract the MFCCs from the given audio file.
:rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC` | [
"Extract",
"the",
"MFCCs",
"from",
"the",
"given",
"audio",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L436-L458 | train | 226,978 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._compute_head_process_tail | def _compute_head_process_tail(self, audio_file_mfcc):
"""
Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float)
"""
head_length = self.task.configuration["i_a_head"]
process_length = self.task.configuration["i_a_process"]
tail_length = self.task.configuration["i_a_tail"]
head_max = self.task.configuration["i_a_head_max"]
head_min = self.task.configuration["i_a_head_min"]
tail_max = self.task.configuration["i_a_tail_max"]
tail_min = self.task.configuration["i_a_tail_min"]
if (
(head_length is not None) or
(process_length is not None) or
(tail_length is not None)
):
self.log(u"Setting explicit head process tail")
else:
self.log(u"Detecting head tail...")
sd = SD(audio_file_mfcc, self.task.text_file, rconf=self.rconf, logger=self.logger)
head_length = TimeValue("0.000")
process_length = None
tail_length = TimeValue("0.000")
if (head_min is not None) or (head_max is not None):
self.log(u"Detecting HEAD...")
head_length = sd.detect_head(head_min, head_max)
self.log([u"Detected HEAD: %.3f", head_length])
self.log(u"Detecting HEAD... done")
if (tail_min is not None) or (tail_max is not None):
self.log(u"Detecting TAIL...")
tail_length = sd.detect_tail(tail_min, tail_max)
self.log([u"Detected TAIL: %.3f", tail_length])
self.log(u"Detecting TAIL... done")
self.log(u"Detecting head tail... done")
self.log([u"Head: %s", gf.safe_float(head_length, None)])
self.log([u"Process: %s", gf.safe_float(process_length, None)])
self.log([u"Tail: %s", gf.safe_float(tail_length, None)])
return (head_length, process_length, tail_length) | python | def _compute_head_process_tail(self, audio_file_mfcc):
"""
Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float)
"""
head_length = self.task.configuration["i_a_head"]
process_length = self.task.configuration["i_a_process"]
tail_length = self.task.configuration["i_a_tail"]
head_max = self.task.configuration["i_a_head_max"]
head_min = self.task.configuration["i_a_head_min"]
tail_max = self.task.configuration["i_a_tail_max"]
tail_min = self.task.configuration["i_a_tail_min"]
if (
(head_length is not None) or
(process_length is not None) or
(tail_length is not None)
):
self.log(u"Setting explicit head process tail")
else:
self.log(u"Detecting head tail...")
sd = SD(audio_file_mfcc, self.task.text_file, rconf=self.rconf, logger=self.logger)
head_length = TimeValue("0.000")
process_length = None
tail_length = TimeValue("0.000")
if (head_min is not None) or (head_max is not None):
self.log(u"Detecting HEAD...")
head_length = sd.detect_head(head_min, head_max)
self.log([u"Detected HEAD: %.3f", head_length])
self.log(u"Detecting HEAD... done")
if (tail_min is not None) or (tail_max is not None):
self.log(u"Detecting TAIL...")
tail_length = sd.detect_tail(tail_min, tail_max)
self.log([u"Detected TAIL: %.3f", tail_length])
self.log(u"Detecting TAIL... done")
self.log(u"Detecting head tail... done")
self.log([u"Head: %s", gf.safe_float(head_length, None)])
self.log([u"Process: %s", gf.safe_float(process_length, None)])
self.log([u"Tail: %s", gf.safe_float(tail_length, None)])
return (head_length, process_length, tail_length) | [
"def",
"_compute_head_process_tail",
"(",
"self",
",",
"audio_file_mfcc",
")",
":",
"head_length",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_head\"",
"]",
"process_length",
"=",
"self",
".",
"task",
".",
"configuration",
"[",
"\"i_a_process\"",
... | Set the audio file head or tail,
by either reading the explicit values
from the Task configuration,
or using SD to determine them.
This function returns the lengths, in seconds,
of the (head, process, tail).
:rtype: tuple (float, float, float) | [
"Set",
"the",
"audio",
"file",
"head",
"or",
"tail",
"by",
"either",
"reading",
"the",
"explicit",
"values",
"from",
"the",
"Task",
"configuration",
"or",
"using",
"SD",
"to",
"determine",
"them",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L460-L505 | train | 226,979 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._clear_cache_synthesizer | def _clear_cache_synthesizer(self):
""" Clear the cache of the synthesizer """
self.log(u"Clearing synthesizer...")
self.synthesizer.clear_cache()
self.log(u"Clearing synthesizer... done") | python | def _clear_cache_synthesizer(self):
""" Clear the cache of the synthesizer """
self.log(u"Clearing synthesizer...")
self.synthesizer.clear_cache()
self.log(u"Clearing synthesizer... done") | [
"def",
"_clear_cache_synthesizer",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Clearing synthesizer...\"",
")",
"self",
".",
"synthesizer",
".",
"clear_cache",
"(",
")",
"self",
".",
"log",
"(",
"u\"Clearing synthesizer... done\"",
")"
] | Clear the cache of the synthesizer | [
"Clear",
"the",
"cache",
"of",
"the",
"synthesizer"
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L513-L517 | train | 226,980 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._synthesize | def _synthesize(self, text_file):
"""
Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list)
"""
handler, path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
result = self.synthesizer.synthesize(text_file, path)
return (handler, path, result[0], self.synthesizer.output_audio_format) | python | def _synthesize(self, text_file):
"""
Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list)
"""
handler, path = gf.tmp_file(suffix=u".wav", root=self.rconf[RuntimeConfiguration.TMP_PATH])
result = self.synthesizer.synthesize(text_file, path)
return (handler, path, result[0], self.synthesizer.output_audio_format) | [
"def",
"_synthesize",
"(",
"self",
",",
"text_file",
")",
":",
"handler",
",",
"path",
"=",
"gf",
".",
"tmp_file",
"(",
"suffix",
"=",
"u\".wav\"",
",",
"root",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TMP_PATH",
"]",
")",
"result",
... | Synthesize text into a WAVE file.
Return a tuple consisting of:
1. the handler of the generated audio file
2. the path of the generated audio file
3. the list of anchors, that is, a list of floats
each representing the start time of the corresponding
text fragment in the generated wave file
``[start_1, start_2, ..., start_n]``
4. a tuple describing the format of the audio file
:param text_file: the text to be synthesized
:type text_file: :class:`~aeneas.textfile.TextFile`
:rtype: tuple (handler, string, list) | [
"Synthesize",
"text",
"into",
"a",
"WAVE",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L519-L539 | train | 226,981 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._align_waves | def _align_waves(self, real_wave_mfcc, synt_wave_mfcc, synt_anchors):
"""
Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices.
"""
self.log(u"Creating DTWAligner...")
aligner = DTWAligner(
real_wave_mfcc,
synt_wave_mfcc,
rconf=self.rconf,
logger=self.logger
)
self.log(u"Creating DTWAligner... done")
self.log(u"Computing boundary indices...")
boundary_indices = aligner.compute_boundaries(synt_anchors)
self.log(u"Computing boundary indices... done")
return boundary_indices | python | def _align_waves(self, real_wave_mfcc, synt_wave_mfcc, synt_anchors):
"""
Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices.
"""
self.log(u"Creating DTWAligner...")
aligner = DTWAligner(
real_wave_mfcc,
synt_wave_mfcc,
rconf=self.rconf,
logger=self.logger
)
self.log(u"Creating DTWAligner... done")
self.log(u"Computing boundary indices...")
boundary_indices = aligner.compute_boundaries(synt_anchors)
self.log(u"Computing boundary indices... done")
return boundary_indices | [
"def",
"_align_waves",
"(",
"self",
",",
"real_wave_mfcc",
",",
"synt_wave_mfcc",
",",
"synt_anchors",
")",
":",
"self",
".",
"log",
"(",
"u\"Creating DTWAligner...\"",
")",
"aligner",
"=",
"DTWAligner",
"(",
"real_wave_mfcc",
",",
"synt_wave_mfcc",
",",
"rconf",
... | Align two AudioFileMFCC objects,
representing WAVE files.
Return a list of boundary indices. | [
"Align",
"two",
"AudioFileMFCC",
"objects",
"representing",
"WAVE",
"files",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L541-L559 | train | 226,982 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._adjust_boundaries | def _adjust_boundaries(self, boundary_indices, text_file, real_wave_mfcc, sync_root, force_aba_auto=False, leaf_level=False):
"""
Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last).
"""
# boundary_indices contains the boundary indices in the all_mfcc of real_wave_mfcc
# starting with the (head-1st fragment) and ending with (-1th fragment-tail)
aba_parameters = self.task.configuration.aba_parameters()
if force_aba_auto:
self.log(u"Forced running algorithm: 'auto'")
aba_parameters["algorithm"] = (AdjustBoundaryAlgorithm.AUTO, [])
# note that the other aba settings (nonspeech and nozero)
# remain as specified by the user
self.log([u"ABA parameters: %s", aba_parameters])
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.adjust(
aba_parameters=aba_parameters,
real_wave_mfcc=real_wave_mfcc,
boundary_indices=boundary_indices,
text_file=text_file,
allow_arbitrary_shift=leaf_level
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | python | def _adjust_boundaries(self, boundary_indices, text_file, real_wave_mfcc, sync_root, force_aba_auto=False, leaf_level=False):
"""
Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last).
"""
# boundary_indices contains the boundary indices in the all_mfcc of real_wave_mfcc
# starting with the (head-1st fragment) and ending with (-1th fragment-tail)
aba_parameters = self.task.configuration.aba_parameters()
if force_aba_auto:
self.log(u"Forced running algorithm: 'auto'")
aba_parameters["algorithm"] = (AdjustBoundaryAlgorithm.AUTO, [])
# note that the other aba settings (nonspeech and nozero)
# remain as specified by the user
self.log([u"ABA parameters: %s", aba_parameters])
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.adjust(
aba_parameters=aba_parameters,
real_wave_mfcc=real_wave_mfcc,
boundary_indices=boundary_indices,
text_file=text_file,
allow_arbitrary_shift=leaf_level
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | [
"def",
"_adjust_boundaries",
"(",
"self",
",",
"boundary_indices",
",",
"text_file",
",",
"real_wave_mfcc",
",",
"sync_root",
",",
"force_aba_auto",
"=",
"False",
",",
"leaf_level",
"=",
"False",
")",
":",
"# boundary_indices contains the boundary indices in the all_mfcc ... | Adjust boundaries as requested by the user.
Return the computed time map, that is,
a list of pairs ``[start_time, end_time]``,
of length equal to number of fragments + 2,
where the two extra elements are for
the HEAD (first) and TAIL (last). | [
"Adjust",
"boundaries",
"as",
"requested",
"by",
"the",
"user",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L561-L588 | train | 226,983 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._append_trivial_tree | def _append_trivial_tree(self, text_file, sync_root):
"""
Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``).
"""
interval = sync_root.value
#
# NOTE the following is correct, but it is a bit obscure
# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2
#
if len(text_file) == 1:
time_values = [interval.begin, interval.begin, interval.end, interval.end]
else:
# interval.begin == interval.end
time_values = [interval.begin] * (3 + len(text_file))
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | python | def _append_trivial_tree(self, text_file, sync_root):
"""
Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``).
"""
interval = sync_root.value
#
# NOTE the following is correct, but it is a bit obscure
# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2
#
if len(text_file) == 1:
time_values = [interval.begin, interval.begin, interval.end, interval.end]
else:
# interval.begin == interval.end
time_values = [interval.begin] * (3 + len(text_file))
aba = AdjustBoundaryAlgorithm(rconf=self.rconf, logger=self.logger)
aba.intervals_to_fragment_list(
text_file=text_file,
time_values=time_values
)
aba.append_fragment_list_to_sync_root(sync_root=sync_root) | [
"def",
"_append_trivial_tree",
"(",
"self",
",",
"text_file",
",",
"sync_root",
")",
":",
"interval",
"=",
"sync_root",
".",
"value",
"#",
"# NOTE the following is correct, but it is a bit obscure",
"# time_values = [interval.begin] * (1 + len(text_file)) + [interval.end] * 2",
"... | Append trivial tree, made by one HEAD,
one sync map fragment for each element of ``text_file``,
and one TAIL.
This function is called if either ``text_file`` has only one element,
or if ``sync_root.value`` is an interval with zero length
(i.e., ``sync_root.value.begin == sync_root.value.end``). | [
"Append",
"trivial",
"tree",
"made",
"by",
"one",
"HEAD",
"one",
"sync",
"map",
"fragment",
"for",
"each",
"element",
"of",
"text_file",
"and",
"one",
"TAIL",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L590-L615 | train | 226,984 |
readbeyond/aeneas | aeneas/executetask.py | ExecuteTask._create_sync_map | def _create_sync_map(self, sync_root):
"""
If requested, check that the computed sync map is consistent.
Then, add it to the Task.
"""
sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
if self.rconf.safety_checks:
self.log(u"Running sanity check on computed sync map...")
if not sync_map.leaves_are_consistent:
self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
self.log(u"Running sanity check on computed sync map... passed")
else:
self.log(u"Not running sanity check on computed sync map")
self.task.sync_map = sync_map | python | def _create_sync_map(self, sync_root):
"""
If requested, check that the computed sync map is consistent.
Then, add it to the Task.
"""
sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
if self.rconf.safety_checks:
self.log(u"Running sanity check on computed sync map...")
if not sync_map.leaves_are_consistent:
self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
self.log(u"Running sanity check on computed sync map... passed")
else:
self.log(u"Not running sanity check on computed sync map")
self.task.sync_map = sync_map | [
"def",
"_create_sync_map",
"(",
"self",
",",
"sync_root",
")",
":",
"sync_map",
"=",
"SyncMap",
"(",
"tree",
"=",
"sync_root",
",",
"rconf",
"=",
"self",
".",
"rconf",
",",
"logger",
"=",
"self",
".",
"logger",
")",
"if",
"self",
".",
"rconf",
".",
"... | If requested, check that the computed sync map is consistent.
Then, add it to the Task. | [
"If",
"requested",
"check",
"that",
"the",
"computed",
"sync",
"map",
"is",
"consistent",
".",
"Then",
"add",
"it",
"to",
"the",
"Task",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/executetask.py#L617-L630 | train | 226,985 |
readbeyond/aeneas | aeneas/sd.py | SD.detect_interval | def detect_interval(
self,
min_head_length=None,
max_head_length=None,
min_tail_length=None,
max_tail_length=None
):
"""
Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
head = self.detect_head(min_head_length, max_head_length)
tail = self.detect_tail(min_tail_length, max_tail_length)
begin = head
end = self.real_wave_mfcc.audio_length - tail
self.log([u"Audio length: %.3f", self.real_wave_mfcc.audio_length])
self.log([u"Head length: %.3f", head])
self.log([u"Tail length: %.3f", tail])
self.log([u"Begin: %.3f", begin])
self.log([u"End: %.3f", end])
if (begin >= TimeValue("0.000")) and (end > begin):
self.log([u"Returning %.3f %.3f", begin, end])
return (begin, end)
self.log(u"Returning (0.000, 0.000)")
return (TimeValue("0.000"), TimeValue("0.000")) | python | def detect_interval(
self,
min_head_length=None,
max_head_length=None,
min_tail_length=None,
max_tail_length=None
):
"""
Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
head = self.detect_head(min_head_length, max_head_length)
tail = self.detect_tail(min_tail_length, max_tail_length)
begin = head
end = self.real_wave_mfcc.audio_length - tail
self.log([u"Audio length: %.3f", self.real_wave_mfcc.audio_length])
self.log([u"Head length: %.3f", head])
self.log([u"Tail length: %.3f", tail])
self.log([u"Begin: %.3f", begin])
self.log([u"End: %.3f", end])
if (begin >= TimeValue("0.000")) and (end > begin):
self.log([u"Returning %.3f %.3f", begin, end])
return (begin, end)
self.log(u"Returning (0.000, 0.000)")
return (TimeValue("0.000"), TimeValue("0.000")) | [
"def",
"detect_interval",
"(",
"self",
",",
"min_head_length",
"=",
"None",
",",
"max_head_length",
"=",
"None",
",",
"min_tail_length",
"=",
"None",
",",
"max_tail_length",
"=",
"None",
")",
":",
"head",
"=",
"self",
".",
"detect_head",
"(",
"min_head_length"... | Detect the interval of the audio file
containing the fragments in the text file.
Return the audio interval as a tuple of two
:class:`~aeneas.exacttiming.TimeValue` objects,
representing the begin and end time, in seconds,
with respect to the full wave duration.
If one of the parameters is ``None``, the default value
(``0.0`` for min, ``10.0`` for max) will be used.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: (:class:`~aeneas.exacttiming.TimeValue`, :class:`~aeneas.exacttiming.TimeValue`)
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"interval",
"of",
"the",
"audio",
"file",
"containing",
"the",
"fragments",
"in",
"the",
"text",
"file",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L126-L170 | train | 226,986 |
readbeyond/aeneas | aeneas/sd.py | SD.detect_head | def detect_head(self, min_head_length=None, max_head_length=None):
"""
Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_head_length, max_head_length, tail=False) | python | def detect_head(self, min_head_length=None, max_head_length=None):
"""
Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_head_length, max_head_length, tail=False) | [
"def",
"detect_head",
"(",
"self",
",",
"min_head_length",
"=",
"None",
",",
"max_head_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_detect",
"(",
"min_head_length",
",",
"max_head_length",
",",
"tail",
"=",
"False",
")"
] | Detect the audio head, returning its duration, in seconds.
:param min_head_length: estimated minimum head length
:type min_head_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_head_length: estimated maximum head length
:type max_head_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"audio",
"head",
"returning",
"its",
"duration",
"in",
"seconds",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L172-L184 | train | 226,987 |
readbeyond/aeneas | aeneas/sd.py | SD.detect_tail | def detect_tail(self, min_tail_length=None, max_tail_length=None):
"""
Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_tail_length, max_tail_length, tail=True) | python | def detect_tail(self, min_tail_length=None, max_tail_length=None):
"""
Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative
"""
return self._detect(min_tail_length, max_tail_length, tail=True) | [
"def",
"detect_tail",
"(",
"self",
",",
"min_tail_length",
"=",
"None",
",",
"max_tail_length",
"=",
"None",
")",
":",
"return",
"self",
".",
"_detect",
"(",
"min_tail_length",
",",
"max_tail_length",
",",
"tail",
"=",
"True",
")"
] | Detect the audio tail, returning its duration, in seconds.
:param min_tail_length: estimated minimum tail length
:type min_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:param max_tail_length: estimated maximum tail length
:type max_tail_length: :class:`~aeneas.exacttiming.TimeValue`
:rtype: :class:`~aeneas.exacttiming.TimeValue`
:raises: TypeError: if one of the parameters is not ``None`` or a number
:raises: ValueError: if one of the parameters is negative | [
"Detect",
"the",
"audio",
"tail",
"returning",
"its",
"duration",
"in",
"seconds",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/sd.py#L186-L198 | train | 226,988 |
readbeyond/aeneas | aeneas/synthesizer.py | Synthesizer._select_tts_engine | def _select_tts_engine(self):
"""
Select the TTS engine to be used by looking at the rconf object.
"""
self.log(u"Selecting TTS engine...")
requested_tts_engine = self.rconf[RuntimeConfiguration.TTS]
if requested_tts_engine == self.CUSTOM:
self.log(u"TTS engine: custom")
tts_path = self.rconf[RuntimeConfiguration.TTS_PATH]
if tts_path is None:
self.log_exc(u"You must specify a value for tts_path", None, True, ValueError)
if not gf.file_can_be_read(tts_path):
self.log_exc(u"Cannot read tts_path", None, True, OSError)
try:
import imp
self.log([u"Loading CustomTTSWrapper module from '%s'...", tts_path])
imp.load_source("CustomTTSWrapperModule", tts_path)
self.log([u"Loading CustomTTSWrapper module from '%s'... done", tts_path])
self.log(u"Importing CustomTTSWrapper...")
from CustomTTSWrapperModule import CustomTTSWrapper
self.log(u"Importing CustomTTSWrapper... done")
self.log(u"Creating CustomTTSWrapper instance...")
self.tts_engine = CustomTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Creating CustomTTSWrapper instance... done")
except Exception as exc:
self.log_exc(u"Unable to load custom TTS wrapper", exc, True, OSError)
elif requested_tts_engine == self.AWS:
try:
import boto3
except ImportError as exc:
self.log_exc(u"Unable to import boto3 for AWS Polly TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: AWS Polly TTS API")
self.tts_engine = AWSTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.NUANCE:
try:
import requests
except ImportError as exc:
self.log_exc(u"Unable to import requests for Nuance TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: Nuance TTS API")
self.tts_engine = NuanceTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.ESPEAKNG:
self.log(u"TTS engine: eSpeak-ng")
self.tts_engine = ESPEAKNGTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.FESTIVAL:
self.log(u"TTS engine: Festival")
self.tts_engine = FESTIVALTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.MACOS:
self.log(u"TTS engine: macOS")
self.tts_engine = MacOSTTSWrapper(rconf=self.rconf, logger=self.logger)
else:
self.log(u"TTS engine: eSpeak")
self.tts_engine = ESPEAKTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Selecting TTS engine... done") | python | def _select_tts_engine(self):
"""
Select the TTS engine to be used by looking at the rconf object.
"""
self.log(u"Selecting TTS engine...")
requested_tts_engine = self.rconf[RuntimeConfiguration.TTS]
if requested_tts_engine == self.CUSTOM:
self.log(u"TTS engine: custom")
tts_path = self.rconf[RuntimeConfiguration.TTS_PATH]
if tts_path is None:
self.log_exc(u"You must specify a value for tts_path", None, True, ValueError)
if not gf.file_can_be_read(tts_path):
self.log_exc(u"Cannot read tts_path", None, True, OSError)
try:
import imp
self.log([u"Loading CustomTTSWrapper module from '%s'...", tts_path])
imp.load_source("CustomTTSWrapperModule", tts_path)
self.log([u"Loading CustomTTSWrapper module from '%s'... done", tts_path])
self.log(u"Importing CustomTTSWrapper...")
from CustomTTSWrapperModule import CustomTTSWrapper
self.log(u"Importing CustomTTSWrapper... done")
self.log(u"Creating CustomTTSWrapper instance...")
self.tts_engine = CustomTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Creating CustomTTSWrapper instance... done")
except Exception as exc:
self.log_exc(u"Unable to load custom TTS wrapper", exc, True, OSError)
elif requested_tts_engine == self.AWS:
try:
import boto3
except ImportError as exc:
self.log_exc(u"Unable to import boto3 for AWS Polly TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: AWS Polly TTS API")
self.tts_engine = AWSTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.NUANCE:
try:
import requests
except ImportError as exc:
self.log_exc(u"Unable to import requests for Nuance TTS API wrapper", exc, True, ImportError)
self.log(u"TTS engine: Nuance TTS API")
self.tts_engine = NuanceTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.ESPEAKNG:
self.log(u"TTS engine: eSpeak-ng")
self.tts_engine = ESPEAKNGTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.FESTIVAL:
self.log(u"TTS engine: Festival")
self.tts_engine = FESTIVALTTSWrapper(rconf=self.rconf, logger=self.logger)
elif requested_tts_engine == self.MACOS:
self.log(u"TTS engine: macOS")
self.tts_engine = MacOSTTSWrapper(rconf=self.rconf, logger=self.logger)
else:
self.log(u"TTS engine: eSpeak")
self.tts_engine = ESPEAKTTSWrapper(rconf=self.rconf, logger=self.logger)
self.log(u"Selecting TTS engine... done") | [
"def",
"_select_tts_engine",
"(",
"self",
")",
":",
"self",
".",
"log",
"(",
"u\"Selecting TTS engine...\"",
")",
"requested_tts_engine",
"=",
"self",
".",
"rconf",
"[",
"RuntimeConfiguration",
".",
"TTS",
"]",
"if",
"requested_tts_engine",
"==",
"self",
".",
"C... | Select the TTS engine to be used by looking at the rconf object. | [
"Select",
"the",
"TTS",
"engine",
"to",
"be",
"used",
"by",
"looking",
"at",
"the",
"rconf",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/synthesizer.py#L98-L150 | train | 226,989 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_shell_encoding | def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
is_in_utf8 = True
is_out_utf8 = True
if sys.stdin.encoding not in ["UTF-8", "UTF8"]:
is_in_utf8 = False
if sys.stdout.encoding not in ["UTF-8", "UTF8"]:
is_out_utf8 = False
if (is_in_utf8) and (is_out_utf8):
gf.print_success(u"shell encoding OK")
else:
gf.print_warning(u"shell encoding WARNING")
if not is_in_utf8:
gf.print_warning(u" The default input encoding of your shell is not UTF-8")
if not is_out_utf8:
gf.print_warning(u" The default output encoding of your shell is not UTF-8")
gf.print_info(u" If you plan to use aeneas on the command line,")
if gf.is_posix():
gf.print_info(u" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell")
else:
gf.print_info(u" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell")
return True
return False | python | def check_shell_encoding(cls):
"""
Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
is_in_utf8 = True
is_out_utf8 = True
if sys.stdin.encoding not in ["UTF-8", "UTF8"]:
is_in_utf8 = False
if sys.stdout.encoding not in ["UTF-8", "UTF8"]:
is_out_utf8 = False
if (is_in_utf8) and (is_out_utf8):
gf.print_success(u"shell encoding OK")
else:
gf.print_warning(u"shell encoding WARNING")
if not is_in_utf8:
gf.print_warning(u" The default input encoding of your shell is not UTF-8")
if not is_out_utf8:
gf.print_warning(u" The default output encoding of your shell is not UTF-8")
gf.print_info(u" If you plan to use aeneas on the command line,")
if gf.is_posix():
gf.print_info(u" you might want to 'export PYTHONIOENCODING=UTF-8' in your shell")
else:
gf.print_info(u" you might want to 'set PYTHONIOENCODING=UTF-8' in your shell")
return True
return False | [
"def",
"check_shell_encoding",
"(",
"cls",
")",
":",
"is_in_utf8",
"=",
"True",
"is_out_utf8",
"=",
"True",
"if",
"sys",
".",
"stdin",
".",
"encoding",
"not",
"in",
"[",
"\"UTF-8\"",
",",
"\"UTF8\"",
"]",
":",
"is_in_utf8",
"=",
"False",
"if",
"sys",
"."... | Check whether ``sys.stdin`` and ``sys.stdout`` are UTF-8 encoded.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"sys",
".",
"stdin",
"and",
"sys",
".",
"stdout",
"are",
"UTF",
"-",
"8",
"encoded",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L49-L77 | train | 226,990 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_ffprobe | def check_ffprobe(cls):
"""
Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffprobewrapper import FFPROBEWrapper
file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
prober = FFPROBEWrapper()
properties = prober.read_properties(file_path)
gf.print_success(u"ffprobe OK")
return False
except:
pass
gf.print_error(u"ffprobe ERROR")
gf.print_info(u" Please make sure you have ffprobe installed correctly")
gf.print_info(u" (usually it is provided by the ffmpeg installer)")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | python | def check_ffprobe(cls):
"""
Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffprobewrapper import FFPROBEWrapper
file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
prober = FFPROBEWrapper()
properties = prober.read_properties(file_path)
gf.print_success(u"ffprobe OK")
return False
except:
pass
gf.print_error(u"ffprobe ERROR")
gf.print_info(u" Please make sure you have ffprobe installed correctly")
gf.print_info(u" (usually it is provided by the ffmpeg installer)")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | [
"def",
"check_ffprobe",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"ffprobewrapper",
"import",
"FFPROBEWrapper",
"file_path",
"=",
"gf",
".",
"absolute_path",
"(",
"u\"tools/res/audio.mp3\"",
",",
"__file__",
")",
"prober",
"=",
"FFPROBEWrapper",
"... | Check whether ``ffprobe`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"ffprobe",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L80-L101 | train | 226,991 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_ffmpeg | def check_ffmpeg(cls):
"""
Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffmpegwrapper import FFMPEGWrapper
input_file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
handler, output_file_path = gf.tmp_file(suffix=u".wav")
converter = FFMPEGWrapper()
result = converter.convert(input_file_path, output_file_path)
gf.delete_file(handler, output_file_path)
if result:
gf.print_success(u"ffmpeg OK")
return False
except:
pass
gf.print_error(u"ffmpeg ERROR")
gf.print_info(u" Please make sure you have ffmpeg installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | python | def check_ffmpeg(cls):
"""
Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.ffmpegwrapper import FFMPEGWrapper
input_file_path = gf.absolute_path(u"tools/res/audio.mp3", __file__)
handler, output_file_path = gf.tmp_file(suffix=u".wav")
converter = FFMPEGWrapper()
result = converter.convert(input_file_path, output_file_path)
gf.delete_file(handler, output_file_path)
if result:
gf.print_success(u"ffmpeg OK")
return False
except:
pass
gf.print_error(u"ffmpeg ERROR")
gf.print_info(u" Please make sure you have ffmpeg installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
return True | [
"def",
"check_ffmpeg",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"ffmpegwrapper",
"import",
"FFMPEGWrapper",
"input_file_path",
"=",
"gf",
".",
"absolute_path",
"(",
"u\"tools/res/audio.mp3\"",
",",
"__file__",
")",
"handler",
",",
"output_file_path... | Check whether ``ffmpeg`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"ffmpeg",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L104-L127 | train | 226,992 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_espeak | def check_espeak(cls):
"""
Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.textfile import TextFile
from aeneas.textfile import TextFragment
from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper
text = u"From fairest creatures we desire increase,"
text_file = TextFile()
text_file.add_fragment(TextFragment(language=u"eng", lines=[text], filtered_lines=[text]))
handler, output_file_path = gf.tmp_file(suffix=u".wav")
ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path)
gf.delete_file(handler, output_file_path)
gf.print_success(u"espeak OK")
return False
except:
pass
gf.print_error(u"espeak ERROR")
gf.print_info(u" Please make sure you have espeak installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
gf.print_info(u" You might also want to check that the espeak-data directory")
gf.print_info(u" is set up correctly, for example, it has the correct permissions")
return True | python | def check_espeak(cls):
"""
Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
try:
from aeneas.textfile import TextFile
from aeneas.textfile import TextFragment
from aeneas.ttswrappers.espeakttswrapper import ESPEAKTTSWrapper
text = u"From fairest creatures we desire increase,"
text_file = TextFile()
text_file.add_fragment(TextFragment(language=u"eng", lines=[text], filtered_lines=[text]))
handler, output_file_path = gf.tmp_file(suffix=u".wav")
ESPEAKTTSWrapper().synthesize_multiple(text_file, output_file_path)
gf.delete_file(handler, output_file_path)
gf.print_success(u"espeak OK")
return False
except:
pass
gf.print_error(u"espeak ERROR")
gf.print_info(u" Please make sure you have espeak installed correctly")
gf.print_info(u" and that its path is in your PATH environment variable")
gf.print_info(u" You might also want to check that the espeak-data directory")
gf.print_info(u" is set up correctly, for example, it has the correct permissions")
return True | [
"def",
"check_espeak",
"(",
"cls",
")",
":",
"try",
":",
"from",
"aeneas",
".",
"textfile",
"import",
"TextFile",
"from",
"aeneas",
".",
"textfile",
"import",
"TextFragment",
"from",
"aeneas",
".",
"ttswrappers",
".",
"espeakttswrapper",
"import",
"ESPEAKTTSWrap... | Check whether ``espeak`` can be called.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"espeak",
"can",
"be",
"called",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L130-L157 | train | 226,993 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cdtw | def check_cdtw(cls):
"""
Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cdtw"):
gf.print_success(u"aeneas.cdtw AVAILABLE")
return False
gf.print_warning(u"aeneas.cdtw NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cdtw(cls):
"""
Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cdtw"):
gf.print_success(u"aeneas.cdtw AVAILABLE")
return False
gf.print_warning(u"aeneas.cdtw NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cdtw",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cdtw\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cdtw AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cdtw NOT AVAILABL... | Check whether Python C extension ``cdtw`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cdtw",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L195-L209 | train | 226,994 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cmfcc | def check_cmfcc(cls):
"""
Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cmfcc"):
gf.print_success(u"aeneas.cmfcc AVAILABLE")
return False
gf.print_warning(u"aeneas.cmfcc NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cmfcc(cls):
"""
Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cmfcc"):
gf.print_success(u"aeneas.cmfcc AVAILABLE")
return False
gf.print_warning(u"aeneas.cmfcc NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be significantly slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cmfcc",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cmfcc\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cmfcc AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cmfcc NOT AVAILA... | Check whether Python C extension ``cmfcc`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cmfcc",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L212-L226 | train | 226,995 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_cew | def check_cew(cls):
"""
Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cew"):
gf.print_success(u"aeneas.cew AVAILABLE")
return False
gf.print_warning(u"aeneas.cew NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be a bit slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | python | def check_cew(cls):
"""
Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool
"""
if gf.can_run_c_extension("cew"):
gf.print_success(u"aeneas.cew AVAILABLE")
return False
gf.print_warning(u"aeneas.cew NOT AVAILABLE")
gf.print_info(u" You can still run aeneas but it will be a bit slower")
gf.print_info(u" Please refer to the installation documentation for details")
return True | [
"def",
"check_cew",
"(",
"cls",
")",
":",
"if",
"gf",
".",
"can_run_c_extension",
"(",
"\"cew\"",
")",
":",
"gf",
".",
"print_success",
"(",
"u\"aeneas.cew AVAILABLE\"",
")",
"return",
"False",
"gf",
".",
"print_warning",
"(",
"u\"aeneas.cew NOT AVAILABLE\... | Check whether Python C extension ``cew`` can be imported.
Return ``True`` on failure and ``False`` on success.
:rtype: bool | [
"Check",
"whether",
"Python",
"C",
"extension",
"cew",
"can",
"be",
"imported",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L229-L243 | train | 226,996 |
readbeyond/aeneas | aeneas/diagnostics.py | Diagnostics.check_all | def check_all(cls, tools=True, encoding=True, c_ext=True):
"""
Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool)
"""
# errors are fatal
if cls.check_ffprobe():
return (True, False, False)
if cls.check_ffmpeg():
return (True, False, False)
if cls.check_espeak():
return (True, False, False)
if (tools) and (cls.check_tools()):
return (True, False, False)
# warnings are non-fatal
warnings = False
c_ext_warnings = False
if encoding:
warnings = cls.check_shell_encoding()
if c_ext:
# we do not want lazy evaluation
c_ext_warnings = cls.check_cdtw() or c_ext_warnings
c_ext_warnings = cls.check_cmfcc() or c_ext_warnings
c_ext_warnings = cls.check_cew() or c_ext_warnings
# return results
return (False, warnings, c_ext_warnings) | python | def check_all(cls, tools=True, encoding=True, c_ext=True):
"""
Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool)
"""
# errors are fatal
if cls.check_ffprobe():
return (True, False, False)
if cls.check_ffmpeg():
return (True, False, False)
if cls.check_espeak():
return (True, False, False)
if (tools) and (cls.check_tools()):
return (True, False, False)
# warnings are non-fatal
warnings = False
c_ext_warnings = False
if encoding:
warnings = cls.check_shell_encoding()
if c_ext:
# we do not want lazy evaluation
c_ext_warnings = cls.check_cdtw() or c_ext_warnings
c_ext_warnings = cls.check_cmfcc() or c_ext_warnings
c_ext_warnings = cls.check_cew() or c_ext_warnings
# return results
return (False, warnings, c_ext_warnings) | [
"def",
"check_all",
"(",
"cls",
",",
"tools",
"=",
"True",
",",
"encoding",
"=",
"True",
",",
"c_ext",
"=",
"True",
")",
":",
"# errors are fatal",
"if",
"cls",
".",
"check_ffprobe",
"(",
")",
":",
"return",
"(",
"True",
",",
"False",
",",
"False",
"... | Perform all checks.
Return a tuple of booleans ``(errors, warnings, c_ext_warnings)``.
:param bool tools: if ``True``, check aeneas tools
:param bool encoding: if ``True``, check shell encoding
:param bool c_ext: if ``True``, check Python C extensions
:rtype: (bool, bool, bool) | [
"Perform",
"all",
"checks",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/diagnostics.py#L246-L277 | train | 226,997 |
readbeyond/aeneas | aeneas/configuration.py | Configuration.config_string | def config_string(self):
"""
Build the storable string corresponding
to this configuration object.
:rtype: string
"""
return (gc.CONFIG_STRING_SEPARATOR_SYMBOL).join(
[u"%s%s%s" % (fn, gc.CONFIG_STRING_ASSIGNMENT_SYMBOL, self.data[fn]) for fn in sorted(self.data.keys()) if self.data[fn] is not None]
) | python | def config_string(self):
"""
Build the storable string corresponding
to this configuration object.
:rtype: string
"""
return (gc.CONFIG_STRING_SEPARATOR_SYMBOL).join(
[u"%s%s%s" % (fn, gc.CONFIG_STRING_ASSIGNMENT_SYMBOL, self.data[fn]) for fn in sorted(self.data.keys()) if self.data[fn] is not None]
) | [
"def",
"config_string",
"(",
"self",
")",
":",
"return",
"(",
"gc",
".",
"CONFIG_STRING_SEPARATOR_SYMBOL",
")",
".",
"join",
"(",
"[",
"u\"%s%s%s\"",
"%",
"(",
"fn",
",",
"gc",
".",
"CONFIG_STRING_ASSIGNMENT_SYMBOL",
",",
"self",
".",
"data",
"[",
"fn",
"]... | Build the storable string corresponding
to this configuration object.
:rtype: string | [
"Build",
"the",
"storable",
"string",
"corresponding",
"to",
"this",
"configuration",
"object",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/configuration.py#L169-L178 | train | 226,998 |
readbeyond/aeneas | aeneas/exacttiming.py | TimeValue.geq_multiple | def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return self
return int(math.ceil(other / self)) * self | python | def geq_multiple(self, other):
"""
Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue`
"""
if other == TimeValue("0.000"):
return self
return int(math.ceil(other / self)) * self | [
"def",
"geq_multiple",
"(",
"self",
",",
"other",
")",
":",
"if",
"other",
"==",
"TimeValue",
"(",
"\"0.000\"",
")",
":",
"return",
"self",
"return",
"int",
"(",
"math",
".",
"ceil",
"(",
"other",
"/",
"self",
")",
")",
"*",
"self"
] | Return the next multiple of this time value,
greater than or equal to ``other``.
If ``other`` is zero, return this time value.
:rtype: :class:`~aeneas.exacttiming.TimeValue` | [
"Return",
"the",
"next",
"multiple",
"of",
"this",
"time",
"value",
"greater",
"than",
"or",
"equal",
"to",
"other",
".",
"If",
"other",
"is",
"zero",
"return",
"this",
"time",
"value",
"."
] | 9d95535ad63eef4a98530cfdff033b8c35315ee1 | https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/exacttiming.py#L67-L77 | train | 226,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.