示例#1
0
文件: audiofile.py 项目: dburt/aeneas
 def __str__(self):
     accumulator = ""
     accumulator += "File path:         %s\n" % self.file_path
     accumulator += "File size (bytes): %s\n" % gf.safe_int(self.file_size)
     accumulator += "Audio length (s):  %s\n" % gf.safe_float(self.audio_length)
     accumulator += "Audio format:      %s\n" % self.audio_format
     accumulator += "Audio sample rate: %s\n" % gf.safe_int(self.audio_sample_rate)
     accumulator += "Audio channels:    %s" % gf.safe_int(self.audio_channels)
     return accumulator
示例#2
0
    def read_properties(self):
        """
        Populate this object by reading
        the audio properties of the file at the given path.

        Currently this function uses
        :class:`~aeneas.ffprobewrapper.FFPROBEWrapper`
        to get the audio file properties.

        :raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called
        :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
        :raises: OSError: if the audio file cannot be read
        """
        self.log(u"Reading properties...")

        # check the file can be read
        if not gf.file_can_be_read(self.file_path):
            self.log_exc(u"File '%s' cannot be read" % (self.file_path), None,
                         True, OSError)

        # get the file size
        self.log([u"Getting file size for '%s'", self.file_path])
        self.file_size = gf.file_size(self.file_path)
        self.log(
            [u"File size for '%s' is '%d'", self.file_path, self.file_size])

        # get the audio properties using FFPROBEWrapper
        try:
            self.log(u"Reading properties with FFPROBEWrapper...")
            properties = FFPROBEWrapper(rconf=self.rconf,
                                        logger=self.logger).read_properties(
                                            self.file_path)
            self.log(u"Reading properties with FFPROBEWrapper... done")
        except FFPROBEPathError:
            self.log_exc(u"Unable to call ffprobe executable", None, True,
                         AudioFileProbeError)
        except (FFPROBEUnsupportedFormatError, FFPROBEParsingError):
            self.log_exc(u"Audio file format not supported by ffprobe", None,
                         True, AudioFileUnsupportedFormatError)

        # save relevant properties in results inside the audiofile object
        self.audio_length = TimeValue(
            properties[FFPROBEWrapper.STDOUT_DURATION])
        self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
        self.audio_sample_rate = gf.safe_int(
            properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
        self.audio_channels = gf.safe_int(
            properties[FFPROBEWrapper.STDOUT_CHANNELS])
        self.log([u"Stored audio_length: '%s'", self.audio_length])
        self.log([u"Stored audio_format: '%s'", self.audio_format])
        self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate])
        self.log([u"Stored audio_channels: '%s'", self.audio_channels])
        self.log(u"Reading properties... done")
示例#3
0
 def __str__(self):
     accumulator = ""
     accumulator += "File path:         %s\n" % self.file_path
     accumulator += "File size (bytes): %s\n" % gf.safe_int(self.file_size)
     accumulator += "Audio length (s):  %s\n" % gf.safe_float(
         self.audio_length)
     accumulator += "Audio format:      %s\n" % self.audio_format
     accumulator += "Audio sample rate: %s\n" % gf.safe_int(
         self.audio_sample_rate)
     accumulator += "Audio channels:    %s" % gf.safe_int(
         self.audio_channels)
     return accumulator
示例#4
0
 def __unicode__(self):
     msg = [
         u"File path:         %s" % self.file_path,
         u"File size (bytes): %s" % gf.safe_int(self.file_size),
         u"Audio length (s):  %s" % gf.safe_float(self.audio_length),
         u"Audio format:      %s" % self.audio_format,
         u"Audio sample rate: %s" % gf.safe_int(self.audio_sample_rate),
         u"Audio channels:    %s" % gf.safe_int(self.audio_channels),
         u"Samples capacity:  %s" % gf.safe_int(self.__samples_capacity),
         u"Samples length:    %s" % gf.safe_int(self.__samples_length),
     ]
     return u"\n".join(msg)
示例#5
0
 def __unicode__(self):
     msg = [
         u"File path:         %s" % self.file_path,
         u"File size (bytes): %s" % gf.safe_int(self.file_size),
         u"Audio length (s):  %s" % gf.safe_float(self.audio_length),
         u"Audio format:      %s" % self.audio_format,
         u"Audio sample rate: %s" % gf.safe_int(self.audio_sample_rate),
         u"Audio channels:    %s" % gf.safe_int(self.audio_channels),
         u"Samples capacity:  %s" % gf.safe_int(self.__samples_capacity),
         u"Samples length:    %s" % gf.safe_int(self.__samples_length),
     ]
     return u"\n".join(msg)
示例#6
0
    def read_properties(self):
        """
        Populate this object by reading
        the audio properties of the file at the given path.

        Currently this function uses
        :class:`~aeneas.ffprobewrapper.FFPROBEWrapper`
        to get the audio file properties.

        :raises: :class:`~aeneas.audiofile.AudioFileProbeError`: if the path to the ``ffprobe`` executable cannot be called
        :raises: :class:`~aeneas.audiofile.AudioFileUnsupportedFormatError`: if the audio file has a format not supported
        :raises: OSError: if the audio file cannot be read
        """
        self.log(u"Reading properties...")

        # check the file can be read
        if not gf.file_can_be_read(self.file_path):
            self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)

        # get the file size
        self.log([u"Getting file size for '%s'", self.file_path])
        self.file_size = gf.file_size(self.file_path)
        self.log([u"File size for '%s' is '%d'", self.file_path, self.file_size])

        # get the audio properties using FFPROBEWrapper
        try:
            self.log(u"Reading properties with FFPROBEWrapper...")
            properties = FFPROBEWrapper(
                rconf=self.rconf,
                logger=self.logger
            ).read_properties(self.file_path)
            self.log(u"Reading properties with FFPROBEWrapper... done")
        except FFPROBEPathError:
            self.log_exc(u"Unable to call ffprobe executable", None, True, AudioFileProbeError)
        except (FFPROBEUnsupportedFormatError, FFPROBEParsingError):
            self.log_exc(u"Audio file format not supported by ffprobe", None, True, AudioFileUnsupportedFormatError)

        # save relevant properties in results inside the audiofile object
        self.audio_length = TimeValue(properties[FFPROBEWrapper.STDOUT_DURATION])
        self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
        self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
        self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS])
        self.log([u"Stored audio_length: '%s'", self.audio_length])
        self.log([u"Stored audio_format: '%s'", self.audio_format])
        self.log([u"Stored audio_sample_rate: '%s'", self.audio_sample_rate])
        self.log([u"Stored audio_channels: '%s'", self.audio_channels])
        self.log(u"Reading properties... done")
示例#7
0
    def read_properties(self):
        """
        Populate this object by reading
        the audio properties of the file at the given path.

        Currently this function uses
        :class:`aeneas.ffprobewrapper.FFPROBEWrapper`
        to get the audio file properties.
        """

        self._log("Reading properties")

        # check the file can be read
        if self.file_path is None:
            raise AttributeError("File path is None")
        if not os.path.isfile(self.file_path):
            self._log(["File '%s' cannot be read", self.file_path],
                      Logger.CRITICAL)
            raise OSError("File cannot be read")

        # get the file size
        self._log(["Getting file size for '%s'", self.file_path])
        self.file_size = os.path.getsize(self.file_path)
        self._log(
            ["File size for '%s' is '%d'", self.file_path, self.file_size])

        # get the audio properties
        self._log("Reading properties with FFPROBEWrapper...")
        prober = FFPROBEWrapper(logger=self.logger)
        properties = prober.read_properties(self.file_path)
        self._log("Reading properties with FFPROBEWrapper... done")

        # save relevant properties in results inside the audiofile object
        self.audio_length = gf.safe_float(
            properties[FFPROBEWrapper.STDOUT_DURATION])
        self._log(["Stored audio_length: '%s'", self.audio_length])
        self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
        self._log(["Stored audio_format: '%s'", self.audio_format])
        self.audio_sample_rate = gf.safe_int(
            properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
        self._log(["Stored audio_sample_rate: '%s'", self.audio_sample_rate])
        self.audio_channels = gf.safe_int(
            properties[FFPROBEWrapper.STDOUT_CHANNELS])
        self._log(["Stored audio_channels: '%s'", self.audio_channels])
示例#8
0
    def read_properties(self):
        """
        Populate this object by reading
        the audio properties of the file at the given path.

        Currently this function uses
        :class:`aeneas.ffprobewrapper.FFPROBEWrapper`
        to get the audio file properties.
        """

        self._log("Reading properties")

        # check the file can be read
        if self.file_path is None:
            raise AttributeError("File path is None")
        if not os.path.isfile(self.file_path):
            self._log(["File '%s' cannot be read", self.file_path], Logger.CRITICAL)
            raise OSError("File cannot be read")

        # get the file size
        self._log(["Getting file size for '%s'", self.file_path])
        self.file_size = os.path.getsize(self.file_path)
        self._log(["File size for '%s' is '%d'", self.file_path, self.file_size])

        # get the audio properties
        self._log("Reading properties with FFPROBEWrapper...")
        prober = FFPROBEWrapper(logger=self.logger)
        properties = prober.read_properties(self.file_path)
        self._log("Reading properties with FFPROBEWrapper... done")

        # save relevant properties in results inside the audiofile object
        self.audio_length = gf.safe_float(properties[FFPROBEWrapper.STDOUT_DURATION])
        self._log(["Stored audio_length: '%s'", self.audio_length])
        self.audio_format = properties[FFPROBEWrapper.STDOUT_CODEC_NAME]
        self._log(["Stored audio_format: '%s'", self.audio_format])
        self.audio_sample_rate = gf.safe_int(properties[FFPROBEWrapper.STDOUT_SAMPLE_RATE])
        self._log(["Stored audio_sample_rate: '%s'", self.audio_sample_rate])
        self.audio_channels = gf.safe_int(properties[FFPROBEWrapper.STDOUT_CHANNELS])
        self._log(["Stored audio_channels: '%s'", self.audio_channels])
示例#9
0
 def test_safe_int(self):
     tests = [
         ["3.14", 1, 3],
         ["3.14 ", 1, 3],
         [" 3.14", 1, 3],
         [" 3.14 ", 1, 3],
         ["3.14f", 1, 1],
         ["0x3.14", 1, 1],
         ["3", 1, 3],
         ["3 ", 1, 3],
         [" 3", 1, 3],
         [" 3 ", 1, 3],
         ["3f", 1, 1],
         ["0x3", 1, 1],
         ["", 1, 1],
         ["foo", 1, 1],
         [None, 1, 1],
     ]
     for test in tests:
         self.assertEqual(gf.safe_int(test[0], test[1]), test[2])
示例#10
0
 def test_safe_int(self):
     tests = [
         ["3.14", 1, 3],
         ["3.14 ", 1, 3],
         [" 3.14", 1, 3],
         [" 3.14 ", 1, 3],
         ["3.14f", 1, 1],
         ["0x3.14", 1, 1],
         ["3", 1, 3],
         ["3 ", 1, 3],
         [" 3", 1, 3],
         [" 3 ", 1, 3],
         ["3f", 1, 1],
         ["0x3", 1, 1],
         ["", 1, 1],
         ["foo", 1, 1],
         [None, 1, 1],
     ]
     for test in tests:
         self.assertEqual(gf.safe_int(test[0], test[1]), test[2])
 def test_safe_int(self):
     tests = [
         ("3.14", 1, 3),
         ("3.14 ", 1, 3),
         (" 3.14", 1, 3),
         (" 3.14 ", 1, 3),
         ("3.14f", 1, 1),
         ("0x3.14", 1, 1),
         ("3", 1, 3),
         ("3 ", 1, 3),
         (" 3", 1, 3),
         (" 3 ", 1, 3),
         ("3f", 1, 1),
         ("0x3", 1, 1),
         ("", 1, 1),
         ("foo", 1, 1),
         (None, 1, 1),
     ]
     for test in tests:
         self.assertEqual(gf.safe_int(test[0], test[1]), test[2])
示例#12
0
 def test_safe_int(self):
     tests = [
         ("3.14", 1, 3),
         ("3.14 ", 1, 3),
         (" 3.14", 1, 3),
         (" 3.14 ", 1, 3),
         ("3.14f", 1, 1),
         ("0x3.14", 1, 1),
         ("3", 1, 3),
         ("3 ", 1, 3),
         (" 3", 1, 3),
         (" 3 ", 1, 3),
         ("3f", 1, 1),
         ("0x3", 1, 1),
         ("", 1, 1),
         ("foo", 1, 1),
         (None, 1, 1),
     ]
     for test in tests:
         self.assertEqual(gf.safe_int(test[0], test[1]), test[2])
示例#13
0
文件: tree.py 项目: danielbair/aeneas
 def __unicode__(self):
     return u"%s (l: %s, c: %s)" % (self.value, gf.safe_int(self.level), gf.safe_int(len(self)))
示例#14
0
    def perform_command(self):
        """
        Perform command and return the appropriate exit code.

        :rtype: int
        """
        if len(self.actual_arguments) < 2:
            return self.print_help()
        source_url = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        download = not self.has_option("--list")
        # largest_audio = True by default or if explicitly given
        if self.has_option("--largest-audio"):
            largest_audio = True
        else:
            largest_audio = not self.has_option("--smallest-audio")
        preferred_format = self.has_option_with_value("--format")
        preferred_index = gf.safe_int(self.has_option_with_value("--index"), None)

        try:
            if download:
                self.print_info(u"Downloading audio stream from '%s' ..." % source_url)
                downloader = Downloader(logger=self.logger)
                result = downloader.audio_from_youtube(
                    source_url,
                    download=download,
                    output_file_path=output_file_path,
                    preferred_index=preferred_index,
                    largest_audio=largest_audio,
                    preferred_format=preferred_format
                )
                self.print_info(u"Downloading audio stream from '%s' ... done" % source_url)
                self.print_success(u"Downloaded file '%s'" % result)
            else:
                self.print_info(u"Downloading stream info from '%s' ..." % source_url)
                downloader = Downloader(logger=self.logger)
                result = downloader.audio_from_youtube(
                    source_url,
                    download=False
                )
                self.print_info(u"Downloading stream info from '%s' ... done" % source_url)
                msg = []
                msg.append(u"%s\t%s\t%s\t%s" % ("Index", "Format", "Bitrate", "Size"))
                i = 0
                for audio in result:
                    ext = audio.extension
                    bitrate = audio.bitrate
                    size = gf.human_readable_number(audio.get_filesize())
                    msg.append(u"%d\t%s\t%s\t%s" % (i, ext, bitrate, size))
                    i += 1
                self.print_generic(u"Available audio streams:")
                self.print_generic(u"\n".join(msg))
            return self.NO_ERROR_EXIT_CODE
        except ImportError:
            self.print_no_pafy_error()
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while downloading audio from YouTube:")
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE
示例#15
0
 def test_safe_int_06(self):
     default = 1
     expected = 1
     value = "3f"
     result = safe_int(value, default)
     self.assertEqual(result, expected)
示例#16
0
    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":
            text = gf.safe_unicode(self.actual_arguments[1])
        elif text_format in TextFileFormat.ALLOWED_VALUES:
            text = self.actual_arguments[1]
            if not self.check_input_file(text):
                return self.ERROR_EXIT_CODE
        else:
            return self.print_help()

        l1_id_regex = self.has_option_with_value(u"--l1-id-regex")
        l2_id_regex = self.has_option_with_value(u"--l2-id-regex")
        l3_id_regex = self.has_option_with_value(u"--l3-id-regex")
        id_regex = self.has_option_with_value(u"--id-regex")
        class_regex = self.has_option_with_value(u"--class-regex")
        sort = self.has_option_with_value(u"--sort")
        backwards = self.has_option([u"-b", u"--backwards"])
        quit_after = gf.safe_float(self.has_option_with_value(u"--quit-after"), None)
        start_fragment = gf.safe_int(self.has_option_with_value(u"--start"), None)
        end_fragment = gf.safe_int(self.has_option_with_value(u"--end"), None)
        parameters = {
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: l1_id_regex,
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: l2_id_regex,
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: l3_id_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: class_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: id_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: sort,
        }
        if (text_format == TextFileFormat.MUNPARSED) and ((l1_id_regex is None) or (l2_id_regex is None) or (l3_id_regex is None)):
            self.print_error(u"You must specify --l1-id-regex and --l2-id-regex and --l3-id-regex for munparsed format")
            return self.ERROR_EXIT_CODE
        if (text_format == TextFileFormat.UNPARSED) and (id_regex is None) and (class_regex is None):
            self.print_error(u"You must specify --id-regex and/or --class-regex for unparsed format")
            return self.ERROR_EXIT_CODE

        language = gf.safe_unicode(self.actual_arguments[2])

        output_file_path = self.actual_arguments[3]
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        text_file = self.get_text_file(text_format, text, parameters)
        if text_file is None:
            self.print_error(u"Unable to build a TextFile from the given parameters")
            return self.ERROR_EXIT_CODE
        elif len(text_file) == 0:
            self.print_error(u"No text fragments found")
            return self.ERROR_EXIT_CODE
        text_file.set_language(language)
        self.print_info(u"Read input text with %d fragments" % (len(text_file)))
        if start_fragment is not None:
            self.print_info(u"Slicing from index %d" % (start_fragment))
        if end_fragment is not None:
            self.print_info(u"Slicing to index %d" % (end_fragment))
        text_slice = text_file.get_slice(start_fragment, end_fragment)
        self.print_info(u"Synthesizing %d fragments" % (len(text_slice)))

        if quit_after is not None:
            self.print_info(u"Stop synthesizing upon reaching %.3f seconds" % (quit_after))

        try:
            synt = Synthesizer(rconf=self.rconf, logger=self.logger)
            synt.synthesize(
                text_slice,
                output_file_path,
                quit_after=quit_after,
                backwards=backwards
            )
            self.print_success(u"Created file '%s'" % output_file_path)
            synt.clear_cache()
            return self.NO_ERROR_EXIT_CODE
        except ImportError as exc:
            tts = self.rconf[RuntimeConfiguration.TTS]
            if tts == Synthesizer.AWS:
                self.print_error(u"You need to install Python module boto3 to use the AWS Polly TTS API wrapper. Run:")
                self.print_error(u"$ pip install boto3")
                self.print_error(u"or, to install for all users:")
                self.print_error(u"$ sudo pip install boto3")
            elif tts == Synthesizer.NUANCE:
                self.print_error(u"You need to install Python module requests to use the Nuance TTS API wrapper. Run:")
                self.print_error(u"$ pip install requests")
                self.print_error(u"or, to install for all users:")
                self.print_error(u"$ sudo pip install requests")
            else:
                self.print_error(u"An unexpected error occurred while synthesizing text:")
                self.print_error(u"%s" % exc)
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while synthesizing text:")
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE
示例#17
0
    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":
            text = gf.safe_unicode(self.actual_arguments[1])
        elif text_format in TextFileFormat.ALLOWED_VALUES:
            text = self.actual_arguments[1]
            if not self.check_input_file(text):
                return self.ERROR_EXIT_CODE
        else:
            return self.print_help()

        l1_id_regex = self.has_option_with_value(u"--l1-id-regex")
        l2_id_regex = self.has_option_with_value(u"--l2-id-regex")
        l3_id_regex = self.has_option_with_value(u"--l3-id-regex")
        id_regex = self.has_option_with_value(u"--id-regex")
        class_regex = self.has_option_with_value(u"--class-regex")
        sort = self.has_option_with_value(u"--sort")
        backwards = self.has_option([u"-b", u"--backwards"])
        quit_after = gf.safe_float(self.has_option_with_value(u"--quit-after"),
                                   None)
        start_fragment = gf.safe_int(self.has_option_with_value(u"--start"),
                                     None)
        end_fragment = gf.safe_int(self.has_option_with_value(u"--end"), None)
        parameters = {
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX: l1_id_regex,
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX: l2_id_regex,
            gc.PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX: l3_id_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX: class_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX: id_regex,
            gc.PPN_TASK_IS_TEXT_UNPARSED_ID_SORT: sort,
        }
        if (text_format == TextFileFormat.MUNPARSED) and (
            (l1_id_regex is None) or (l2_id_regex is None) or
            (l3_id_regex is None)):
            self.print_error(
                u"You must specify --l1-id-regex and --l2-id-regex and --l3-id-regex for munparsed format"
            )
            return self.ERROR_EXIT_CODE
        if (text_format == TextFileFormat.UNPARSED) and (
                id_regex is None) and (class_regex is None):
            self.print_error(
                u"You must specify --id-regex and/or --class-regex for unparsed format"
            )
            return self.ERROR_EXIT_CODE

        language = gf.safe_unicode(self.actual_arguments[2])

        output_file_path = self.actual_arguments[3]
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        text_file = self.get_text_file(text_format, text, parameters)
        if text_file is None:
            self.print_error(
                u"Unable to build a TextFile from the given parameters")
            return self.ERROR_EXIT_CODE
        elif len(text_file) == 0:
            self.print_error(u"No text fragments found")
            return self.ERROR_EXIT_CODE
        text_file.set_language(language)
        self.print_info(u"Read input text with %d fragments" %
                        (len(text_file)))
        if start_fragment is not None:
            self.print_info(u"Slicing from index %d" % (start_fragment))
        if end_fragment is not None:
            self.print_info(u"Slicing to index %d" % (end_fragment))
        text_slice = text_file.get_slice(start_fragment, end_fragment)
        self.print_info(u"Synthesizing %d fragments" % (len(text_slice)))

        if quit_after is not None:
            self.print_info(u"Stop synthesizing upon reaching %.3f seconds" %
                            (quit_after))

        try:
            synt = Synthesizer(rconf=self.rconf, logger=self.logger)
            synt.synthesize(text_slice,
                            output_file_path,
                            quit_after=quit_after,
                            backwards=backwards)
            self.print_success(u"Created file '%s'" % output_file_path)
            synt.clear_cache()
            return self.NO_ERROR_EXIT_CODE
        except ImportError as exc:
            tts = self.rconf[RuntimeConfiguration.TTS]
            if tts == Synthesizer.AWS:
                self.print_error(
                    u"You need to install Python module boto3 to use the AWS Polly TTS API wrapper. Run:"
                )
                self.print_error(u"$ pip install boto3")
                self.print_error(u"or, to install for all users:")
                self.print_error(u"$ sudo pip install boto3")
            elif tts == Synthesizer.NUANCE:
                self.print_error(
                    u"You need to install Python module requests to use the Nuance TTS API wrapper. Run:"
                )
                self.print_error(u"$ pip install requests")
                self.print_error(u"or, to install for all users:")
                self.print_error(u"$ sudo pip install requests")
            else:
                self.print_error(
                    u"An unexpected error occurred while synthesizing text:")
                self.print_error(u"%s" % exc)
        except Exception as exc:
            self.print_error(
                u"An unexpected error occurred while synthesizing text:")
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE
示例#18
0
    def perform_command(self):
        """
        Perform command and return the appropriate exit code.

        :rtype: int
        """
        if len(self.actual_arguments) < 2:
            return self.print_help()
        input_file_path = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        fast = self.has_option("--fast")
        fragment_text = self.has_option("--text")
        h_zoom = gf.safe_int(self.has_option_with_value("--hzoom"), 5)
        label = self.has_option_with_value("--label")
        time_step = gf.safe_int(self.has_option_with_value("--time-step"), 0)
        v_zoom = gf.safe_int(self.has_option_with_value("--vzoom"), 30)

        labels = not self.has_option("--no-labels")
        begin_times = not self.has_option("--no-begin-times")
        end_times = not self.has_option("--no-end-times")
        begin_guides = not self.has_option("--no-begin-guides")
        end_guides = not self.has_option("--no-end-guides")

        try:
            # import or ImportError
            from aeneas.plotter import PlotLabelset
            from aeneas.plotter import PlotTimeScale
            from aeneas.plotter import PlotWaveform
            from aeneas.plotter import Plotter

            # create plotter object
            self.print_info(u"Plotting to file...")
            plotter = Plotter(rconf=self.rconf, logger=self.logger)

            # add waveform
            afm = AudioFile(input_file_path, rconf=self.rconf, logger=self.logger)
            afm.read_samples_from_file()
            plotter.add_waveform(PlotWaveform(afm, label=label, fast=fast, rconf=self.rconf, logger=self.logger))

            # add time scale, if requested
            if time_step > 0:
                plotter.add_timescale(PlotTimeScale(afm.audio_length, time_step=time_step, rconf=self.rconf, logger=self.logger))

            # add labelsets, if any
            for i in range(len(self.actual_arguments)):
                if (self.actual_arguments[i] == "-i") and (i + 1 < len(self.actual_arguments)):
                    label_file_path = self.actual_arguments[i+1]
                    extension = gf.file_extension(label_file_path)
                    if extension == "vad":
                        labelset = self._read_syncmap_file(label_file_path, SyncMapFormat.TSV, False)
                        ls = PlotLabelset(labelset, parameters=None, rconf=self.rconf, logger=self.logger)
                        ls.parameters["labels"] = False
                        ls.parameters["begin_time"] = begin_times
                        ls.parameters["end_time"] = end_times
                        ls.parameters["begin_guide"] = begin_guides
                        ls.parameters["end_guide"] = end_guides
                        plotter.add_labelset(ls)
                    if extension in SyncMapFormat.ALLOWED_VALUES:
                        labelset = self._read_syncmap_file(label_file_path, extension, fragment_text)
                        ls = PlotLabelset(labelset, parameters=None, rconf=self.rconf, logger=self.logger)
                        ls.parameters["labels"] = labels
                        ls.parameters["begin_time"] = begin_times
                        ls.parameters["end_time"] = end_times
                        ls.parameters["begin_guide"] = begin_guides
                        ls.parameters["end_guide"] = end_guides
                        plotter.add_labelset(ls)

            # output to file
            plotter.draw_png(output_file_path, h_zoom=h_zoom, v_zoom=v_zoom)
            self.print_info(u"Plotting to file... done")
            self.print_success(u"Created file '%s'" % output_file_path)
            return self.NO_ERROR_EXIT_CODE
        except ImportError:
            self.print_error(u"You need to install Python module Pillow to output image to file. Run:")
            self.print_error(u"$ pip install Pillow")
            self.print_error(u"or, to install for all users:")
            self.print_error(u"$ sudo pip install Pillow")
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while generating the image file:")
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE
示例#19
0
 def __unicode__(self):
     return u"%s (l: %s, c: %s)" % (self.value, gf.safe_int(
         self.level), gf.safe_int(len(self)))
示例#20
0
 def test_safe_int_04(self):
     default = 1
     expected = 3
     value = " 3.14 "
     result = safe_int(value, default)
     self.assertEqual(result, expected)
示例#21
0
    def perform_command(self):
        """
        Perform command and return the appropriate exit code.

        :rtype: int
        """
        if len(self.actual_arguments) < 2:
            return self.print_help()
        input_file_path = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        if not self.check_output_file(output_file_path):
            return self.ERROR_EXIT_CODE

        fast = self.has_option("--fast")
        fragment_text = self.has_option("--text")
        h_zoom = gf.safe_int(self.has_option_with_value("--hzoom"), 5)
        label = self.has_option_with_value("--label")
        time_step = gf.safe_int(self.has_option_with_value("--time-step"), 0)
        v_zoom = gf.safe_int(self.has_option_with_value("--vzoom"), 30)

        labels = not self.has_option("--no-labels")
        begin_times = not self.has_option("--no-begin-times")
        end_times = not self.has_option("--no-end-times")
        begin_guides = not self.has_option("--no-begin-guides")
        end_guides = not self.has_option("--no-end-guides")

        try:
            # import or ImportError
            from aeneas.plotter import PlotLabelset
            from aeneas.plotter import PlotTimeScale
            from aeneas.plotter import PlotWaveform
            from aeneas.plotter import Plotter

            # create plotter object
            self.print_info(u"Plotting to file...")
            plotter = Plotter(rconf=self.rconf, logger=self.logger)

            # add waveform
            afm = AudioFile(input_file_path,
                            rconf=self.rconf,
                            logger=self.logger)
            afm.read_samples_from_file()
            plotter.add_waveform(
                PlotWaveform(afm,
                             label=label,
                             fast=fast,
                             rconf=self.rconf,
                             logger=self.logger))

            # add time scale, if requested
            if time_step > 0:
                plotter.add_timescale(
                    PlotTimeScale(afm.audio_length,
                                  time_step=time_step,
                                  rconf=self.rconf,
                                  logger=self.logger))

            # add labelsets, if any
            for i in range(len(self.actual_arguments)):
                if (self.actual_arguments[i]
                        == "-i") and (i + 1 < len(self.actual_arguments)):
                    label_file_path = self.actual_arguments[i + 1]
                    extension = gf.file_extension(label_file_path)
                    if extension == "vad":
                        labelset = self._read_syncmap_file(
                            label_file_path, SyncMapFormat.TSV, False)
                        ls = PlotLabelset(labelset,
                                          parameters=None,
                                          rconf=self.rconf,
                                          logger=self.logger)
                        ls.parameters["labels"] = False
                        ls.parameters["begin_time"] = begin_times
                        ls.parameters["end_time"] = end_times
                        ls.parameters["begin_guide"] = begin_guides
                        ls.parameters["end_guide"] = end_guides
                        plotter.add_labelset(ls)
                    if extension in SyncMapFormat.ALLOWED_VALUES:
                        labelset = self._read_syncmap_file(
                            label_file_path, extension, fragment_text)
                        ls = PlotLabelset(labelset,
                                          parameters=None,
                                          rconf=self.rconf,
                                          logger=self.logger)
                        ls.parameters["labels"] = labels
                        ls.parameters["begin_time"] = begin_times
                        ls.parameters["end_time"] = end_times
                        ls.parameters["begin_guide"] = begin_guides
                        ls.parameters["end_guide"] = end_guides
                        plotter.add_labelset(ls)

            # output to file
            plotter.draw_png(output_file_path, h_zoom=h_zoom, v_zoom=v_zoom)
            self.print_info(u"Plotting to file... done")
            self.print_success(u"Created file '%s'" % output_file_path)
            return self.NO_ERROR_EXIT_CODE
        except ImportError:
            self.print_error(
                u"You need to install Python module Pillow to output image to file. Run:"
            )
            self.print_error(u"$ pip install Pillow")
            self.print_error(u"or, to install for all users:")
            self.print_error(u"$ sudo pip install Pillow")
        except Exception as exc:
            self.print_error(
                u"An unexpected error occurred while generating the image file:"
            )
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE
示例#22
0
    def perform_command(self):
        """
        Perform command and return the appropriate exit code.

        :rtype: int
        """
        if len(self.actual_arguments) < 2:
            return self.print_help()
        source_url = self.actual_arguments[0]
        output_file_path = self.actual_arguments[1]

        download = not self.has_option("--list")
        # largest_audio = True by default or if explicitly given
        if self.has_option("--largest-audio"):
            largest_audio = True
        else:
            largest_audio = not self.has_option("--smallest-audio")
        preferred_format = self.has_option_with_value("--format")
        preferred_index = gf.safe_int(self.has_option_with_value("--index"), None)

        try:
            if download:
                self.print_info(u"Downloading audio stream from '%s' ..." % source_url)
                downloader = Downloader(logger=self.logger)
                result = downloader.audio_from_youtube(
                    source_url,
                    download=download,
                    output_file_path=output_file_path,
                    preferred_index=preferred_index,
                    largest_audio=largest_audio,
                    preferred_format=preferred_format
                )
                self.print_info(u"Downloading audio stream from '%s' ... done" % source_url)
                self.print_success(u"Downloaded file '%s'" % result)
            else:
                self.print_info(u"Downloading stream info from '%s' ..." % source_url)
                downloader = Downloader(logger=self.logger)
                result = downloader.audio_from_youtube(
                    source_url,
                    download=False
                )
                self.print_info(u"Downloading stream info from '%s' ... done" % source_url)
                msg = []
                msg.append(u"%s\t%s\t%s\t%s" % ("Index", "Format", "Bitrate", "Size"))
                i = 0
                for audio in result:
                    ext = audio.extension
                    bitrate = audio.bitrate
                    size = gf.human_readable_number(audio.get_filesize())
                    msg.append(u"%d\t%s\t%s\t%s" % (i, ext, bitrate, size))
                    i += 1
                self.print_generic(u"Available audio streams:")
                self.print_generic(u"\n".join(msg))
            return self.NO_ERROR_EXIT_CODE
        except ImportError:
            self.print_no_pafy_error()
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while downloading audio from YouTube:")
            self.print_error(u"%s" % exc)

        return self.ERROR_EXIT_CODE