예제 #1
0
 def _read_syncmap_file(self, path, extension, text=False):
     """ Read labels from a SyncMap file """
     syncmap = SyncMap(logger=self.logger)
     syncmap.read(extension, path, parameters=None)
     if text:
         return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragments]
     return [(f.begin, f.end, f.text_fragment.identifier) for f in syncmap.fragments]
예제 #2
0
파일: executetask.py 프로젝트: cbeer/aeneas
    def _create_syncmap(self, text_map):
        """
        Create a sync map out of the provided interval map,
        and store it in the task object.

        Return a success bool flag.
        """
        self._log("Creating SyncMap")
        self._log("Number of fragments: %d" % len(text_map))
        if len(text_map) != len(self.task.text_file.fragments):
            return False
        try:
            sync_map = SyncMap()
            i = 0
            head = 0
            if self.task.configuration.is_audio_file_head_length != None:
                head = gf.safe_float(self.task.configuration.is_audio_file_head_length, 0)
            for fragment in self.task.text_file.fragments:
                start = head + text_map[i][0]
                end = head + text_map[i][1]
                sync_map_frag = SyncMapFragment(fragment, start, end)
                sync_map.append(sync_map_frag)
                i += 1
            self.task.sync_map = sync_map
            return True
        except:
            return False
예제 #3
0
def main():
    """ Entry point """
    if len(sys.argv) < 3:
        usage()
        return
    input_file_path = sys.argv[1]
    output_file_path = sys.argv[2]
    parameters = {}
    for i in range(3, len(sys.argv)):
        args = sys.argv[i].split("=")
        if len(args) == 2:
            key, value = args
            if key in [
                    gc.PPN_SYNCMAP_LANGUAGE,
                    gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF,
                    gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF,
                    "input_format",
                    "output_format",
                    "text_file"
            ]:
                parameters[key] = value

    if "input_format" in parameters:
        input_sm_format = parameters["input_format"]
    else:
        input_sm_format = gf.file_extension(input_file_path)
    if input_sm_format not in SyncMapFormat.ALLOWED_VALUES:
        print "[ERRO] Input sync map format '%s' is not allowed" % (input_sm_format)
        print "[INFO] Allowed formats: %s" % (" ".join(SyncMapFormat.ALLOWED_VALUES))
        return

    if "output_format" in parameters:
        output_sm_format = parameters["output_format"]
    else:
        output_sm_format = gf.file_extension(output_file_path)
    if output_sm_format not in SyncMapFormat.ALLOWED_VALUES:
        print "[ERRO] Output sync map format '%s' is not allowed" % (output_sm_format)
        print "[INFO] Allowed sync map formats: %s" % (" ".join(SyncMapFormat.ALLOWED_VALUES))
        return

    try:
        print "[INFO] Reading sync map in %s format from file %s ..." % (input_sm_format, input_file_path)
        syncmap = SyncMap()
        result = syncmap.read(input_sm_format, input_file_path, parameters)
        if not result:
            print "[ERRO] Error while reading sync map"
            return
        print "[INFO] Reading sync map in %s format from file %s ... done" % (input_sm_format, input_file_path)
        print "[INFO] Read %s sync map fragments" % (len(syncmap))
        print "[INFO] Writing sync map in %s format to file %s ..." % (output_sm_format, output_file_path)
        result = syncmap.write(output_sm_format, output_file_path, parameters)
        if not result:
            print "[ERRO] Error while writing sync map (forgot required arguments?)"
            return
        print "[INFO] Writing sync map in %s format to file %s ... done" % (output_sm_format, output_file_path)
    except Exception as e:
        print "[ERRO] Uncaught exception %s" % (str(e))
        return
예제 #4
0
 def _read_syncmap_file(self, path, extension, text=False):
     """ Read labels from a SyncMap file """
     syncmap = SyncMap(logger=self.logger)
     syncmap.read(extension, path, parameters=None)
     if text:
         return [(f.begin, f.end, u" ".join(f.text_fragment.lines))
                 for f in syncmap.fragments]
     return [(f.begin, f.end, f.text_fragment.identifier)
             for f in syncmap.fragments]
예제 #5
0
 def read(self, fmt, multiline=False, utf8=False, parameters=PARAMETERS):
     syn = SyncMap()
     if multiline and utf8:
         path = "res/syncmaps/sonnet001_mu."
     elif multiline:
         path = "res/syncmaps/sonnet001_m."
     elif utf8:
         path = "res/syncmaps/sonnet001_u."
     else:
         path = "res/syncmaps/sonnet001."
     syn.read(fmt, gf.absolute_path(path + fmt, __file__), parameters=parameters)
     return syn
예제 #6
0
 def read(self, fmt, multiline=False, utf8=False, parameters=PARAMETERS):
     syn = SyncMap()
     if multiline and unicode:
         path = "res/syncmaps/sonnet001_mu."
     elif multiline:
         path = "res/syncmaps/sonnet001_m."
     elif utf8:
         path = "res/syncmaps/sonnet001_u."
     else:
         path = "res/syncmaps/sonnet001."
     result = syn.read(fmt, get_abs_path(path + fmt), parameters=parameters)
     return (syn, result)
예제 #7
0
 def load(self, path=None, lines=None):
     syn = SyncMap()
     if path == None:
         path = "res/inputtext/sonnet_parsed.txt"
         lines = 15
     tfl = TextFile(get_abs_path(path), TextFileFormat.PARSED)
     self.assertEqual(len(tfl), lines)
     i = 0
     for fragment in tfl.fragments:
         # dummy time values!
         syn_frag = SyncMapFragment(fragment, i, i + 1)
         syn.append(syn_frag)
         i += 1
     return syn
 def read(self, fmt, multiline=False, utf8=False, parameters=PARAMETERS):
     syn = SyncMap()
     if multiline and utf8:
         path = "res/syncmaps/sonnet001_mu."
     elif multiline:
         path = "res/syncmaps/sonnet001_m."
     elif utf8:
         path = "res/syncmaps/sonnet001_u."
     else:
         path = "res/syncmaps/sonnet001."
     syn.read(fmt,
              gf.absolute_path(path + fmt, __file__),
              parameters=parameters)
     return syn
예제 #9
0
 def test_is_single_level_true_not_empty(self):
     smf = SyncMapFragment()
     child = Tree(value=smf)
     tree = Tree()
     tree.add_child(child)
     syn = SyncMap(tree=tree)
     self.assertTrue(syn.is_single_level)
예제 #10
0
 def test_fragments_tree_not_empty(self):
     smf = SyncMapFragment()
     child = Tree(value=smf)
     tree = Tree()
     tree.add_child(child)
     syn = SyncMap(tree=tree)
     self.assertEqual(len(syn.fragments_tree), 1)
예제 #11
0
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment(u"f001", Language.ENG, [u"Fragment 1"])
     sync_map.add_fragment(SyncMapFragment(frag, 0, 12.345))
     frag = TextFragment(u"f002", Language.ENG, [u"Fragment 2"])
     sync_map.add_fragment(SyncMapFragment(frag, 12.345, 23.456))
     frag = TextFragment(u"f003", Language.ENG, [u"Fragment 3"])
     sync_map.add_fragment(SyncMapFragment(frag, 23.456, 34.567))
     return sync_map
예제 #12
0
    def _create_syncmap(self, tree):
        """
        Return a sync map corresponding to the provided text file and time map.

        :param tree: a Tree of SyncMapFragments
        :type  tree: :class:`~aeneas.tree.Tree`
        :rtype: :class:`~aeneas.syncmap.SyncMap`
        """
        self.log(
            [u"Fragments in time map (including HEAD/TAIL): %d",
             len(tree)])
        head_tail_format = self.task.configuration["o_h_t_format"]
        self.log([u"Head/tail format: %s", str(head_tail_format)])

        children = tree.vchildren
        head = children[0]
        first = children[1]
        last = children[-2]
        tail = children[-1]

        # remove HEAD fragment if needed
        if head_tail_format != SyncMapHeadTailFormat.ADD:
            tree.remove_child(0)
            self.log(u"Removed HEAD")

        # stretch first and last fragment timings if needed
        if head_tail_format == SyncMapHeadTailFormat.STRETCH:
            self.log([
                u"Stretched first.begin: %.3f => %.3f (head)", first.begin,
                head.begin
            ])
            self.log([
                u"Stretched last.end:    %.3f => %.3f (tail)", last.end,
                tail.end
            ])
            first.begin = head.begin
            last.end = tail.end

        # remove TAIL fragment if needed
        if head_tail_format != SyncMapHeadTailFormat.ADD:
            tree.remove_child(-1)
            self.log(u"Removed TAIL")

        # return sync map
        sync_map = SyncMap()
        sync_map.fragments_tree = tree
        return sync_map
예제 #13
0
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment("f001", Language.EN, "Fragment 1")
     sync_map.append(SyncMapFragment(frag, 0, 12.345))
     frag = TextFragment("f002", Language.EN, "Fragment 2")
     sync_map.append(SyncMapFragment(frag, 12.345, 23.456))
     frag = TextFragment("f003", Language.EN, "Fragment 3")
     sync_map.append(SyncMapFragment(frag, 23.456, 34.567))
     return sync_map
예제 #14
0
 def test_is_single_level_false(self):
     smf2 = SyncMapFragment()
     child2 = Tree(value=smf2)
     smf = SyncMapFragment()
     child = Tree(value=smf)
     child.add_child(child2)
     tree = Tree()
     tree.add_child(child)
     syn = SyncMap(tree=tree)
     self.assertFalse(syn.is_single_level)
예제 #15
0
파일: test_task.py 프로젝트: cbeer/aeneas
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment("f001", Language.EN, "Fragment 1")
     sync_map.append(SyncMapFragment(frag, 0, 12.345))
     frag = TextFragment("f002", Language.EN, "Fragment 2")
     sync_map.append(SyncMapFragment(frag, 12.345, 23.456))
     frag = TextFragment("f003", Language.EN, "Fragment 3")
     sync_map.append(SyncMapFragment(frag, 23.456, 34.567))
     return sync_map
예제 #16
0
파일: test_task.py 프로젝트: ptrwtts/aeneas
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment(u"f001", Language.ENG, [u"Fragment 1"])
     sync_map.add_fragment(SyncMapFragment(frag, 0, 12.345))
     frag = TextFragment(u"f002", Language.ENG, [u"Fragment 2"])
     sync_map.add_fragment(SyncMapFragment(frag, 12.345, 23.456))
     frag = TextFragment(u"f003", Language.ENG, [u"Fragment 3"])
     sync_map.add_fragment(SyncMapFragment(frag, 23.456, 34.567))
     return sync_map
예제 #17
0
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment(u"f001", Language.ENG, [u"Fragment 1"])
     sync_map.add_fragment(SyncMapFragment(text_fragment=frag, begin=TimeValue("0.000"), end=TimeValue("12.345")))
     frag = TextFragment(u"f002", Language.ENG, [u"Fragment 2"])
     sync_map.add_fragment(SyncMapFragment(text_fragment=frag, begin=TimeValue("12.345"), end=TimeValue("23.456")))
     frag = TextFragment(u"f003", Language.ENG, [u"Fragment 3"])
     sync_map.add_fragment(SyncMapFragment(text_fragment=frag, begin=TimeValue("23.456"), end=TimeValue("34.567")))
     return sync_map
예제 #18
0
    def _create_syncmap(self, tree):
        """
        Return a sync map corresponding to the provided text file and time map.

        :param tree: a Tree of SyncMapFragments
        :type  tree: :class:`~aeneas.tree.Tree`
        :rtype: :class:`~aeneas.syncmap.SyncMap`
        """
        self.log([u"Fragments in time map (including HEAD/TAIL): %d", len(tree)])
        head_tail_format = self.task.configuration["o_h_t_format"]
        self.log([u"Head/tail format: %s", str(head_tail_format)])

        children = tree.vchildren
        head = children[0]
        first = children[1]
        last = children[-2]
        tail = children[-1]

        # remove HEAD fragment if needed
        if head_tail_format != SyncMapHeadTailFormat.ADD:
            tree.remove_child(0)
            self.log(u"Removed HEAD")

        # stretch first and last fragment timings if needed
        if head_tail_format == SyncMapHeadTailFormat.STRETCH:
            self.log([u"Stretched first.begin: %.3f => %.3f (head)", first.begin, head.begin])
            self.log([u"Stretched last.end:    %.3f => %.3f (tail)", last.end, tail.end])
            first.begin = head.begin
            last.end = tail.end

        # remove TAIL fragment if needed
        if head_tail_format != SyncMapHeadTailFormat.ADD:
            tree.remove_child(-1)
            self.log(u"Removed TAIL")

        # return sync map
        sync_map = SyncMap()
        sync_map.fragments_tree = tree
        return sync_map
예제 #19
0
 def _create_sync_map(self, sync_root):
     """
     If requested, check that the computed sync map is consistent.
     Then, add it to the Task.
     """
     sync_map = SyncMap(tree=sync_root, rconf=self.rconf, logger=self.logger)
     if self.rconf.safety_checks:
         self.log(u"Running sanity check on computed sync map...")
         if not sync_map.leaves_are_consistent:
             self._step_failure(ValueError(u"The computed sync map contains inconsistent fragments"))
         self.log(u"Running sanity check on computed sync map... passed")
     else:
         self.log(u"Not running sanity check on computed sync map")
     self.task.sync_map = sync_map
예제 #20
0
 def dummy_sync_map(self):
     sync_map = SyncMap()
     frag = TextFragment(u"f001", Language.ENG, [u"Fragment 1"])
     sync_map.add_fragment(
         SyncMapFragment(text_fragment=frag,
                         begin=TimeValue("0.000"),
                         end=TimeValue("12.345")))
     frag = TextFragment(u"f002", Language.ENG, [u"Fragment 2"])
     sync_map.add_fragment(
         SyncMapFragment(text_fragment=frag,
                         begin=TimeValue("12.345"),
                         end=TimeValue("23.456")))
     frag = TextFragment(u"f003", Language.ENG, [u"Fragment 3"])
     sync_map.add_fragment(
         SyncMapFragment(text_fragment=frag,
                         begin=TimeValue("23.456"),
                         end=TimeValue("34.567")))
     return sync_map
예제 #21
0
 def test_has_zero_length_leaves(self):
     params = [
         ([("0.000", "0.000"), ("0.000", "0.000")], True),
         ([("0.000", "0.000"), ("0.000", "1.000")], True),
         ([("0.000", "1.000"), ("1.000", "1.000")], True),
         ([("0.000", "1.000"), ("1.000", "2.000")], False),
         ([("0.000", "0.000"), ("1.000", "1.000")], True),
         ([("0.000", "0.000"), ("1.000", "2.000")], True),
         ([("0.000", "1.000"), ("2.000", "2.000")], True),
         ([("0.000", "1.000"), ("2.000", "3.000")], False),
     ]
     for l, exp in params:
         tree = Tree()
         for b, e in l:
             interval = TimeInterval(begin=TimeValue(b), end=TimeValue(e))
             smf = SyncMapFragment(interval=interval)
             child = Tree(value=smf)
             tree.add_child(child, as_last=True)
         syn = SyncMap(tree=tree)
         self.assertEqual(syn.has_zero_length_leaves, exp)
예제 #22
0
 def test_leaves_are_consistent(self):
     params = [
         ([("0.000", "0.000"), ("0.000", "0.000")], True),
         ([("0.000", "0.000"), ("0.000", "1.000")], True),
         ([("0.000", "1.000"), ("1.000", "1.000")], True),
         ([("0.000", "1.000"), ("1.000", "2.000")], True),
         ([("0.000", "0.000"), ("1.000", "1.000")], True),
         ([("0.000", "0.000"), ("1.000", "2.000")], True),
         ([("0.000", "1.000"), ("2.000", "2.000")], True),
         ([("0.000", "1.000"), ("2.000", "3.000")], True),
         ([("0.000", "1.000"), ("1.000", "1.000"),
           ("1.000", "2.000")], True),
         ([("0.000", "1.000"), ("1.000", "1.000"),
           ("2.000", "2.000")], True),
         ([("0.000", "1.000"), ("2.000", "3.000"),
           ("1.500", "1.500")], True),
         ([("0.000", "1.000"), ("2.000", "3.000"),
           ("1.500", "1.750")], True),
         ([("0.000", "1.000"), ("1.040", "2.000")], True),
         ([("0.000", "1.000"), ("0.000", "0.500")], False),
         ([("0.000", "1.000"), ("0.000", "1.000")], False),
         ([("0.000", "1.000"), ("0.000", "1.500")], False),
         ([("0.000", "1.000"), ("0.500", "0.500")], False),
         ([("0.000", "1.000"), ("0.500", "0.750")], False),
         ([("0.000", "1.000"), ("0.500", "1.000")], False),
         ([("0.000", "1.000"), ("0.500", "1.500")], False),
         ([("0.000", "1.000"), ("2.000", "2.000"),
           ("1.500", "2.500")], False),
         ([("0.000", "1.000"), ("2.000", "3.000"),
           ("1.500", "2.500")], False),
         ([("0.000", "1.000"), ("0.960", "2.000")], False),
     ]
     for l, exp in params:
         tree = Tree()
         for b, e in l:
             interval = TimeInterval(begin=TimeValue(b), end=TimeValue(e))
             smf = SyncMapFragment(interval=interval)
             child = Tree(value=smf)
             tree.add_child(child, as_last=True)
         syn = SyncMap(tree=tree)
         self.assertEqual(syn.leaves_are_consistent, exp)
예제 #23
0
 def test_read_none(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.read(None, self.EXISTING_SRT)
예제 #24
0
 def test_append_invalid_fragment(self):
     syn = SyncMap()
     with self.assertRaises(TypeError):
         syn.add_fragment("foo")
예제 #25
0
 def test_write_not_existing_path(self):
     syn = SyncMap()
     with self.assertRaises(OSError):
         syn.write(SyncMapFormat.SRT, self.NOT_WRITEABLE_SRT)
예제 #26
0
 def test_write_not_existing_path(self):
     syn = SyncMap()
     with self.assertRaises(OSError):
         syn.write(SyncMapFormat.SRT, self.NOT_WRITEABLE_SRT)
예제 #27
0
 def test_write_none(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.write(None, self.NOT_EXISTING_SRT)
예제 #28
0
 def test_read_none(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.read(None, self.EXISTING_SRT)
예제 #29
0
 def test_fragments_tree_empty(self):
     tree = Tree()
     syn = SyncMap(tree=tree)
     self.assertEqual(len(syn.fragments_tree), 0)
예제 #30
0
 def test_fragments_tree_not_given(self):
     syn = SyncMap()
     self.assertEqual(len(syn.fragments_tree), 0)
예제 #31
0
 def test_read_not_existing_path(self):
     syn = SyncMap()
     with self.assertRaises(OSError):
         syn.read(SyncMapFormat.SRT, self.NOT_EXISTING_SRT)
예제 #32
0
 def test_constructor_none(self):
     syn = SyncMap(tree=None)
     self.assertEqual(len(syn), 0)
예제 #33
0
 def test_leaves_are_consistent_empty(self):
     syn = SyncMap()
     self.assertTrue(syn.leaves_are_consistent)
예제 #34
0
 def test_read_invalid_format(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.read("foo", self.EXISTING_SRT)
예제 #35
0
 def test_read_invalid_format(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.read("foo", self.EXISTING_SRT)
예제 #36
0
 def test_read_not_existing_path(self):
     syn = SyncMap()
     with self.assertRaises(OSError):
         syn.read(SyncMapFormat.SRT, self.NOT_EXISTING_SRT)
예제 #37
0
    def _create_syncmap(self, adjusted_map):
        """
        Create a sync map out of the provided interval map,
        and store it in the task object.

        Return a success bool flag.
        """
        self._log("Creating sync map")
        self._log(["Number of fragments in adjusted map (including HEAD and TAIL): %d", len(adjusted_map)])
        # adjusted map has 2 elements (HEAD and TAIL) more than text_file
        if len(adjusted_map) != len(self.task.text_file.fragments) + 2:
            self._log("The number of sync map fragments does not match the number of text fragments (+2)", Logger.CRITICAL)
            return False
        try:
            sync_map = SyncMap()
            head = adjusted_map[0]
            tail = adjusted_map[-1]

            # get language
            language = Language.EN
            self._log(["Language set to default: %s", language])
            if len(self.task.text_file.fragments) > 0:
                language = self.task.text_file.fragments[0].language
                self._log(["Language read from text_file: %s", language])

            # get head/tail format
            head_tail_format = self.task.configuration.os_file_head_tail_format
            # note that str() is necessary, as head_tail_format might be None
            self._log(["Head/tail format: %s", str(head_tail_format)])

            # add head sync map fragment if needed
            if head_tail_format == SyncMapHeadTailFormat.ADD:
                head_frag = TextFragment(u"HEAD", language, [u""])
                sync_map_frag = SyncMapFragment(head_frag, head[0], head[1])
                sync_map.append(sync_map_frag)
                self._log(["Adding head (ADD): %.3f %.3f", head[0], head[1]])

            # stretch first and last fragment timings if needed
            if head_tail_format == SyncMapHeadTailFormat.STRETCH:
                self._log(["Stretching (STRETCH): %.3f => %.3f (head) and %.3f => %.3f (tail)", adjusted_map[1][0], head[0], adjusted_map[-2][1], tail[1]])
                adjusted_map[1][0] = head[0]
                adjusted_map[-2][1] = tail[1]

            i = 1
            for fragment in self.task.text_file.fragments:
                start = adjusted_map[i][0]
                end = adjusted_map[i][1]
                sync_map_frag = SyncMapFragment(fragment, start, end)
                sync_map.append(sync_map_frag)
                i += 1

            # add tail sync map fragment if needed
            if head_tail_format == SyncMapHeadTailFormat.ADD:
                tail_frag = TextFragment(u"TAIL", language, [u""])
                sync_map_frag = SyncMapFragment(tail_frag, tail[0], tail[1])
                sync_map.append(sync_map_frag)
                self._log(["Adding tail (ADD): %.3f %.3f", tail[0], tail[1]])

            self.task.sync_map = sync_map
            self._log("Creating sync map: succeeded")
            return True
        except Exception as e:
            self._log("Creating sync map: failed")
            self._log(["Message: %s", str(e)])
            return False
예제 #38
0
 def test_write_invalid_format(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.write("foo", self.NOT_EXISTING_SRT)
예제 #39
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]
        output_html = self.has_option(u"--output-html")

        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        input_sm_format = self.has_option_with_value(u"--input-format")
        if input_sm_format is None:
            input_sm_format = gf.file_extension(input_file_path)
        if not self.check_format(input_sm_format):
            return self.ERROR_EXIT_CODE

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

        if output_html:
            if len(self.actual_arguments) < 3:
                return self.print_help()
            audio_file_path = self.actual_arguments[2]
            if not self.check_input_file(audio_file_path):
                return self.ERROR_EXIT_CODE
        else:
            output_sm_format = self.has_option_with_value(u"--output-format")
            if output_sm_format is None:
                output_sm_format = gf.file_extension(output_file_path)
            if not self.check_format(output_sm_format):
                return self.ERROR_EXIT_CODE

        # TODO add a way to specify a text file for input formats like SMIL
        #      that do not carry the source text
        language = self.has_option_with_value(u"--language")
        audio_ref = self.has_option_with_value(u"--audio-ref")
        page_ref = self.has_option_with_value(u"--page-ref")
        parameters = {
            gc.PPN_SYNCMAP_LANGUAGE : language,
            gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF : audio_ref,
            gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF : page_ref
        }

        try:
            self.print_info(u"Reading sync map in '%s' format from file '%s'" % (input_sm_format, input_file_path))
            self.print_info(u"Reading sync map...")
            syncmap = SyncMap(logger=self.logger)
            syncmap.read(input_sm_format, input_file_path, parameters)
            self.print_info(u"Reading sync map... done")
            self.print_info(u"Read %d sync map fragments" % (len(syncmap)))
        except Exception as exc:
            self.print_error(u"An unexpected error occurred while reading the input sync map:")
            self.print_error(u"%s" % (exc))
            return self.ERROR_EXIT_CODE

        if output_html:
            try:
                self.print_info(u"Writing HTML file...")
                syncmap.output_html_for_tuning(audio_file_path, output_file_path, parameters)
                self.print_info(u"Writing HTML file... done")
                self.print_success(u"Created HTML file '%s'" % (output_file_path))
                return self.NO_ERROR_EXIT_CODE
            except Exception as exc:
                self.print_error(u"An unexpected error occurred while writing the output HTML file:")
                self.print_error(u"%s" % (exc))
        else:
            try:
                self.print_info(u"Writing sync map...")
                syncmap.write(output_sm_format, output_file_path, parameters)
                self.print_info(u"Writing sync map... done")
                self.print_success(u"Created '%s' sync map file '%s'" % (output_sm_format, output_file_path))
                return self.NO_ERROR_EXIT_CODE
            except Exception as exc:
                self.print_error(u"An unexpected error occurred while writing the output sync map:")
                self.print_error(u"%s" % (exc))

        return self.ERROR_EXIT_CODE
예제 #40
0
 def test_constructor(self):
     syn = SyncMap()
     self.assertEqual(len(syn), 0)
예제 #41
0
 def test_append_none(self):
     syn = SyncMap()
     with self.assertRaises(TypeError):
         syn.add_fragment(None)
예제 #42
0
 def test_write_invalid_format(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.write("foo", self.NOT_EXISTING_SRT)
예제 #43
0
 def test_append_none(self):
     syn = SyncMap()
     with self.assertRaises(TypeError):
         syn.add_fragment(None)
예제 #44
0
 def test_write_none(self):
     syn = SyncMap()
     with self.assertRaises(ValueError):
         syn.write(None, self.NOT_EXISTING_SRT)
예제 #45
0
 def test_has_zero_length_leaves_empty(self):
     syn = SyncMap()
     self.assertFalse(syn.has_zero_length_leaves)
예제 #46
0
    def _create_syncmap(self, adjusted_map):
        """
        Create a sync map out of the provided interval map,
        and store it in the task object.

        Return a success bool flag.
        """
        self._log("Creating sync map")
        self._log([
            "Number of fragments in adjusted map (including HEAD and TAIL): %d",
            len(adjusted_map)
        ])
        # adjusted map has 2 elements (HEAD and TAIL) more than text_file
        if len(adjusted_map) != len(self.task.text_file.fragments) + 2:
            self._log(
                "The number of sync map fragments does not match the number of text fragments (+2)",
                Logger.CRITICAL)
            return False
        try:
            sync_map = SyncMap()
            head = adjusted_map[0]
            tail = adjusted_map[-1]

            # get language
            language = Language.EN
            self._log(["Language set to default: %s", language])
            if len(self.task.text_file.fragments) > 0:
                language = self.task.text_file.fragments[0].language
                self._log(["Language read from text_file: %s", language])

            # get head/tail format
            head_tail_format = self.task.configuration.os_file_head_tail_format
            # note that str() is necessary, as head_tail_format might be None
            self._log(["Head/tail format: %s", str(head_tail_format)])

            # add head sync map fragment if needed
            if head_tail_format == SyncMapHeadTailFormat.ADD:
                head_frag = TextFragment(u"HEAD", language, [u""])
                sync_map_frag = SyncMapFragment(head_frag, head[0], head[1])
                sync_map.append(sync_map_frag)
                self._log(["Adding head (ADD): %.3f %.3f", head[0], head[1]])

            # stretch first and last fragment timings if needed
            if head_tail_format == SyncMapHeadTailFormat.STRETCH:
                self._log([
                    "Stretching (STRETCH): %.3f => %.3f (head) and %.3f => %.3f (tail)",
                    adjusted_map[1][0], head[0], adjusted_map[-2][1], tail[1]
                ])
                adjusted_map[1][0] = head[0]
                adjusted_map[-2][1] = tail[1]

            i = 1
            for fragment in self.task.text_file.fragments:
                start = adjusted_map[i][0]
                end = adjusted_map[i][1]
                sync_map_frag = SyncMapFragment(fragment, start, end)
                sync_map.append(sync_map_frag)
                i += 1

            # add tail sync map fragment if needed
            if head_tail_format == SyncMapHeadTailFormat.ADD:
                tail_frag = TextFragment(u"TAIL", language, [u""])
                sync_map_frag = SyncMapFragment(tail_frag, tail[0], tail[1])
                sync_map.append(sync_map_frag)
                self._log(["Adding tail (ADD): %.3f %.3f", tail[0], tail[1]])

            self.task.sync_map = sync_map
            self._log("Creating sync map: succeeded")
            return True
        except Exception as e:
            self._log("Creating sync map: failed")
            self._log(["Message: %s", str(e)])
            return False
예제 #47
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]
        output_html = self.has_option(u"--output-html")

        if not self.check_input_file(input_file_path):
            return self.ERROR_EXIT_CODE
        input_sm_format = self.has_option_with_value(u"--input-format")
        if input_sm_format is None:
            input_sm_format = gf.file_extension(input_file_path)
        if not self.check_format(input_sm_format):
            return self.ERROR_EXIT_CODE

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

        if output_html:
            if len(self.actual_arguments) < 3:
                return self.print_help()
            audio_file_path = self.actual_arguments[2]
            if not self.check_input_file(audio_file_path):
                return self.ERROR_EXIT_CODE
        else:
            output_sm_format = self.has_option_with_value(u"--output-format")
            if output_sm_format is None:
                output_sm_format = gf.file_extension(output_file_path)
            if not self.check_format(output_sm_format):
                return self.ERROR_EXIT_CODE

        # TODO add a way to specify a text file for input formats like SMIL
        #      that do not carry the source text
        language = self.has_option_with_value(u"--language")
        audio_ref = self.has_option_with_value(u"--audio-ref")
        page_ref = self.has_option_with_value(u"--page-ref")
        parameters = {
            gc.PPN_SYNCMAP_LANGUAGE: language,
            gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF: audio_ref,
            gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF: page_ref
        }

        try:
            self.print_info(u"Reading sync map in '%s' format from file '%s'" %
                            (input_sm_format, input_file_path))
            self.print_info(u"Reading sync map...")
            syncmap = SyncMap(logger=self.logger)
            syncmap.read(input_sm_format, input_file_path, parameters)
            self.print_info(u"Reading sync map... done")
            self.print_info(u"Read %d sync map fragments" % (len(syncmap)))
        except Exception as exc:
            self.print_error(
                u"An unexpected error occurred while reading the input sync map:"
            )
            self.print_error(u"%s" % (exc))
            return self.ERROR_EXIT_CODE

        if output_html:
            try:
                self.print_info(u"Writing HTML file...")
                syncmap.output_html_for_tuning(audio_file_path,
                                               output_file_path, parameters)
                self.print_info(u"Writing HTML file... done")
                self.print_success(u"Created HTML file '%s'" %
                                   (output_file_path))
                return self.NO_ERROR_EXIT_CODE
            except Exception as exc:
                self.print_error(
                    u"An unexpected error occurred while writing the output HTML file:"
                )
                self.print_error(u"%s" % (exc))
        else:
            try:
                self.print_info(u"Writing sync map...")
                syncmap.write(output_sm_format, output_file_path, parameters)
                self.print_info(u"Writing sync map... done")
                self.print_success(u"Created '%s' sync map file '%s'" %
                                   (output_sm_format, output_file_path))
                return self.NO_ERROR_EXIT_CODE
            except Exception as exc:
                self.print_error(
                    u"An unexpected error occurred while writing the output sync map:"
                )
                self.print_error(u"%s" % (exc))

        return self.ERROR_EXIT_CODE
예제 #48
0
 def test_constructor_invalid(self):
     with self.assertRaises(TypeError):
         syn = SyncMap(tree=[])
예제 #49
0
 def test_append_invalid_fragment(self):
     syn = SyncMap()
     with self.assertRaises(TypeError):
         syn.add_fragment("foo")