Beispiel #1
0
    def read_from_file(self):
        f = open(self.fileName.decode('utf-8'), "r")
        data = f.readlines()
        f.close()

        encoding = self.encoding_detection(data)
        if not ('UTF' in encoding.upper() or 'ASCII' in encoding.upper()):
            data = self.convert_to_utf8(data, 'windows-1253')

        subs = []
        state = [0,"",[]]
        stateIdx = 0
        for line in data:
            if stateIdx == 0 and len(self.digitLine.findall(line)) > 0:
                state[0] = line.strip()
                stateIdx = 1
                continue
            if stateIdx == 1 and len(self.timeLine.findall(line)) > 0:
                state[1] = line.strip()
                stateIdx = 2
                continue
            if stateIdx == 2 and line.strip() != "":
                state[2].append(line.strip())
            if stateIdx == 2 and (line.strip() == "" or line == data[-1]):
                timeCode = state[1].split(" --> ")
                text = ""
                for item in state[2]:
                    text += item + '\n'
                text = text[:-1]
                subs.append(subRec(timeCode[0], timeCode[1], text.decode("utf-8", "ignore")))
                state = [0, "", []]
                stateIdx = 0
        return subs
Beispiel #2
0
 def save(self):
     if self.filename == '':
         return
     subList = [
         subRec(self.start_data[i].msec, self.stop_data[i].msec,
                self.text_data[i]) for i in range(len(self.text_data))
     ]
     f = srtFile(self.filename)
     f.write_to_file(subList)
Beispiel #3
0
    def read_from_file(self):
        f = open(self.fileName, "rb")
        _data = f.read()
        f.close()

        encoding = self.encoding_detection(_data)
        f = open(self.fileName, "r", encoding=encoding, errors = 'ignore')
        data = f.readlines()
        f.close()

        subs = []
        state = [0,"",[]]
        stateIdx = 0

        for idx, line in enumerate(data):
            if stateIdx == 0 and len(self.digitLine.findall(line)) > 0:
                state[0] = line.strip()
                stateIdx = 1
                continue
            if stateIdx == 1 and len(self.timeLine.findall(line)) > 0:
                state[1] = line.strip()
                stateIdx = 2
                continue
            if stateIdx == 2 and line.strip() != "":
                state[2].append(line.strip())
            if stateIdx == 2 and (line.strip() == "" or idx == len(data)-1):
                timeCode = state[1].split(" --> ")
                text = ""
                for item in state[2]:
                    text += item + '\n'
                text = text[:-1]
                subs.append(subRec(timeCode[0], timeCode[1], text))
                state = [0, "", []]
                stateIdx = 0

        return subs
Beispiel #4
0
    def __init__(self, parent, sub, info_type, thesaurus):
        super(cTextEditDialog, self).__init__('Subtitle Text Editor', None, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, ("_Cancel", Gtk.ResponseType.CANCEL, "_OK", Gtk.ResponseType.OK))
        self.set_transient_for(parent)
        self.set_default_size(500, 240)
        self.char_count = Gtk.TextView()
        self.char_count.set_property('width-request', 30)
        self.char_count.set_sensitive(False)
        self.thesaurus = thesaurus
        
        self.hbox = Gtk.HBox(spacing = 1)
        self.text_view_box = Gtk.VBox(spacing = 1)
        self.text_view = Gtk.TextView()
        self.text_view.set_size_request(-1, 50)
        self.helper_text_view = Gtk.TextView()
        self.helper_text_view.set_property('editable', False)
        self.helper_text_view.set_property('can-focus', False)
        self.text_view_box.add(self.text_view)
        self.text_view_box.add(self.helper_text_view)

        if info_type == 'info':
            color_list = [(sub.info[key][1], sub.info[key][2]) for key in sub.info if key.startswith('Text')]
            tagText = cTagText()
            tagText.text = sub.text
            for color in color_list:
                for pos in color[0]:
                    tagText.add_tag(Tag('span', pos[0], pos[1], {'background': color[1]}))
            tagText.replace_parsed('<i>', '&lt;i&gt;')
            tagText.replace_parsed('</i>', '&lt;/i&gt;')
            custom_insert_markup(self.text_view.get_buffer(), tagText.markup)
            custom_insert_markup(self.helper_text_view.get_buffer(), sub.info_text_str)
        elif info_type == 'vo':
            self.text_view.get_buffer().set_text(sub.text)
            self.helper_text_view.get_buffer().set_text(sub.vo)

        self.rs_text_label = Gtk.Label('Reading Speed: ')
        self.rs_value_label = Gtk.Label('')
        self.rs_dummylabel = Gtk.Label('\t\t\t\t')
        self.rs_box = Gtk.HBox(spacing = 1)
        self.rs_box.pack_start(self.rs_text_label, False, False, 0)
        self.rs_box.pack_start(self.rs_value_label, False, False, 0)
        self.rs_box.pack_start(self.rs_dummylabel, True, True, 0)

        self.history = cHistory(self.text_view.get_buffer())
        self.text_view.history = self.history

        self.spell = GtkSpell.Checker()
        self.spell.attach(self.text_view)
        self.spell.set_language('el_GR')

        self.hbox.pack_start(self.char_count, False, False, 0)
        self.hbox.pack_end(self.text_view_box, True, True, 0)
        self.vbox.pack_start(self.hbox,True, True, 0)
        self.action_area.pack_start(self.rs_box, False, False, 0)
        self.action_area.reorder_child(self.rs_box, 0)

        self.sub = subtitles.subRec(int(sub.startTime), int(sub.stopTime),  sub.text)
        self.update_count()

        self.vbox.show_all()
        self.set_default_response(Gtk.ResponseType.OK)
        self.changed_handler = self.text_view.get_buffer().connect('changed', self.buffer_changed)
        self.text_view.connect("key-release-event", self.key_release)
        self.text_view.connect("key-press-event", self.key_press)
        self.connect('destroy-event', self.on_destroy)
        self.text = sub.text

        self.text_view.connect('populate-popup',  self.on_tv_populate_popup)
        self.text_view.connect('button-press-event', self.on_tv_button_press)
        self.helper_text_view.connect('populate-popup',  self.on_hp_populate_popup)
        self.helper_text_view.connect('button-press-event', self.on_hp_button_press)
        self.helper_text_view.last_mouse_x = 0
        self.helper_text_view.last_mouse_y = 0
        self.text_view.last_mouse_x  = 0
        self.text_view.last_mouse_y = 0
        self.spell.on_buffer_changed(self.text_view.get_buffer())
Beispiel #5
0
    def __init__(self, parent, sub, info_type, thesaurus):
        super(cTextEditDialog, self).__init__('Subtitle Text Editor', None, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, ("_Cancel", Gtk.ResponseType.CANCEL, "_OK", Gtk.ResponseType.OK))
        self.set_transient_for(parent)
        self.set_default_size(500, 240)
        self.char_count = Gtk.TextView()
        self.char_count.set_property('width-request', 30)
        self.char_count.set_sensitive(False)
        self.thesaurus = thesaurus

        self.hbox = Gtk.HBox(spacing = 1)
        self.text_view_box = Gtk.VBox(spacing = 1)
        self.text_view = Gtk.TextView()
        self.text_view.set_size_request(-1, 50)
        self.helper_text_view = Gtk.TextView()
        self.helper_text_view.set_property('editable', False)
        #self.helper_text_view.set_property('can-focus', False)
        self.text_view_box.add(self.text_view)
        self.text_view_box.add(self.helper_text_view)
        self.info_resp_button = None
        self.info_type = info_type

        if info_type == 'info':
            color_list = [(sub.info[key][1], sub.info[key][2]) for key in sub.info if key.startswith('Text')]
            tagText = cTagText()
            tagText.text = sub.text
            for color in color_list:
                for pos in color[0]:
                    tagText.add_tag(Tag('span', pos[0], pos[1], {'background': color[1]}))
            tagText.replace_parsed('<i>', '&lt;i&gt;')
            tagText.replace_parsed('</i>', '&lt;/i&gt;')
            custom_insert_markup(self.text_view.get_buffer(), tagText.markup)
            custom_insert_markup(self.helper_text_view.get_buffer(), sub.info_text_str)
        elif info_type == 'vo':
            self.text_view.get_buffer().set_text(sub.text)
            if sub.vo != '':
                self.helper_text_view.get_buffer().set_text(sub.vo)
            else:
                self.helper_text_view.get_buffer().set_text(sub.text)
        elif info_type == 'copy':
            self.text_view.get_buffer().set_text(sub.text)
            self.helper_text_view.get_buffer().set_text(sub.text)

        self.rs_text_label = Gtk.Label('Reading Speed: ')
        self.rs_value_label = Gtk.Label('')
        self.rs_dummylabel = Gtk.Label('\t\t\t\t')
        self.rs_box = Gtk.HBox(spacing = 1)
        self.rs_box.pack_start(self.rs_text_label, False, False, 0)
        self.rs_box.pack_start(self.rs_value_label, False, False, 0)
        self.rs_box.pack_start(self.rs_dummylabel, True, True, 0)

        self.history = cHistory(self.text_view.get_buffer())
        self.text_view.history = self.history

        self.spell = GtkSpell.Checker()
        self.spell.attach(self.text_view)
        self.spell.set_language('el_GR')

        if info_type == 'info':
            button_next = Gtk.Button('>')
            button_prev = Gtk.Button('<')
            self.hbox.pack_start(button_prev, False, False, 1)
            self.hbox.pack_end(button_next, False, False, 1)
            button_next.connect('clicked', self.on_nav_button, 'next')
            button_prev.connect('clicked', self.on_nav_button, 'prev')

        self.hbox.pack_start(self.char_count, False, False, 0)
        self.hbox.pack_end(self.text_view_box, True, True, 0)
        self.vbox.pack_start(self.hbox,True, True, 0)

        self.action_area.pack_start(self.rs_box, False, False, 0)
        self.action_area.reorder_child(self.rs_box, 0)

        self.sub = subtitles.subRec(int(sub.startTime), int(sub.stopTime),  sub.text)
        self.update_count()

        self.vbox.show_all()

        self.set_default_response(Gtk.ResponseType.OK)
        self.changed_handler = self.text_view.get_buffer().connect('changed', self.buffer_changed)
        self.text_view.connect("key-release-event", self.key_release)
        self.text_view.connect("key-press-event", self.key_press)
        self.connect('destroy-event', self.on_destroy)
        self.text = sub.text

        self.text_view.connect('populate-popup',  self.on_tv_populate_popup)
        self.text_view.connect('button-press-event', self.on_tv_button_press)
        self.helper_text_view.connect('populate-popup',  self.on_hp_populate_popup)
        self.helper_text_view.connect('button-press-event', self.on_hp_button_press)
        self.helper_text_view.last_mouse_x = 0
        self.helper_text_view.last_mouse_y = 0
        self.text_view.last_mouse_x  = 0
        self.text_view.last_mouse_y = 0
        self.spell.on_buffer_changed(self.text_view.get_buffer())
        self.text_view.grab_focus()
Beispiel #6
0
    def run(self):
        if not hasattr(self, 'dst_v_fname'):
            self.close()
            return

        # Create raw filenames
        path = explode_path(self.src_v_fname)[0]
        sraw = join(path, 'src-xsubedit.raw')
        draw = join(path, 'dst-xsubedit.raw')

        # Generate Src Raw Audio
        #rdlg = cRawGenerationDialog(self, self.src_v_fname, sraw)
        #rdlg.run()

        # Generate Dst Raw Audio
        #rdlg = cRawGenerationDialog(self, self.dst_v_fname, draw)
        #rdlg.run()

        # Load Src, Dst spectrums
        if not exists(sraw) or not exists(draw):
            return
        src_spec = autoSyncTools.get_spect_from_file(sraw)
        dst_spec = autoSyncTools.get_spect_from_file(draw)

        # Normalize spectrums
        dst_spec = autoSyncTools.normalize_spec(dst_spec)
        src_spec = autoSyncTools.normalize_spec(src_spec)

        # create a new empty sublist
        dst_sublist = []
        missing_subs = []

        # match subs
        pb = cProgressBarDialog(self, 'Matching subtitles...',
                                'Matching subtitle 0 / %d' % len(self.subs))
        pb.set_progress(idx / len(self.subs))
        pb.update_info('Matching subtitle %d / %d' % (idx, len(self.subs)))

        # Step 1: match a low, middle and high subs
        sl = match_low(src_spec, dst_spec, self.subs)
        sm = match_middle(src_spec, dst_spec, self.subs)
        sh = match_high(src_spec, dst_spec, self.subs)
        if any([i is None for i in [sl, sm, sh]]):
            return False  # Failed to auto sync
        # Step 2: Calc the "line"
        rate1 = int(sm.startTime) - int(sl.startTime)
        rate2 = int(sh.startTime) - int(sm.startTime)
        if 0.95 < rate2 / rate1 < 1.05:
            dst_sublist = [
                subRec(sub.startTime, sub.stopTime, sub.text)
                for sub in self.subs
            ]
            d0 = int(dst_sublist[0].startTime)
            drate = (rate1 + rate2) / 2
            for sub in dst_sublist:
                sub.startTime -= d0
                sub.stopTime -= d0
                srate = (sub - d0) // len(self.subs)

        else:
            pass  # split into two lists, fist half and second half
            # Then run the whole process for each lists

        self.process_messages()
        pb.close()

        # save new sublist
        if len(dst_sublist) > 0:
            pd = explode_path(self.dst_v_fname)
            srt = subfile.srtFile(join(pd[0], pd[1] + '.srt'))
            srt.write_to_file(dst_sublist)
Beispiel #7
0
 def on_dragging(self, msec):
     if self.overHandle != None:
         if self.overSub != self.tmpSub:
             self.tmpSub = None
         # In this case we are dragging a subtitle handle
         target_time = None
         if self.dragging_sub == None:
             self.dragging_sub = subRec(int(self.overSub.startTime), int(self.overSub.stopTime), self.overSub.text)
         if self.overHandle == self.HANDLE_START:
             prevSub = self.subtitlesModel.get_prev(self.overSub)
             if prevSub == None:
                 target_time = msec if msec > 0 else None
             else:
                 target_time = msec if prevSub.stopTime + 120 <= msec else int(prevSub.stopTime + 120)
             target_time = target_time if target_time < self.overSub.stopTime else None
             if target_time:
                 self.activeSub = self.overSub
                 self.overSub.startTime = target_time
                 self.isCanvasBufferValid = False
                 self.queue_draw()
                 if self.overSub != self.tmpSub:
                     self.emit('sub-updated', self.overSub)
         elif self.overHandle == self.HANDLE_END:
             nextSub = self.subtitlesModel.get_next(self.overSub)
             if nextSub == None:
                 target_time = msec if msec < self.videoDuration - 120 else None
             else:
                 target_time = msec if nextSub.startTime - 120 >= msec else int(nextSub.startTime - 120)
             target_time = target_time if target_time > self.overSub.startTime else None
             if target_time:
                 self.activeSub = self.overSub
                 self.overSub.stopTime = target_time
                 self.isCanvasBufferValid = False
                 self.queue_draw()
                 if self.overSub != self.tmpSub:
                     self.emit('sub-updated', self.overSub)
     else:
         # In this case we are creating a temporary sub
         target_time = msec if self.lowms <= msec <= self.highms else None
         initial_msec = self.get_mouse_msec(self.mouse_click_coords[0])
         if self.tmpSub == None:
             if target_time and (abs(target_time - initial_msec) / self.mspp) > 6:
                 self.tmpSub = subRec(min(initial_msec, target_time), max(initial_msec, target_time), '')
             else:
                 if target_time:
                     self.cursor = target_time
                     self.isCanvasBufferValid = False
                     self.queue_draw()
         else:
             if target_time and (abs(target_time - initial_msec) / self.mspp) > 6:
                 self.tmpSub.startTime = min(initial_msec, target_time)
                 self.tmpSub.stopTime = max(initial_msec, target_time)
                 self.emit('tmpSub-update')
                 self.videoSegment = ( int(self.tmpSub.startTime), int(self.tmpSub.stopTime))
                 self.isCanvasBufferValid = False
                 self.queue_draw()
             else:
                 self.tmpSub = None
                 if target_time:
                     self.cursor = target_time
                     self.isCanvasBufferValid = False
                     self.queue_draw()