INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add child sprite. Child will be nested within parent
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()
Remove one or several :class:`Sprite` sprites from scene
def remove_child(self, *sprites): """Remove one or several :class:`Sprite` sprites from scene """ # first drop focus scene = self.get_scene() if scene: child_sprites = list(self.all_child_sprites()) if scene._focus_sprite in child_sprites: scene....
returns all child and grandchild sprites in a flat list
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
connect to a child event so that will disconnect if the child is removed from this sprite. this is the recommended way to connect to child events. syntax is same as for the .connect itself, just you prepend the child sprite as the first element
def connect_child(self, sprite, event, *args, **kwargs): """connect to a child event so that will disconnect if the child is removed from this sprite. this is the recommended way to connect to child events. syntax is same as for the .connect itself, just you prepend the child sprite as t...
connect to a child event so that will disconnect if the child is removed from this sprite. this is the recommended way to connect to child events. syntax is same as for the .connect itself, just you prepend the child sprite as the first element
def connect_child_after(self, sprite, event, *args, **kwargs): """connect to a child event so that will disconnect if the child is removed from this sprite. this is the recommended way to connect to child events. syntax is same as for the .connect itself, just you prepend the child sprit...
disconnects from child event. if handler is not specified, will disconnect from all the child sprite events
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_con...
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.
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_...
adjusts sprite's z-order so that the sprite is on top of it's siblings
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
adjusts sprite's z-order so that the sprite is behind it's siblings
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
grab window's focus. Keyboard and scroll events will be forwarded to the sprite who has the focus. Check the 'focused' property of sprite in the on-render event to decide how to render it (say, add an outline when focused=true)
def grab_focus(self): """grab window's focus. Keyboard and scroll events will be forwarded to the sprite who has the focus. Check the 'focused' property of sprite in the on-render event to decide how to render it (say, add an outline when focused=true)""" scene = self.get_scene()...
removes focus from the current element if it has it
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
returns all the parent sprites up until scene
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
measure the extents of the sprite's graphics.
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()) ...
check if the given coordinates are inside the sprite's fill or stroke path
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: ...
returns class:`Scene` the sprite belongs to
def get_scene(self): """returns class:`Scene` the sprite belongs to""" if self._scene is None: parent = getattr(self, "parent", None) if parent: self._scene = parent.get_scene() return self._scene
Request parent Scene to Interpolate attributes using the internal tweener. Specify sprite's attributes that need changing. `duration` defaults to 0.4 seconds and `easing` to cubic in-out (for others see pytweener.Easing class). Example:: # tween some_sprite to c...
def animate(self, duration = None, easing = None, on_complete = None, on_update = None, round = False, **kwargs): """Request parent Scene to Interpolate attributes using the internal tweener. Specify sprite's attributes that need changing. `duration` defaults to 0.4 seconds...
return sprite's current transformation 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()
Converts x, y given in the scene coordinates to sprite's local ones coordinates
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)
measures given text with label's font and size. returns width, height and ascent. Ascent's null in case if the label does not have font face specified (and is thusly using pango)
def measure(self, text, escape = True, max_width = None): """measures given text with label's font and size. returns width, height and ascent. Ascent's null in case if the label does not have font face specified (and is thusly using pango)""" if escape: text = text.replace (...
Interpolate attributes of the given object using the internal tweener and redrawing scene after every tweener update. Specify the sprite and sprite's attributes that need changing. `duration` defaults to 0.4 seconds and `easing` to cubic in-out (for others see pytweener.Easin...
def animate(self, sprite, duration = None, easing = None, on_complete = None, on_update = None, round = False, **kwargs): """Interpolate attributes of the given object using the internal tweener and redrawing scene after every tweener update. Specify the sprite and sprite's...
stop animation without firing on_complete
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)
Queue redraw. The redraw will be performed not more often than the `framerate` allows
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.datetim...
loop until there is nothing more to tween
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
Returns flat list of the sprite tree for simplified iteration
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...
Returns the topmost visible interactive sprite for given coordinates
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
start dragging given sprite
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 ...
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 ...
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_datet...
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, th...
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...
Output the log to file. :param string path: the path of the log file to be written
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())
Sanitize the given message, dealing with multiple arguments and/or string formatting. :param message: the log message to be sanitized :type message: string or list of strings :rtype: string
def _sanitize(cls, message): """ Sanitize the given message, dealing with multiple arguments and/or string formatting. :param message: the log message to be sanitized :type message: string or list of strings :rtype: string """ if isinstance(messa...
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
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"[%...
Log generic message :param string message: the message to log :param string severity: the message severity :rtype: datetime
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)
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` ...
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.CRI...
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`
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` """ ...
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`
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` ""...
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`
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` ""...
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_pat...
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 m...
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)
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: mul...
Get a suitable time string ("ss", "mm:ss", "hh:mm:ss"), according to the maximum time. :param int value: the time value :rtype: string
def _time_string(self, value): """ Get a suitable time string ("ss", "mm:ss", "hh:mm:ss"), according to the maximum time. :param int value: the time value :rtype: string """ if self.max_time < 60: return "%02d" % (value) elif self.max_...
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`
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 i...
Draw this set of labels 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`
def draw_png(self, image, h_zoom, v_zoom, current_y): """ Draw this set of labels 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...
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`
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 ima...
Perform command and return the appropriate exit code. :rtype: int
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 4: return self.print_help() text_format = gf.safe_unicode(self.actual_arguments[0]) if text_format == u"list": ...
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
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 o...
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
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 ...
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...
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 ...
Create the ``self.audio_file`` object by reading the audio file at ``self.audio_file_path_absolute``.
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...
Create the ``self.text_file`` object by reading the text file at ``self.text_file_path_absolute``.
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.configura...
Return a dictionary representing the :class:`~aeneas.adjustboundaryalgorithm.AdjustBoundaryAlgorithm` parameters stored in this task configuration. Available keys: * ``algorithm``, tuple: (string, list) * ``nonspeech``, tuple: (TimeValue or None, string) * ``nozero``, b...
def aba_parameters(self): """ Return a dictionary representing the :class:`~aeneas.adjustboundaryalgorithm.AdjustBoundaryAlgorithm` parameters stored in this task configuration. Available keys: * ``algorithm``, tuple: (string, list) * ``nonspeech``, tuple: (Time...
Read the properties of an audio file and return them as a dictionary. Example: :: d["index"]=0 d["codec_name"]=mp3 d["codec_long_name"]=MP3 (MPEG audio layer 3) d["profile"]=unknown d["codec_type"]=audio d["codec_time_base"]=1/441...
def read_properties(self, audio_file_path): """ Read the properties of an audio file and return them as a dictionary. Example: :: d["index"]=0 d["codec_name"]=mp3 d["codec_long_name"]=MP3 (MPEG audio layer 3) d["profile"]=unknown ...
Given an ``lxml`` node, get lines from ``node.text``, where the line separator is ``<br xmlns=... />``.
def _get_lines_from_node_text(cls, node): """ Given an ``lxml`` node, get lines from ``node.text``, where the line separator is ``<br xmlns=... />``. """ # TODO more robust parsing from lxml import etree parts = ([node.text] + list(chain(*([etree.tostring(c, with_...
Return an ``lxml`` tree as a Unicode 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", ...
Print a message and log it. :param msg: the message :type msg: Unicode string :param prefix: the (optional) prefix :type prefix: Unicode string
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)...
Print help message and exit. :param short: print short help only :type short: bool
def print_help(self, short=False): """ Print help message and exit. :param short: print short help only :type short: bool """ header = [ u"", u"NAME", u" %s - %s" % (self.NAME, self.HELP["description"]), u"", ] ...
Print program name and version and exit. :rtype: int
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)
Print the list of runtime configuration parameters and exit.
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") re...
Program entry point. Please note that the first item in ``arguments`` is discarded, as it is assumed to be the script/invocation name; pass a "dumb" placeholder if you call this method with an argument different that ``sys.argv``. :param arguments: the list of arguments ...
def run(self, arguments, show_help=True): """ Program entry point. Please note that the first item in ``arguments`` is discarded, as it is assumed to be the script/invocation name; pass a "dumb" placeholder if you call this method with an argument different that ``sys.ar...
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
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...
Check if the actual arguments include an option starting with the given ``prefix`` and having a value, e.g. ``--format=ogg`` for ``prefix="--format"``. :param prefix: the option prefix :type prefix: Unicode string :param actual_arguments: if ``True``, check among actual argumen...
def has_option_with_value(self, prefix, actual_arguments=True): """ Check if the actual arguments include an option starting with the given ``prefix`` and having a value, e.g. ``--format=ogg`` for ``prefix="--format"``. :param prefix: the option prefix :type prefix: Uni...
Perform command and return the appropriate exit code. :rtype: int
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ self.log(u"This function should be overloaded in derived classes") self.log([u"Invoked with %s", self.actual_arguments]) return self.NO_ERROR_EXIT_CODE
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
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 ...
If the given path does not exist, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the input file or directory :type path: string (path) :rtype: bool
def check_input_file_or_directory(self, path): """ If the given path does not exist, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the input file or directory :type path: string (path) :rtype: bool """ if (not gf...
If the given path does not exist, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the input file :type path: string (path) :rtype: bool
def check_input_file(self, path): """ If the given path does not exist, emit an error and return ``False``. Otherwise return ``True``. :param path: the path of the input file :type path: string (path) :rtype: bool """ if not gf.file_can_be_read(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
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(p...
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
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.i...
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`
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...
Return ``True`` if ``entry`` can be safely extracted, that is, if it does start with ``/`` or ``../`` after path normalization, ``False`` otherwise. :rtype: bool
def is_entry_safe(self, entry): """ Return ``True`` if ``entry`` can be safely extracted, that is, if it does start with ``/`` or ``../`` after path normalization, ``False`` otherwise. :rtype: bool """ normalized = os.path.normpath(entry) if normalized.st...
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 (...
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 give...
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 = "co...
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...
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`
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` ...
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 e...
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, ...
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...
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:...
Return ``True`` if the container has its path set and it exists, ``False`` otherwise. :rtype: boolean
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)
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` ...
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 :cla...
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))
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 audi...
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``
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`` ...
Analyze the given container and return the corresponding job. If ``config_string`` is ``None``, try reading it from the TXT config file inside the container. :param string config_string: the configuration string :rtype: :class:`~aeneas.job.Job`
def _analyze_txt_config(self, config_string=None): """ Analyze the given container and return the corresponding job. If ``config_string`` is ``None``, try reading it from the TXT config file inside the container. :param string config_string: the configuration string :rt...
Analyze the given container and return the corresponding job. If ``config_contents`` is ``None``, try reading it from the XML config file inside the container. :param string config_contents: the contents of the XML config file :rtype: :class:`~aeneas.job.Job`
def _analyze_xml_config(self, config_contents=None): """ Analyze the given container and return the corresponding job. If ``config_contents`` is ``None``, try reading it from the XML config file inside the container. :param string config_contents: the contents of the XML config...
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_ma...
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`...
Replace the prefix placeholder :class:`~aeneas.globalconstants.PPV_OS_TASK_PREFIX` with ``custom_id`` and return the resulting string. :rtype: string
def _replace_placeholder(self, string, custom_id): """ Replace the prefix placeholder :class:`~aeneas.globalconstants.PPV_OS_TASK_PREFIX` with ``custom_id`` and return the resulting string. :rtype: string """ if string is None: return None sel...
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_...
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 :p...
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 ...
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: t...
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 ...
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", "f...
Match directory names in paged hierarchies. Example: :: root = /foo/bar regex_string = [0-9]+ /foo/bar/ 1/ bar baz 2/ bar 3/ ...
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 ...
Perform command and return the appropriate exit code. :rtype: int
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 2: return self.print_help() text_format = gf.safe_unicode(self.actual_arguments[0]) if text_format == u"list": ...
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`
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` ""...
Log begin of a step
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))
Log end of a step
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) sel...
Log failure of a step
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)
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 exec...
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 ...
Execute a 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._extr...
Execute a multi-level task
def _execute_multi_level_task(self): """ Execute a multi-level task """ self.log(u"Executing multi level task...") self.log(u"Saving rconf...") # save original rconf orig_rconf = self.rconf.clone() # clone rconfs and set granularity # TODO the following code assu...
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 repre...
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 ...
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...
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 i...
Load audio in memory. :rtype: :class:`~aeneas.audiofile.AudioFile`
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...
Clear audio from memory. :param audio_file: the object to clear :type audio_file: :class:`~aeneas.audiofile.AudioFile`
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 ...
Extract the MFCCs from the given audio file. :rtype: :class:`~aeneas.audiofilemfcc.AudioFileMFCC`
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_fo...
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)
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, tai...
Create synthesizer
def _set_synthesizer(self): """ Create synthesizer """ self.log(u"Setting synthesizer...") self.synthesizer = Synthesizer(rconf=self.rconf, logger=self.logger) self.log(u"Setting synthesizer... done")
Clear the cache of the 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")