Esempio n. 1
0
def edit(path="/"):
    """Edit the given subtitle, or create a new one"""
    path = normalize_path(path)
    realpath = os.path.abspath(root_dir + path)
    data = {}
    title = ".".join(path.split("/")[-1].split(".")[:-2])
    data["title"] = title
    data["path"] = path
    data["root"] = "/".join(path.split("/")[:-1])
    data["breadCrumbs"] = listBreadCrumbs(path)

    if "shift" in request.values:
        # Shift subtitle
        try:
            s = float(request.values["shift"])
            shift.shift(realpath, s)
            data["message"] = "File shifted by {}s.".format(s)
        except ValueError:
            pass
    elif "upload" in request.files:
        # Upload custom subtitle
        f = request.files["upload"]
        name = os.path.splitext(path.split("/")[-1])[0]
        data["message"] = 'The file "' + name + '.srt" has been uploaded'
        ext = os.path.splitext(f.filename)[1]
        target = os.path.splitext(realpath)[0] + ".srt"
        if ext == ".sub":
            # Convert .sub to .srt
            t = tempfile.NamedTemporaryFile()
            f.save(t.name)
            sub2srt.convert(t.name, target)
            data["message"] += " and converted to SRT format"
        else:
            f.save(target)
        os.chmod(target, 0o666)
        normalize_encoding(target)
    elif "auto" in request.values:
        # Download subtitle from OpenSubtitle
        try:
            folderPath = "/".join((root_dir + normalize_path(path)).split("/")[:-1])
            opensubs.get_sub(root_dir + normalize_path(path))
        except:
            logging.warning(traceback.format_exc())
            data["message"] = "Could not download subtitles"

    # Subtitle content
    try:
        data["filecontent"] = open(realpath).read().replace("\n", "<br/>")
        data["sub_title"] = "Subtitle content"
    except:
        data["sub_title"] = "No subtitle"

    return flask.render_template("edit.html", **data)
 def _saveYTSubtitles(self, ID, vidFile, mediaPath):
     url = 'http://video.google.com/timedtext?hl=%(LANG)s&v=%(ID)s&lang=%(LANG)s'
     url = url % {'LANG': 'cs', 'ID': ID}
     destFile = self._get_subtitles_file(vidFile, mediaPath)
     try:
         r = urllib2.urlopen(url, timeout=3)
         if r.code == 200:
             savedFile = os.path.join(self.tmp, 'titles.txt')
             with open(savedFile, 'w') as f:
                 f.write(r.read())
             sub2srt.convert(savedFile, destFile)
     except Exception:
         pass
Esempio n. 3
0
 def _saveYTSubtitles(self, ID, vidFile, mediaPath):
     url = 'http://video.google.com/timedtext?hl=%(LANG)s&v=%(ID)s&lang=%(LANG)s'
     url = url % {'LANG': 'cs', 'ID': ID}
     destFile = self._get_subtitles_file(vidFile, mediaPath)
     try:
         r = urllib2.urlopen(url, timeout=3)
         if r.code == 200:
             savedFile = os.path.join(self.tmp, 'titles.txt')
             with open(savedFile, 'w') as f:
                 f.write(r.read())
             sub2srt.convert(savedFile, destFile)
     except Exception:
         pass
Esempio n. 4
0
    def getSRT(self, fileLoc):
        head, ext = os.path.splitext(os.path.basename(fileLoc))
        log("head: %s" % head)
        
        #First check existing subtitle files, especially existing SRT backups
        for fname in os.listdir(os.path.dirname(fileLoc)):
            parts = os.path.splitext(fname)
            if len(parts) == 2 and parts[1].lower() == ".mpbak" and parts[0].endswith(".srt"):
                originalname = os.path.join(os.path.dirname(fileLoc), fname[:-len(".mpbak")])
                log("Found backup srt file, renaming to original name: " + originalname)
                if xbmcvfs.exists(originalname):
                    log("Removing the original file name so we can rename")
                    xbmcvfs.delete(originalname)
                xbmcvfs.rename(os.path.join(os.path.dirname(fileLoc), fname), originalname)
                return originalname

        for fname in os.listdir(os.path.dirname(fileLoc)):
            log("Checking fname: %s" % fname)
            if fname.startswith(head) and os.path.splitext(fname)[1].lower() == ".srt":
                fname = os.path.join(os.path.dirname(fileLoc), fname)
                log("Found existing SRT file: %s" % fname)
                return fname
                
        log("No existing SRT file was found")
        
        #Check other subtitle formats, converting them to SRT, starting with SubStation Alpha
        extensions = ['.ssa', '.ass']
        for fname in os.listdir(os.path.dirname(fileLoc)):
            if fname.startswith(head) and os.path.splitext(fname)[1].lower() in extensions:
                fname = os.path.join(os.path.dirname(fileLoc), fname)
                log("Found existing Substation Alpha file: %s" % fname)
                try:
                    return ssatool.main(fname)
                except:
                    log("Error attempting to convert SubStation Alpha file")
                    
        #Check for SMI files
        for fname in os.listdir(os.path.dirname(fileLoc)):
            if fname.startswith(head) and os.path.splitext(fname)[1].lower() == ".smi":
                fname = os.path.join(os.path.dirname(fileLoc), fname)
                log("Found existing SMI file: %s" % fname)
                try:
                    srtFile = smi2srt.convertSMI(fname)
                    if srtFile:
                        return srtFile
                except:
                    log("Error attempting to convert SubStation Alpha file")
        
        #Check for sub files last
        for fname in os.listdir(os.path.dirname(fileLoc)):
            if fname.startswith(head) and os.path.splitext(fname)[1].lower() == ".sub":
                fname = os.path.join(os.path.dirname(fileLoc), fname)
                log("Found existing SUB file: %s, converting to SRT" % fname)
                try:
                    return sub2srt.convert(fname)
                except:
                    log("Error attempting to convert sub file")
        
        extractor = None
        if ext.lower() == '.mkv' and self.Addon.getSetting("usemkvextract") == "true":
            log("Will attempt to use mkvextract to extract subtitle")
            toolsDir = self.Addon.getSetting("mkvextractpath")
            if toolsDir:
                extractor = mkv.MKVExtractor(toolsDir)
            else:
                extractor = mkv.MKVExtractor()
        elif (ext.lower() == ".m4v" or ext.lower() == '.mp4') and self.Addon.getSetting("usemp4box") == "true":
            log("Will attempt to use mp4box to extract subtitle")
            extractor = mp4.MP4Extractor()
        
        if extractor:
            subTrack = None
            try:
                subTrack = extractor.getSubTrack(fileLoc)
            except:
                log(traceback.format_exc())
                log('Error attempting to get the subtitle track')
            
            if not subTrack:
                log("No subtitle track found in the file")
                
            else:
                pDialog = xbmcgui.DialogProgress()
                pDialog.create('XBMC', self.Addon.getLocalizedString(30320))
                extractor.startExtract(fileLoc, subTrack)
                while extractor.isRunning():
                    if pDialog.iscanceled():
                        extractor.cancelExtract()
                        log("User cancelled the extraction progress; returning")
                        return None
                    pDialog.update(extractor.progress)
                    time.sleep(.1)
                
                pDialog.close()    
                srtFile = extractor.getSubFile()
                if srtFile:
                    return srtFile
                else:
                    log("Unable to extract subtitle from file")
                    xbmcgui.Dialog().ok('XBMC', self.Addon.getLocalizedString(30321))
                    
        dialog = xbmcgui.Dialog()
        download = True
        if self.Addon.getSetting("autodownload") != "true":
            download = dialog.yesno("XBMC", self.Addon.getLocalizedString(30304))
            
        if download:
            pDialog = xbmcgui.DialogProgress()
            pDialog.create('XBMC', self.Addon.getLocalizedString(30305))
            log('Attempting to download subtitle file from the internet')
            extractor = sdl.StartThreaded(fileLoc, "eng")
            while extractor.isAlive():
                if pDialog.iscanceled():
                    log("Dialog was cancelled, Stopping download")
                    extractor.join(.01)
                    pDialog.close()
                    return None
                time.sleep(.1)
            
            pDialog.close()
            srtFile = extractor.join()
            if srtFile:
                log("Successfully downloaded subtitle file: %s" % srtFile)
                return srtFile
            else:
                log("Could not download subtitle file")
                dialog.ok('XBMC', self.Addon.getLocalizedString(30306))
        
        #Any other options to create SRT file, put them here
        log("Could not use any means available to find the subtitle file")
        return None
Esempio n. 5
0
 def _save_SRT(self, input_stream, output_stram):
     import sub2srt
     sub2srt.convert(input_stream, output_stram)