Best Python code snippet using yandex-tank
SubtitlesSupport.py
Source:SubtitlesSupport.py
1#Embedded file name: ACEStream\Core\Subtitles\SubtitlesSupport.pyo2from ACEStream.Core.Subtitles.MetadataDomainObjects.Languages import LanguagesProvider3from ACEStream.Core.Subtitles.MetadataDomainObjects.MetadataDTO import MetadataDTO4from ACEStream.Core.Subtitles.MetadataDomainObjects.MetadataExceptions import RichMetadataException5from ACEStream.Core.Subtitles.MetadataDomainObjects.SubtitleInfo import SubtitleInfo6from ACEStream.Core.Utilities import utilities7from ACEStream.Core.Utilities.utilities import isValidPermid, bin2str8import sys9import threading10DEBUG = False11class SubtitlesSupport(object):12 __single = None13 _singletonLock = threading.RLock()14 def __init__(self):15 try:16 SubtitlesSupport._singletonLock.acquire()17 SubtitlesSupport.__single = self18 finally:19 SubtitlesSupport._singletonLock.release()20 self.richMetadata_db = None21 self.subtitlesHandler = None22 self.channelcast_db = None23 self.langUtility = LanguagesProvider.getLanguagesInstance()24 self._registered = False25 @staticmethod26 def getInstance(*args, **kw):27 try:28 SubtitlesSupport._singletonLock.acquire()29 if SubtitlesSupport.__single == None:30 SubtitlesSupport(*args, **kw)31 finally:32 SubtitlesSupport._singletonLock.release()33 return SubtitlesSupport.__single34 def _register(self, richMetadataDBHandler, subtitlesHandler, channelcast_db, my_permid, my_keypair, peersHaveManger, ol_bridge):35 self.richMetadata_db = richMetadataDBHandler36 self.subtitlesHandler = subtitlesHandler37 self.channelcast_db = channelcast_db38 self.my_permid = my_permid39 self.my_keypair = my_keypair40 self._peersHaveManager = peersHaveManger41 self._ol_bridge = ol_bridge42 self._registered = True43 def getSubtileInfosForInfohash(self, infohash):44 returnDictionary = dict()45 metadataDTOs = self.richMetadata_db.getAllMetadataForInfohash(infohash)46 for metadataDTO in metadataDTOs:47 channel = metadataDTO.channel48 subtitles = metadataDTO.getAllSubtitles()49 if len(subtitles) > 0:50 returnDictionary[channel] = subtitles51 return returnDictionary52 def getSubtitleInfos(self, channel, infohash):53 metadataDTO = self.richMetadata_db.getMetadata(channel, infohash)54 if metadataDTO:55 return metadataDTO.getAllSubtitles()56 return {}57 def publishSubtitle(self, infohash, lang, pathToSrtSubtitle):58 channelid = bin2str(self.my_permid)59 base64infohash = bin2str(infohash)60 consinstent = self.channelcast_db.isItemInChannel(channelid, base64infohash)61 if not consinstent:62 msg = 'Infohash %s not found in my channel. Rejecting subtitle' % base64infohash63 if DEBUG:64 print >> sys.stderr, msg65 raise RichMetadataException(msg)66 try:67 filepath = self.subtitlesHandler.copyToSubtitlesFolder(pathToSrtSubtitle, self.my_permid, infohash, lang)68 except Exception as e:69 if DEBUG:70 print >> sys.stderr, 'Failed to read and copy subtitle to appropriate folder: %s' % str(e)71 metadataDTO = self.richMetadata_db.getMetadata(self.my_permid, infohash)72 if metadataDTO is None:73 metadataDTO = MetadataDTO(self.my_permid, infohash)74 else:75 metadataDTO.resetTimestamp()76 newSubtitle = SubtitleInfo(lang, filepath)77 if newSubtitle.subtitleExists():78 newSubtitle.computeChecksum()79 else:80 msg = 'Inconsistency found. The subtitle was not published'81 if DEBUG:82 print >> sys.stderr, msg83 raise RichMetadataException(msg)84 metadataDTO.addSubtitle(newSubtitle)85 metadataDTO.sign(self.my_keypair)86 self.richMetadata_db.insertMetadata(metadataDTO)87 def retrieveSubtitleContent(self, channel, infohash, subtitleInfo, callback = None):88 if subtitleInfo.subtitleExists():89 if subtitleInfo.verifyChecksum():90 callback(subtitleInfo)91 return92 if DEBUG:93 print >> sys.stderr, 'Subtitle is locally available but has invalid checksum. Issuing another download'94 subtitleInfo.path = None95 languages = [subtitleInfo.lang]96 def call_me_when_subtitle_arrives(listOfLanguages):97 if callback is not None:98 sub = self.richMetadata_db.getSubtitle(channel, infohash, listOfLanguages[0])99 callback(sub)100 self._queryPeersForSubtitles(channel, infohash, languages, call_me_when_subtitle_arrives)101 def retrieveMultipleSubtitleContents(self, channel, infohash, listOfSubInfos, callback = None):102 languages = []103 locallyAvailableSubs = []104 for subtitleInfo in listOfSubInfos:105 if subtitleInfo.checksum is None:106 if DEBUG:107 print >> sys.stderr, 'No checksum for subtitle %s. Skipping it in the request' % subtitleInfo108 continue109 if subtitleInfo.subtitleExists():110 if subtitleInfo.verifyChecksum():111 locallyAvailableSubs.append(subtitleInfo)112 continue113 else:114 if DEBUG:115 print >> sys.stderr, 'Subtitle is locally available but has invalid checksum. Issuing another download'116 subtitleInfo.path = None117 languages.append(subtitleInfo.lang)118 if len(locallyAvailableSubs) > 0 and callback is not None:119 callback(locallyAvailableSubs)120 def call_me_when_subtitles_arrive(listOfLanguages):121 if callback is not None:122 subInfos = list()123 allSubtitles = self.richMetadata_db.getAllSubtitles(channel, infohash)124 for lang in listOfLanguages:125 subInfos.append(allSubtitles[lang])126 callback(subInfos)127 if len(languages) > 0:128 self._queryPeersForSubtitles(channel, infohash, languages, call_me_when_subtitles_arrive)129 def _queryPeersForSubtitles(self, channel, infohash, languages, callback):130 def task():131 bitmask = self.langUtility.langCodesToMask(languages)132 if not bitmask > 0:133 if DEBUG:134 print >> sys.stderr, 'Will not send a request for 0 subtitles'135 return136 peers_to_query = self._peersHaveManager.getPeersHaving(channel, infohash, bitmask)137 for peer in peers_to_query:138 self.subtitlesHandler.sendSubtitleRequest(peer, channel, infohash, languages, callback)139 self._ol_bridge.add_task(task)140 def runDBConsinstencyRoutine(self):141 result = self.richMetadata_db.getAllLocalSubtitles()142 for channel in result:143 for infohash in result[channel]:144 for subInfo in result[channel][infohash]:145 if not subInfo.subtitleExists():146 if channel == self.my_permid:147 metadataDTO = self.richMetadata_db.getMetadata(channel, infohash)148 metadataDTO.removeSubtitle(subInfo.lang)149 metadataDTO.sign(self.my_keypair)150 self.richMetadata_db.insertMetadata(metadataDTO)151 else:...
views.py
Source:views.py
...92 for subtitle in media.subtitle_files:93 if subtitle["id"] == id:94 path = subtitle["filepath"]95 text = ""96 value = open_subtitle(path)97 text, status = value[0], value[1]98 if status == True :99 form = forms.CustomizeSubtitlesForm(request.form,100 subtitle=text)101 if request.method == 'POST' and form.validate():102 subtitle_data = form.subtitle.data103 status = save_subtitle(path,subtitle_data)104 if status == True:105 messages.add_message(106 request,107 messages.SUCCESS,108 ("Subtitle file changed!!!"))109 return redirect(request,110 location=media.url_for_self(request.urlgen))111 else :112 messages.add_message(113 request,114 messages.ERROR,115 ("Couldn't edit the subtitles!!!"))116 return redirect(request,117 location=media.url_for_self(request.urlgen))...
default.py
Source:default.py
1# -*- coding: utf-8 -*- 2import os3import os.path4import sys5import xbmc6import xbmcgui7import xbmcaddon8import time9import urllib10import urllib211import base6412import hashlib13TRANSLATED_SUBTITLE_FILE_NAME = "translatedSubtitle.srt"14PLUGIN_SUBTITLE_FILENAME = "temp_sub.en.srt"15PLUGIN_SUBTITLE_PATH = xbmc.translatePath('special://masterprofile/addon_data/script.xbmc.subtitles/sub_stream/temp_sub.en.srt')16TRANSLATING_TEXT = 'Translating...'17QUICK_TRANSLATE_URL ='https://explain.cc/app/quickSubtitleTranslate'18HEAD = 'Explain.CC'19TRANSLATED_SUBTITLE_FILENAME = xbmc.translatePath('special://masterprofile/addon_data/translatedSubtitle.srt')20EMPTY_STRING = ""21cachedSubtitle = ""22def isPluginSubtitles(subtitlesName):23 return PLUGIN_SUBTITLE_FILENAME == subtitlesName24def isTranslatedSubtitles(subtitlesName):25 return TRANSLATED_SUBTITLE_FILE_NAME == subtitlesName26 27def readFile(path) :28 print path # Bug on ubuntu, can't see the file.29 print os.path.isfile(path)30 if os.path.isfile(path) :31 f = open(path,'r')32 content = f.read()33 return content34 return ""35def writeFile(absoluteFilename, content) :36 f = open(absoluteFilename,'w')37 f.write(content)38 f.close()39def saveSubtitles(content) :40 print TRANSLATED_SUBTITLE_FILENAME41 writeFile(TRANSLATED_SUBTITLE_FILENAME, content)42def getSubtitleContentFromPluginFile() :43 return readFile(PLUGIN_SUBTITLE_PATH)44def getTranslatedSubtitleContent() :45 return readFile(TRANSLATED_SUBTITLE_FILENAME)46def quickSubtitleTranslate(subtitle) :47 popup = xbmcgui.DialogProgress()48 popup.create(HEAD, TRANSLATING_TEXT)49 response = EMPTY_STRING50 try:51 request = urllib2.Request(QUICK_TRANSLATE_URL)52 request.add_header("Authorization",getBasicAuthentication())53 params = urllib.urlencode({'subtitle': subtitle})54 response = urllib2.urlopen(request, params).read()55 print response;56 except Exception as inst:57 popup.close()58 xbmc.executebuiltin('Notification(Explain.CC,%s,20000)' % str(inst))59 popup.close()60 return response61def setTranslatedSubtitle(subtitle) :62 translatedSubtitle = quickSubtitleTranslate(subtitle)63 saveSubtitles(translatedSubtitle)64 player.setSubtitles(TRANSLATED_SUBTITLE_FILENAME)65 return translatedSubtitle66def saveSubtitleInCache(subtitle) :67 global cachedSubtitle68 cachedSubtitle = subtitle69def isUserAgreeToTranslateSubtitles() :70 dialog = xbmcgui.Dialog()71 return dialog.yesno(HEAD, 'Do you want translate subtitles ?')72def getBasicAuthentication() :73 addon = xbmcaddon.Addon()74 login = addon.getSetting('login')75 password = addon.getSetting('password')76 print hashlib.md5(login+password).hexdigest()77 auth = base64.encodestring('%s:%s' % (login, hashlib.md5(login+password).hexdigest())).replace('\n','')78 return 'Basic %s' % auth79def readSubtitle(subtitleName) :80 if isPluginSubtitles(subtitleName) :81 subtitle = getSubtitleContentFromPluginFile()82 elif isTranslatedSubtitles(subtitleName) :83 subtitle = getTranslatedSubtitleContent()84 else :85 subtitle = readFile(subtitleName)86 return subtitle87def isSubtitleChanged(subtitleName) :88 print len(readSubtitle(subtitleName))89 print len(cachedSubtitle)90 return readSubtitle(subtitleName) != cachedSubtitle91player = xbmc.Player()92while(1):93 time.sleep(2)94 if player.isPlayingVideo() and player.getSubtitles() :95 subtitleName = player.getSubtitles()96 if isSubtitleChanged(subtitleName) :97 subtitle = readSubtitle(subtitleName)98 if isUserAgreeToTranslateSubtitles() :99 subtitle = setTranslatedSubtitle(subtitle)...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!