Ejemplo n.º 1
0
def main(return_tagdir=False):
    utils.parse_options()
    utils.configure_logging()
    releaser = Releaser()
    releaser.run()
    tagdir = releaser.data.get('tagdir')
    if tagdir:
        logger.info("Reminder: tag checkout is in %s", tagdir)
Ejemplo n.º 2
0
def main(return_tagdir=False):
    utils.parse_options()
    utils.configure_logging()
    releaser = Releaser()
    releaser.run()
    tagdir = releaser.data.get('tagdir')
    if tagdir:
        logger.info("Reminder: tag checkout is in %s", tagdir)
Ejemplo n.º 3
0
def handle_options(args):
    utils.parse_options(options, args)

    print(options)
    if options.bible != None:
        verse_role.set_version(options.bible)
        biblepassage.set_version(options.bible)

    if not options.draft:
        #print('NOT DRAFT')
        docutil_settings['strip_elements_with_classes'] = ['comment']
    else:
        #print('DRAFT')
        if 'strip_elements_with_classes' in docutil_settings:
            del docutil_settings['strip_elements_with_classes']
Ejemplo n.º 4
0
def handle_options(args):
    utils.parse_options(options, args)

    print(options)
    if options.bible != None:
        verse_role.set_version(options.bible)
        biblepassage.set_version(options.bible)

    if not options.draft:
        #print('NOT DRAFT')
        docutil_settings['strip_elements_with_classes'] = ['comment']
    else:
        #print('DRAFT')
        if 'strip_elements_with_classes' in docutil_settings:
            del docutil_settings['strip_elements_with_classes']
Ejemplo n.º 5
0
def echo(ctx, n, *args, **kwargs):
    """
    Display the passed options N times
    """
    input_type, value = parse_options(kwargs)
    click.echo("\nThe given input was of type: {}\n"
               "And the value was: {}\n".format(input_type, value) * n)
Ejemplo n.º 6
0
def print_mat(ctx, *args, **kwargs):
    """
    print's the supplied matrix
    """
    input_type, value = parse_options(kwargs)
    mat = import_mat(ctx)
    if isinstance(mat, scipy.sparse.spmatrix):
        mat = mat.todense()
    click.echo(mat)
Ejemplo n.º 7
0
def main():
    utils.parse_options()
    utils.configure_logging()
    logger.info('Starting prerelease.')
    original_dir = os.getcwd()
    # prerelease
    prereleaser = prerelease.Prereleaser()
    prereleaser.run()
    logger.info('Starting release.')
    # release
    releaser = release.Releaser(vcs=prereleaser.vcs)
    releaser.run()
    tagdir = releaser.data.get('tagdir')
    logger.info('Starting postrelease.')
    # postrelease
    postreleaser = postrelease.Postreleaser(vcs=releaser.vcs)
    postreleaser.run()
    os.chdir(original_dir)
    logger.info('Finished full release.')
    if tagdir:
        logger.info("Reminder: tag checkout is in %s", tagdir)
Ejemplo n.º 8
0
 def __init__(self, options = {}):
     defaults = yaml.load(file(config.base_dir + 'scripts/defaults.yml', 'r'), Loader=yaml.Loader)['layer']
     self.options = utils.parse_options(options, defaults)
     self.nodes = []
     self.links_in = []
     self.links_out = []
     self.is_active = True
     for i in range(self.options['size']): 
         self.nodes.append(Node(self))
     
     # Add bias node
     if self.options['bias_node']:
         self.nodes.append(Node(self))
         self.nodes[-1].set_bias()
Ejemplo n.º 9
0
    def __init__(self, options={}):
        defaults = yaml.load(file(config.base_dir + 'scripts/defaults.yml',
                                  'r'),
                             Loader=yaml.Loader)['layer']
        self.options = utils.parse_options(options, defaults)
        self.nodes = []
        self.links_in = []
        self.links_out = []
        self.is_active = True
        for i in range(self.options['size']):
            self.nodes.append(Node(self))

        # Add bias node
        if self.options['bias_node']:
            self.nodes.append(Node(self))
            self.nodes[-1].set_bias()
Ejemplo n.º 10
0
def handle_options(args):
    utils.parse_options(options, args)
Ejemplo n.º 11
0
def main():
    utils.parse_options()
    utils.configure_logging()
    prereleaser = Prereleaser()
    prereleaser.run()
Ejemplo n.º 12
0
  cert.gmtime_adj_notAfter(DEFAULT_VALIDITY_DAYS)
  cert.set_issuer(ca_cert.get_subject())
  cert.set_pubkey(req.get_pubkey())
  cert.set_version(0x02)
  cert.add_extensions([
    OpenSSL.crypto.X509Extension("basicConstraints", False,
                                 "CA:FALSE"),
    ])
  cert.sign(ca_key, X509_CERT_SIGN_DIGEST)

  utils.WriteCertificate(cert, certfile)


if __name__ == "__main__":

  args = utils.parse_options()

  certs = [
    (args.server_create, args.server_sign_method,
     args.server_cert, args.server_key, args.server_req,
     args.server_hostname),
    (args.client_create, args.client_sign_method,
     args.client_cert, args.client_key, args.client_req,
     args.client_hostname),
          ]

  if args.ca_create:
    (cakeypem, cacertpem) = GenerateSelfSignedCert(
      args.ca_hostname, args.ca_cert, args.ca_key)
    VerifyKeyCertFile(args.ca_key, args.ca_cert)
Ejemplo n.º 13
0
 def __init__(self, options={}):
     defaults = yaml.load(file(config.base_dir + 'scripts/defaults.yml',
                               'r'),
                          Loader=yaml.Loader)['link']
     self.options = utils.parse_options(options, defaults)
Ejemplo n.º 14
0
def handle_options(args):
    utils.parse_options(options, args)
Ejemplo n.º 15
0
    def run(self):
        """Called as a result of self.__init__().

        Creates a child process to run the youtube-dl system command.

        Reads from the child process STDOUT and STDERR, and calls the main
        application with the result of the process (success or failure).
        """

        # Checking for a new release of Tartube doesn't involve any system
        #   commands or child processes, so it is handled by a separate
        #   function
        if self.info_type == 'version':

            return self.run_check_version()

        # Show information about the info operation in the Output tab
        if self.info_type == 'test_ytdl':

            msg = _(
                'Starting info operation, testing downloader with specified' \
                + ' options',
            )

        else:

            if self.info_type == 'formats':

                msg = _(
                    'Starting info operation, fetching list of video/audio'\
                    + ' formats for \'{0}\'',
                ).format(self.video_obj.name)

            else:

                msg = _(
                    'Starting info operation, fetching list of subtitles'\
                    + ' for \'{0}\'',
                ).format(self.video_obj.name)

        self.app_obj.main_win_obj.output_tab_write_stdout(1, msg)

        # Convert a path beginning with ~ (not on MS Windows)
        ytdl_path = self.app_obj.check_downloader(self.app_obj.ytdl_path)
        if os.name != 'nt':
            ytdl_path = re.sub('^\~', os.path.expanduser('~'), ytdl_path)

        # Prepare the system command...
        if self.info_type == 'formats':

            cmd_list = [
                ytdl_path,
                '--list-formats',
                self.video_obj.source,
            ]

        elif self.info_type == 'subs':

            cmd_list = [
                ytdl_path,
                '--list-subs',
                self.video_obj.source,
            ]

        else:

            if self.app_obj.ytdl_path_custom_flag:
                cmd_list = ['python3'] + [ytdl_path]
            else:
                cmd_list = [ytdl_path]

            if self.options_string is not None \
            and self.options_string != '':

                # Parse the string into a list. It was obtained from a
                #   Gtk.TextView, so it can contain newline and/or multiple
                #   whitepsace characters. Whitespace characters within
                #   double quotes "..." must be preserved
                option_list = utils.parse_options(self.options_string)
                for item in option_list:
                    cmd_list.append(item)

            if self.url_string is not None \
            and self.url_string != '':

                cmd_list.append('-o')
                cmd_list.append(
                    os.path.join(
                        self.app_obj.temp_test_dir,
                        '%(title)s.%(ext)s',
                    ), )

                cmd_list.append(self.url_string)

        # ...display it in the Output tab (if required)
        space = ' '
        self.app_obj.main_win_obj.output_tab_write_system_cmd(
            1,
            space.join(cmd_list),
        )

        # Create a new child process using that command...
        self.create_child_process(cmd_list)
        # ...and set up the PipeReader objects to read from the child process
        #   STDOUT and STDERR
        if self.child_process is not None:
            self.stdout_reader.attach_fh(self.child_process.stdout)
            self.stderr_reader.attach_fh(self.child_process.stderr)

        while self.is_child_process_alive():

            # Pause a moment between each iteration of the loop (we don't want
            #   to hog system resources)
            time.sleep(self.sleep_time)

            # Read from the child process STDOUT and STDERR, in the correct
            #   order, until there is nothing left to read
            while self.read_child_process():
                pass

        # (Generate our own error messages for debugging purposes, in certain
        #   situations)
        if self.child_process is None:

            msg = _('System process did not start')
            self.stderr_list.append(msg)
            self.app_obj.main_win_obj.output_tab_write_stdout(
                1,
                msg,
            )

        elif self.child_process.returncode > 0:

            msg = _('Child process exited with non-zero code: {}').format(
                self.child_process.returncode, )
            self.app_obj.main_win_obj.output_tab_write_stdout(
                1,
                msg,
            )

        # Operation complete. self.success_flag is checked by
        #   mainapp.TartubeApp.info_manager_finished()
        if not self.stderr_list:
            self.success_flag = True

        # Show a confirmation in the the Output tab
        self.app_obj.main_win_obj.output_tab_write_stdout(
            1,
            _('Info operation finished'),
        )

        # Let the timer run for a few more seconds to prevent Gtk errors
        GObject.timeout_add(
            0,
            self.app_obj.info_manager_halt_timer,
        )
Ejemplo n.º 16
0
    def get_system_cmd(self, app_obj, video_obj=None, start_point=None,
    stop_point=None, clip_title=None, clip_dir=None, edit_dict=[]):

        """Can be called by anything.

        Given the FFmpeg options specified by self.options_dict, generates the
        FFmpeg system command, returning it as a list of options.

        N.B. The 'delete_original_flag' option is not applied until the end of
        the process operation.

        Args:

            app_obj (mainapp.TartubeApp): The main application

            video_obj (media.Video or None): If specified, uses the video's
                downloaded file as the source file. Not specified when called
                from config.FFmpegOptionsEditWin, in which case a specimen
                source file is used (so that a specimen system command can be
                displayed in the edit window)

            start_point, stop_point, clip_title, clip_dir (str):
                When splitting a video, the points at which to start/stop
                (timestamps or values in seconds), the clip title, and the
                destination directory for sections (if not the same as the
                original file). Ignored if 'output_mode' is not 'split' or
                'slice'. If 'output_mode' is 'split' or 'slice', then these
                arguments are not specified when called from
                config.FFmpegOptionsEditWin, in which case specimen timestamps/
                titles are used

            edit_dict (dict): When called from the edit window, any changes
                that have been made to the FFmpeg options, but which have not
                yet been saved to this object. We take those changes into
                account when compiling the system command.

        Return values:

            Returns a tuple of three items:

                - The full path to the source file
                - The full path to the output file
                - A (python) list of options comprising the complete system
                    commmand (including the FFmpeg binary and the source/output
                    files)

        """

        opt_list = []
        tuning_list = []
        return_list = []

        # When called from the edit window (config.FFmpegOptionsEditWin), any
        #   changes in the edit window may not have been applied to
        #   self.options_dict yet
        # To produce an up-to-date system command, use a temporary copy of
        #   self.options_dict, to which the unapplied changes have been added
        options_dict = self.options_dict.copy()
        for key in edit_dict:
            options_dict[key] = edit_dict[key]

        # (Shortcuts to values retrieved several times)
        bitrate = options_dict['bitrate']
        input_mode = options_dict['input_mode']
        limit_buffer = options_dict['limit_buffer']
        limit_mbps = options_dict['limit_mbps']
        output_mode = options_dict['output_mode']
        rate_factor = options_dict['rate_factor']

        # The 'extra_cmd_string' item must be processed, and split into
        #   a list of separate items, preserving everything inside quotes as a
        #   single item (just as we do for youtube-dl download options)
        extra_cmd_string = options_dict['extra_cmd_string']
        if extra_cmd_string != '':
            extra_cmd_list = utils.parse_options(extra_cmd_string)
        else:
            extra_cmd_list = []

        # FFmpeg binary
        binary = app_obj.ffmpeg_manager_obj.get_executable()

        # Set variables describing the full path to the source video/audio and/
        #   or source thumbnail files

        # If no media.Video object was specified, then use specimen paths that
        #   can be displayed in the edit window's textview
        if video_obj is None:

            source_video_path = 'source.ext'
            source_audio_path = 'source.ext'
            source_thumb_path = 'source.jpg'

        else:

            if video_obj.dummy_flag:

                # (Special case: 'dummy' video objects (those downloaded in the
                #   Classic Mode tab) use different IVs)

                # If a specified media.Video has an unknown path, then return
                #   an empty list; there is nothing for FFmpeg to convert
                if video_obj.dummy_path is None:
                    return None

                # Check the video/audio file actually exists. If not, there is
                #   nothing for FFmpeg to convert
                source_video_path = video_obj.dummy_path
                if not os.path.exists(source_video_path) \
                and input_mode == 'video':
                    return None, None, []

            else:

                # If a specified media.Video has an unknown filename, then
                #   return an empty list; there is nothing for FFmpeg to
                #   convert
                if video_obj.file_name is None:
                    return None, None, []

                # Check the video/audio file actually exists, and is marked as
                #   downloaded. If not, there is nothing for FFmpeg to convert
                source_video_path = video_obj.get_actual_path(app_obj)
                if (
                    not os.path.exists(source_video_path) \
                    or not video_obj.dl_flag
                ) and input_mode == 'video':
                    return None, None, []

            # Find the video's thumbnail
            source_thumb_path = utils.find_thumbnail(app_obj, video_obj, True)
            if source_thumb_path is None and input_mode == 'thumb':
                # Return an empty list; there is nothing for FFmpeg to convert
                return None, None, []

            # If 'output_mode' is 'merge', then look for an audio file with the
            #   same name as the video file (but otherwise don't bother)
            source_audio_path = None
            if output_mode == 'merge':

                name, video_ext = os.path.splitext(source_video_path)
                for audio_ext in formats.AUDIO_FORMAT_LIST:

                    audio_path = os.path.abspath(os.path.join(name, audio_ext))
                    if os.path.isfile(audio_path):
                        source_audio_path = audio_path
                        break

                if source_audio_path is None:
                    # Nothing merge
                    return None, None, []

        # Break down the full path into its components, so that we can set the
        #   output file, after applying optional modifications
        if input_mode == 'video':
            output_dir, output_file = os.path.split(source_video_path)
        else:
            output_dir, output_file = os.path.split(source_thumb_path)

        output_name, output_ext = os.path.splitext(output_file)

        add_end_filename = options_dict['add_end_filename']
        if add_end_filename != '':

            # Remove trailing whitepsace
            add_end_filename = re.sub(
                r'\s+$',
                '',
                options_dict['add_end_filename'],
            )

            # Update the filename
            output_name += add_end_filename

        regex_match_filename = options_dict['regex_match_filename']
        if regex_match_filename != '':

            output_name = re.sub(
                regex_match_filename,
                options_dict['regex_apply_subst'],
                output_name,
            )

        change_file_ext = options_dict['change_file_ext'].lower()
        if change_file_ext == '':
            output_file = output_name + output_ext
        else:
            output_file = output_name + '.' + change_file_ext

        if video_obj is None:
            output_path = output_file
        else:
            output_path = os.path.abspath(
                os.path.join(output_dir, output_file),
            )

        # Special case: when called from config.FFmpegOptionsEditWin, then show
        #   a specimen system command resembling the one that will eventually
        #   be generated by FFmpegManager.run_ffmpeg_multiple_files()
        if app_obj.ffmpeg_simple_options_flag \
        and video_obj is None \
        and output_mode != 'split' \
        and output_mode != 'slice':

            return_list.append(binary)
            return_list.append('-y')
            return_list.append('-loglevel')
            return_list.append('repeat+info')
            return_list.append('-i')

            if input_mode == 'video':
                return_list.append(source_video_path)
            else:
                return_list.append(source_thumb_path)

            if extra_cmd_list:
                return_list.extend(extra_cmd_list)

            return_list.extend(
                [
                    app_obj.ffmpeg_manager_obj._ffmpeg_filename_argument(
                        output_path,
                    ),
                ],
            )

            return source_video_path, output_path, return_list

        # When the full GUI layout is visible, apply all FFmpeg options
        if input_mode == 'video':

            opt_list.append('-i')
            opt_list.append(source_video_path)

        else:

            opt_list.append('-i')
            opt_list.append(source_thumb_path)

        # H.264
        if output_mode == 'h264':

            # In the original code, this was marked:
            #   Only necessary if the output filename does not end with .mp4
            opt_list.append('-c:v')
            opt_list.append(options_dict['gpu_encoding'])

            opt_list.append('-preset')
            opt_list.append(options_dict['patience_preset'])

            if options_dict['hw_accel'] != 'none':
                opt_list.append('-hwaccel')
                opt_list.append(options_dict['hw_accel'])

            if options_dict['tuning_film_flag']:
                tuning_list.append('film')
            if options_dict['tuning_animation_flag']:
                tuning_list.append('animation')
            if options_dict['tuning_grain_flag']:
                tuning_list.append('grain')
            if options_dict['tuning_still_image_flag']:
                tuning_list.append('stillimage')
            if options_dict['tuning_fast_decode_flag']:
                tuning_list.append('fastdecode')
            if options_dict['tuning_zero_latency_flag']:
                tuning_list.append('zerolatency')

            if tuning_list:
                opt_list.append('-tune')
                opt_list.append(','.join(tuning_list))

            if options_dict['fast_start_flag']:
                opt_list.append('-movflags')
                opt_list.append('faststart')

            if input_mode == 'video' and options_dict['audio_flag']:
                opt_list.append('-c:a')
                opt_list.append('aac')
                opt_list.append('-b:a')
                opt_list.append(
                    str(options_dict['audio_bitrate']) + 'k',
                )

            if options_dict['profile_flag'] and rate_factor != 0:
                opt_list.append('-profile:v')
                opt_list.append('baseline')
                opt_list.append('-level')
                opt_list.append('3.0')

            if options_dict['limit_flag']:
                opt_list.append('-maxrate')
                opt_list.append(str(limit_mbps) + 'M')
                opt_list.append('-bufsize')
                opt_list.append((str(limit_mbps) * str(limit_buffer)) + 'M')

            if options_dict['seek_flag']:

                # In the original code, this was marked:
                #   Inserts an I-frame every 15 frames
                opt_list.append('-x264-params')
                opt_list.append('keyint=15')

            # In the original code, this was marked:
            #   Preserves the frame timestamps of VFR videos
            opt_list.append('-vsync')
            opt_list.append('2')
            opt_list.append('-enc_time_base')
            opt_list.append('-1')

            if options_dict['quality_mode'] == 'crf':

                return_list.append(binary)
                return_list.extend(opt_list)
                return_list.append('-crf')
                return_list.append(str(rate_factor))

                if extra_cmd_list:
                    return_list.extend(extra_cmd_list)

                return_list.append(output_path)

            else:
                dummy_file = options_dict['dummy_file']
                if dummy_file == 'output':
                    dummy_file = output_path

                return_list.append(binary)
                return_list.append('-y')
                return_list.extend(opt_list)
                return_list.append('-b:v')
                return_list.append(str(bitrate))
                return_list.append('-pass')
                return_list.append('1')
                return_list.append('-f')
                return_list.append('mp4')
                return_list.append(dummy_file)

                return_list.append('&&')
                return_list.append(binary)
                return_list.extend(opt_list)
                return_list.append('-b:v')
                return_list.append(str(bitrate))
                return_list.append('-pass')
                return_list.append('2')

                if extra_cmd_list:
                    return_list.extend(extra_cmd_list)

                return_list.append(output_path)

        # GIF
        elif output_mode == 'gif':

            if options_dict['palette_mode'] == 'faster':

                return_list.append(binary)
                return_list.extend(opt_list)

                if extra_cmd_list:
                    return_list.extend(extra_cmd_list)

                return_list.append(output_name + '.gif')

            else:

                return_list.append(binary)
                return_list.extend(opt_list)
                return_list.append('-vf')
                return_list.append('palettegen')
                return_list.append('palette.png')

                return_list.append('&&')
                return_list.append(binary)
                return_list.extend(opt_list)
                return_list.append('-i')
                return_list.append('palette.png')
                return_list.append('-filter_complex')
                return_list.append('"[0:v][1:v] paletteuse"')

                if extra_cmd_list:
                    return_list.extend(extra_cmd_list)

                return_list.append(output_name + '.gif')

        # Merge video/audio
        elif output_mode == 'merge':

            return_list.append(binary)
            return_list.extend(opt_list)

            return_list.append('-i')
            return_list.append(source_audio_path)
            return_list.append('-c:v')
            return_list.append('copy')
            return_list.append('-c:a')
            return_list.append('copy')

            return_list.append(output_path)

        # Split video by timestamps, or times in seconds
        elif output_mode == 'split' or output_mode == 'slice':

            return_list.append(binary)
            return_list.extend(opt_list)

            if output_mode == 'split':

                return_list.append('-ss')
                if start_point is None:
                    # (A specimen timestamp)
                    return_list.append('0:00')
                else:
                    return_list.append(str(start_point))

                # (If no timestamp is specified, the end of the video is used)
                if stop_point is not None:
                    return_list.append('-to')
                    return_list.append(str(stop_point))

            else:

                return_list.append('-ss')
                if start_point is None:
                    # (A specimen time, in seconds)
                    return_list.append('0')
                else:
                    return_list.append(str(start_point))

                # (If no timestamp is specified, the end of the video is used)
                if stop_point is not None:
                    return_list.append('-to')
                    return_list.append(str(stop_point))

            if clip_title is None or clip_title == "":
                # (When called from config.FFmpegOptionsEditWin)
                clip_title = app_obj.split_video_generic_title

            if clip_dir is None:

                output_path = os.path.abspath(
                    os.path.join(output_dir, clip_title + output_ext),
                )

            else:

                output_path = os.path.abspath(
                    os.path.join(clip_dir, clip_title + output_ext),
                )

            return_list.append(output_path)

        # Video thumbnails
        else:

            return_list.append(binary)
            return_list.extend(opt_list)
            return_list.append(output_path)

        # All done
        if output_mode == 'thumb':
            return source_thumb_path, output_path, return_list
        else:
            return source_video_path, output_path, return_list
Ejemplo n.º 17
0
def main():
    utils.parse_options()
    utils.configure_logging()
    prereleaser = Prereleaser()
    prereleaser.run()
Ejemplo n.º 18
0
 def __init__(self, options = {}):
     defaults = yaml.load(file(config.base_dir + 'scripts/defaults.yml', 'r'), Loader=yaml.Loader)['link']
     self.options = utils.parse_options(options, defaults)
Ejemplo n.º 19
0
    def run(self):

        """Called as a result of self.__init__().

        Creates a child process to run the youtube-dl system command.

        Reads from the child process STDOUT and STDERR, and calls the main
        application with the result of the process (success or failure).
        """

        # Checking for a new release of Tartube doesn't involve any system
        #   commands or child processes, so it is handled by a separate
        #   function
        if self.info_type == 'version':

            return self.run_check_version()

        # Show information about the info operation in the Output Tab
        if self.info_type == 'test_ytdl':

            msg = _(
                'Starting info operation, testing downloader with specified' \
                + ' options',
            )

        else:

            if self.info_type == 'formats':

                msg = _(
                    'Starting info operation, fetching list of video/audio'\
                    + ' formats for \'{0}\'',
                ).format(self.video_obj.name)

            else:

                msg = _(
                    'Starting info operation, fetching list of subtitles'\
                    + ' for \'{0}\'',
                ).format(self.video_obj.name)

        self.app_obj.main_win_obj.output_tab_write_stdout(1, msg)

        # Convert a path beginning with ~ (not on MS Windows)
        ytdl_path = self.app_obj.check_downloader(self.app_obj.ytdl_path)
        if os.name != 'nt':
            ytdl_path = re.sub('^\~', os.path.expanduser('~'), ytdl_path)

        # Prepare the system command
        if self.info_type == 'formats':

            cmd_list = [
                ytdl_path,
                '--list-formats',
                self.video_obj.source,
            ]

        elif self.info_type == 'subs':

            cmd_list = [
                ytdl_path,
                '--list-subs',
                self.video_obj.source,
            ]

        else:

            if app_obj.ytdl_path_custom_flag:
                cmd_list = ['python3'] + [ytdl_path]
            else:
                cmd_list = [ytdl_path]

            if self.options_string is not None \
            and self.options_string != '':

                # Parse the string into a list. It was obtained from a
                #   Gtk.TextView, so it can contain newline and/or multiple
                #   whitepsace characters. Whitespace characters within
                #   double quotes "..." must be preserved
                option_list = utils.parse_options(self.options_string)
                for item in option_list:
                    cmd_list.append(item)

            if self.url_string is not None \
            and self.url_string != '':

                cmd_list.append('-o')
                cmd_list.append(
                    os.path.join(
                        self.app_obj.temp_test_dir,
                        '%(title)s.%(ext)s',
                    ),
                )

                cmd_list.append(self.url_string)

        # Create the new child process
        self.create_child_process(cmd_list)

        # Show the system command in the Output Tab
        space = ' '
        self.app_obj.main_win_obj.output_tab_write_system_cmd(
            1,
            space.join(cmd_list),
        )

        # So that we can read from the child process STDOUT and STDERR, attach
        #   a file descriptor to the PipeReader objects
        if self.child_process is not None:

            self.stdout_reader.attach_file_descriptor(
                self.child_process.stdout,
            )

            self.stderr_reader.attach_file_descriptor(
                self.child_process.stderr,
            )

        while self.is_child_process_alive():

            # Read from the child process STDOUT, and convert into unicode for
            #   Python's convenience
            while not self.stdout_queue.empty():

                stdout = self.stdout_queue.get_nowait().rstrip()
                if stdout:

                    if os.name == 'nt':
                        stdout = stdout.decode('cp1252')
                    else:
                        stdout = stdout.decode('utf-8')

                    self.output_list.append(stdout)
                    self.stdout_list.append(stdout)

                    # Show command line output in the Output Tab
                    self.app_obj.main_win_obj.output_tab_write_stdout(
                        1,
                        stdout,
                    )

        # The child process has finished
        while not self.stderr_queue.empty():

            # Read from the child process STDERR queue (we don't need to read
            #   it in real time), and convert into unicode for python's
            #   convenience
            stderr = self.stderr_queue.get_nowait().rstrip()
            if os.name == 'nt':
                stderr = stderr.decode('cp1252')
            else:
                stderr = stderr.decode('utf-8')

            if stderr:

                # While testing youtube-dl, don't treat anything as an error
                if self.info_type == 'test_ytdl':
                    self.stdout_list.append(stderr)

                # When fetching subtitles from a video that has none, don't
                #   treat youtube-dl WARNING: messages as something that
                #   makes the info operation fail
                elif self.info_type == 'subs':

                    if not re.match('WARNING\:', stderr):
                        self.stderr_list.append(stderr)

                # When fetching formats, recognise all warnings as errors
                else:
                    self.stderr_list.append(stderr)

                # Show command line output in the Output Tab
                self.app_obj.main_win_obj.output_tab_write_stderr(
                    1,
                    stderr,
                )

        # (Generate our own error messages for debugging purposes, in certain
        #   situations)
        if self.child_process is None:

            msg = _('System process did not start')
            self.stderr_list.append(msg)
            self.app_obj.main_win_obj.output_tab_write_stdout(
                1,
                msg,
            )

        elif self.child_process.returncode > 0:

            msg = _('Child process exited with non-zero code: {}').format(
                self.child_process.returncode,
            )
            self.app_obj.main_win_obj.output_tab_write_stdout(
                1,
                msg,
            )

        # Operation complete. self.success_flag is checked by
        #   mainapp.TartubeApp.info_manager_finished()
        if not self.stderr_list:
            self.success_flag = True

        # Show a confirmation in the the Output Tab
        self.app_obj.main_win_obj.output_tab_write_stdout(
            1,
            _('Info operation finished'),
        )

        # Let the timer run for a few more seconds to prevent Gtk errors (for
        #   systems with Gtk < 3.24)
        GObject.timeout_add(
            0,
            self.app_obj.info_manager_halt_timer,
        )
Ejemplo n.º 20
0
def main():
    params = parse_options("params.yaml")

    cap = cv2.VideoCapture(params["video_path"])
    aruco_dict = aruco.Dictionary_get(aruco.DICT_4X4_50)

    aruco_params = aruco.DetectorParameters_create()
    aruco_params.cornerRefinementMethod = \
        aruco.CORNER_REFINE_SUBPIX
    aruco_params.cornerRefinementWinSize = 5
    aruco_params.minMarkerDistanceRate = 0.05
    aruco_params.cornerRefinementMinAccuracy = 0.5

    resize_factor = params["aruco_detection_resize_factor"]

    print("\n==============")
    print("Press CTRL and C simuntaniously to exit program")
    print("==============\n")
    try:
        while True:
            ret, frame = cap.read()

            width = int(frame.shape[1] * resize_factor)
            height = int(frame.shape[0] * resize_factor)
            dim = (width, height)
            resized_frame = cv2.resize(frame,
                                       dim,
                                       interpolation=cv2.INTER_AREA)
            corners, aruco_ids, rejected = aruco.detectMarkers(
                resized_frame, aruco_dict, parameters=aruco_params)

            if len(corners) > 0:
                for corner, aruco_id in zip(corners, aruco_ids):
                    show_aruco, robo_params = find_params_by_aruco_id(
                        aruco_id, params)
                    if show_aruco is False:
                        continue

                    center = np.mean(corner, axis=1, dtype=np.int32)[0]

                    overlay = np.full(
                        [params["box"]["y_size"], params["box"]["x_size"], 3],
                        robo_params["box_color"][::-1],
                        dtype=np.uint8)

                    # TODO: X and Y use is abmiguous. Which one is which?
                    x_start = int((center[1] / resize_factor) -
                                  int(params["box"]["y_size"] / 2))
                    x_stop = x_start + int(params["box"]["y_size"])
                    y_start = int((center[0] / resize_factor) -
                                  int(params["box"]["x_size"] / 2))
                    y_stop = y_start + int(params["box"]["x_size"])

                    x_start_idx = clamp(
                        x_start, 0, frame.shape[0] - params["box"]["y_size"])
                    x_stop_idx = clamp(x_stop, params["box"]["y_size"],
                                       frame.shape[0])
                    y_start_idx = clamp(
                        y_start, 0, frame.shape[1] - params["box"]["x_size"])
                    y_stop_idx = clamp(y_stop, params["box"]["x_size"],
                                       frame.shape[1])

                    # https://stackoverflow.com/questions/40895785/using-opencv-to-overlay-transparent-image-onto-another-image
                    overlay = cv2.addWeighted(
                        frame[x_start_idx:x_stop_idx, y_start_idx:y_stop_idx],
                        params["box"]["transparentness"], overlay,
                        1 - params["box"]["transparentness"], 0)
                    frame[x_start_idx:x_stop_idx,
                          y_start_idx:y_stop_idx] = overlay

                    text_start = (
                        int((center[0] + params["text"]["offset_x"]) /
                            resize_factor),
                        int((center[1] + params["text"]["offset_y"]) /
                            resize_factor))

                    aruco_text = robo_params["name"]
                    cv2.putText(
                        frame, aruco_text, text_start,
                        getattr(cv2, params["text"]["font_name"],
                                "FONT_HERSHEY_SIMPLEX"),
                        params["text"]["size"],
                        robo_params["text_color"][::-1],
                        params["text"]["thickness"], cv2.LINE_4)

            if params["show_aruco_detection_image"]:
                cv2.imshow('Aruco marker detection image', resized_frame)
            cv2.imshow('out', frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        # When everything done, release the capture

    except KeyboardInterrupt:
        print("Exiting")
    # except Exception as error:
    #     print(f'Got unexpected exception in "main" Message: {error}')
    finally:
        cap.release()
        cv2.destroyAllWindows()