Example #1
0
def convertSubtitles(part, SaveSRT):
    Log(part.file)
    basePath = os.path.splitext(part.file)[0]
    smiPath = basePath + '.smi'
    if not os.path.exists(smiPath):
        return False

    ext = '.smi'

    # (1) transcode to CP949
    subData = Core.storage.load(smiPath)
    subEncoding = chdet(subData)

    # (2) convert SMI to SRT and save
    result = {'ko': ''}
    if SaveSRT and subEncoding != 'Unknown':  # if Unicode with BOM
        result['ko'] = convertSMI(
            subData.decode(subEncoding, 'ignore').encode('utf-8'))
        Log('convert(%s)' % (smiPath))
        ext = '.srt'
        Core.storage.save(basePath + '.ko' + ext, result['ko'])
        return True
    elif SaveSRT and subEncoding == 'Unknown':  # if EUC-KR
        subData = convertSMI(
            subData.decode('EUC-KR', 'ignore').encode('utf-8'))
        Log('convert Unknown')
        if subData != False:
            # print('convert(%s)(EUC-KR)' % smiPath)
            Core.storage.save(basePath + '.ko.srt', subData)
            return True
        else:  # else
            Log('Unknown Encoding')
    elif not SaveSRT:
        Log('SaveSRT false')
Example #2
0
def convertSubtitles(part, SaveSRT):
  Log(part.file)
  basePath = os.path.splitext(part.file)[0]
  smiPath = basePath+'.smi'
  if not os.path.exists(smiPath):
    return False

  ext = '.smi'

  # (1) transcode to CP949
  subData = Core.storage.load(smiPath)
  subEncoding = chdet(subData)
  if subEncoding != 'Unknown':
    Log('transcode to cp949')
    subData = unicode(subData, subEncoding, 'ignore').encode('cp949')

  # (2) split languages if needed
  result = demuxSMI(subData)

  # (3) convert SMI to SRT
  if SaveSRT:
    result2 = dict()
    for lang, smiData in result.iteritems():
      result2[lang] = convertSMI(smiData.decode('cp949','ignore').encode('utf-8'))
      Log('convert(%s): %d -> %d' % (lang, len(smiData), len(result2[lang])))
    result = result2
    ext = '.srt'

  # (4) save
  if not SaveSRT and subEncoding == 'Unknown':
    return True	    # no need to save
  if len(result) > 1:
    for lang, subData in result.iteritems():
      Core.storage.save(basePath+'.'+lang+ext, subData)
  elif SaveSRT or subEncoding != 'Unknown':
    Core.storage.save(basePath+'.ko'+ext, result['unknown'])
  return True
Example #3
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