def workOnMovie(movieName,subtitleName): """ make sound Segmentation for the whole movie by its subtitle frames Args: movieName(string) - name of the movie subtitleName(string) - name of subtitle file (usually .srt) Return: None """ # print(subtitleName) # print("\\".join(fileDirectorylist[:len(fileDirectorylist)-1])) index,timePeriods,SubText = Subtitle.extractSubtitleData(subtitleName) subtitleChunks = Subtitle.manupilateSubtitleData(index,timePeriods,SubText) Subtitle.saveSubtitleData(subtitleName,subtitleChunks) fileDirectorylist = movieName.split(movieName[len(movieName)-4:])[0].split("\\") # get full path as a list fileDirectory = "\\".join(fileDirectorylist[:len(fileDirectorylist)-1]) # get only the directory segmentsDir = fileDirectory + "\Segments" # segments folder path within the movie directory try: os.mkdir(segmentsDir) # create segments folder except FileExistsError: pass segmentsDir = segmentsDir.replace("\\","\\\\") # path issues ( may be fixed later) fileDirectory = fileDirectory.replace("\\","\\\\") # same as above idx = 0 # keep count of the segments for naming the files for segment in subtitleChunks: Sound.soundSegment(segment[0],segment[2],movieName,"segment"+str(idx)+".wav",fileDirectory,segmentsDir) idx += 1
def __init__(self, tvs, season, episode): self.tvs = tvs self.season = season self.episode = episode if tvs == 'G' or tvs == 'g': self.subDir = self.dirFeaturesGoT self.subtlDir = self.subtlDir + 'GoT/English/GameOfThrones.' self.saveClstResult = self.saveClstResult + 'GoT_' GoT = True elif tvs == 'B' or tvs == 'b': self.subDir = self.dirFeaturesBB self.subtlDir = self.subtlDir + 'BB/English/BreakingBad.' self.saveClstResult = self.saveClstResult + 'BB_' GoT = False else: print('you did not choose a TV-Series! bye bye') self.Season = "Season0" + str(season) self.Episode = ("Episode" + str(episode)) if int(episode) >= 10 else ("Episode0" + str(episode)) self.fileName = self.Season + '.' + self.Episode self.subtlFile = self.subtlDir + self.fileName + '.en.srt' self.saveClstResult = self.saveClstResult + self.Season + 'Result.ixt' print('You have chosen :') if GoT == True: print('Tv-Series: Game of Thrones') else: print('Tv-Series: Breaking bad') print('Season: ', self.season) print('Episode:', self.episode) print('Subtile File : ', self.subtlFile) self.sub = sb.Subtitle(self.subtlFile)
def extract_frames(path_to_folder, quote_search_text): ''' Extracts the frame from the video and the subtitle, and saves them in the frames folder The names of the frames are just the names of the quote_search_text list's index so we know what texts hit and what didnt hit in the subtitle file. ''' basepath = Path(path_to_folder) files_in_basepath = list(basepath.iterdir()) for h, k in enumerate(quote_search_text): for _, item in enumerate(files_in_basepath): found = 0 if item.suffix == '.srt': path_to_vid = str(item).strip('.srt') + '.mkv' found = sb.search_in_srt(item, k) with open(item, 'r', errors='ignore') as f: all_subs = f.readlines() if found: timestamp = sb.find_timestamp(all_subs, found) if timestamp == []: break print(timestamp) video = cv2.VideoCapture(path_to_vid) print(path_to_vid) fps = video.get(cv2.CAP_PROP_FPS) fps = round(fps, 2) print(fps) frame_no = round(( (timestamp[0] * 60 + timestamp[1]) * 60 + timestamp[2]) * fps + (timestamp[3] / 1000) * fps) print(frame_no) video.set(1, frame_no) success, image = video.read() try: cv2.imwrite( os.path.join(path_to_folder, f"Frames/{h}.jpg"), image) except: print('some error') break
def do_GET(self): global g_param try: dprint(__name__, 2, "http request header:\n{0}", self.headers) dprint(__name__, 2, "http request path:\n{0}", self.path) # check for PMS address PMSaddress = '' pms_end = self.path.find(')') if self.path.startswith('/PMS(') and pms_end > -1: PMSaddress = urllib.unquote_plus(self.path[5:pms_end]) self.path = self.path[pms_end + 1:] # break up path, separate PlexConnect options # clean path needed for filetype decoding parts = re.split( r'[?&]', self.path, 1) # should be '?' only, but we do some things different :-) if len(parts) == 1: self.path = parts[0] options = {} query = '' else: self.path = parts[0] # break up query string options = {} query = '' parts = parts[1].split('&') for part in parts: if part.startswith('PlexConnect'): # get options[] opt = part.split('=', 1) if len(opt) == 1: options[opt[0]] = '' else: options[opt[0]] = urllib.unquote(opt[1]) else: # recreate query string (non-PlexConnect) - has to be merged back when forwarded if query == '': query = '?' + part else: query += '&' + part # get aTV language setting options['aTVLanguage'] = Localize.pickLanguage( self.headers.get('Accept-Language', 'en')) query = query.replace("yyltyy", "<").replace("yygtyy", ">") # add client address - to be used in case UDID is unknown if 'X-Forwarded-For' in self.headers: options['aTVAddress'] = self.headers['X-Forwarded-For'].split( ',', 1)[0] else: options['aTVAddress'] = self.client_address[0] # get aTV hard-/software parameters options['aTVFirmwareVersion'] = self.headers.get( 'X-Apple-TV-Version', '5.1') options['aTVScreenResolution'] = self.headers.get( 'X-Apple-TV-Resolution', '720') dprint(__name__, 2, "pms address:\n{0}", PMSaddress) dprint(__name__, 2, "cleaned path:\n{0}", self.path) dprint(__name__, 2, "PlexConnect options:\n{0}", options) dprint(__name__, 2, "additional arguments:\n{0}", query) if 'User-Agent' in self.headers and \ 'AppleTV' in self.headers['User-Agent']: # recieve simple logging messages from the ATV if 'PlexConnectATVLogLevel' in options: dprint('ATVLogger', int(options['PlexConnectATVLogLevel']), options['PlexConnectLog']) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() return # serve "*.cer" - Serve up certificate file to atv if self.path.endswith(".cer"): dprint(__name__, 1, "serving *.cer: " + self.path) if g_param['CSettings'].getSetting('certfile').startswith( '.'): # relative to current path cfg_certfile = sys.path[0] + sep + g_param[ 'CSettings'].getSetting('certfile') else: # absolute path cfg_certfile = g_param['CSettings'].getSetting( 'certfile') cfg_certfile = path.normpath(cfg_certfile) cfg_certfile = path.splitext(cfg_certfile)[0] + '.cer' try: f = open(cfg_certfile, "rb") except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) return self.sendResponse(f.read(), 'text/xml', False) f.close() return # serve .js files to aTV # application, main: ignore path, send /assets/js/application.js # otherwise: path should be '/js', send /assets/js/*.js dirname = path.dirname(self.path) basename = path.basename(self.path) if basename in ("application.js", "main.js", "javascript-packed.js", "bootstrap.js") or \ basename.endswith(".js") and dirname == '/js': if basename in ("main.js", "javascript-packed.js", "bootstrap.js"): basename = "application.js" dprint(__name__, 1, "serving /js/{0}", basename) JS = JSConverter(basename, options) self.sendResponse(JS, 'text/javascript', True) return # proxy phobos.apple.com to support PlexConnect main icon if "a1.phobos.apple.com" in self.headers['Host']: resource = self.headers['Host'] + self.path icon = g_param['CSettings'].getSetting('icon') if basename.startswith(icon): icon_res = basename[len( icon ):] # cut string from settings, keeps @720.png/@1080.png resource = sys.path[0] + '/assets/icons/icon' + icon_res dprint( __name__, 1, "serving " + self.headers['Host'] + self.path + " with " + resource) r = open(resource, "rb") else: r = urllib.urlopen('http://' + resource) self.sendResponse(r.read(), 'image/png', False) r.close() return # serve "*.jpg" - thumbnails for old-style mainpage if self.path.endswith(".jpg"): dprint(__name__, 1, "serving *.jpg: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.sendResponse(f.read(), 'image/jpeg', False) f.close() return # serve "*.png" - only png's support transparent colors if self.path.endswith(".png"): dprint(__name__, 1, "serving *.png: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.sendResponse(f.read(), 'image/png', False) f.close() return # serve subtitle file - transcoded to aTV subtitle json if 'PlexConnect' in options and \ options['PlexConnect']=='Subtitle': dprint(__name__, 1, "serving subtitle: " + self.path) XML = Subtitle.getSubtitleJSON(PMSaddress, self.path + query, options) self.sendResponse(XML, 'application/json', True) return # get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds if True: dprint(__name__, 1, "serving .xml: " + self.path) XML = XMLConverter.XML_PMS2aTV(PMSaddress, self.path + query, options) self.sendResponse(XML, 'text/xml', True) return """ # unexpected request self.send_error(403,"Access denied: %s" % self.path) """ else: """ Added Up Page for docker helthcheck self.send_error(403,"Not Serving Client %s" % self.client_address[0]) """ dprint(__name__, 1, "serving *.html: " + self.path) f = open(sys.path[0] + sep + "assets/templates/up.html") self.sendResponse(f.read(), 'text/html', False) f.close() except IOError: dprint(__name__, 0, 'File Not Found:\n{0}', traceback.format_exc()) self.send_error(404, "File Not Found: %s" % self.path) except: dprint(__name__, 0, 'Internal Server Error:\n{0}', traceback.format_exc()) self.send_error(500, "Internal Server Error: %s" % self.path)
def do_GET(self): global g_param try: dprint(__name__, 2, "http request header:\n{0}", self.headers) dprint(__name__, 2, "http request path:\n{0}", self.path) # check for PMS address PMSaddress = '' pms_end = self.path.find(')') if self.path.startswith('/PMS(') and pms_end>-1: PMSaddress = urllib.unquote_plus(self.path[5:pms_end]) self.path = self.path[pms_end+1:] # break up path, separate PlexConnect options # clean path needed for filetype decoding parts = re.split(r'[?&]', self.path, 1) # should be '?' only, but we do some things different :-) if len(parts)==1: self.path = parts[0] options = {} query = '' else: self.path = parts[0] # break up query string options = {} query = '' parts = parts[1].split('&') for part in parts: if part.startswith('PlexConnect'): # get options[] opt = part.split('=', 1) if len(opt)==1: options[opt[0]] = '' else: options[opt[0]] = urllib.unquote(opt[1]) else: # recreate query string (non-PlexConnect) - has to be merged back when forwarded if query=='': query = '?' + part else: query += '&' + part # get aTV language setting options['aTVLanguage'] = Localize.pickLanguage(self.headers.get('Accept-Language', 'en')) # add client address - to be used in case UDID is unknown if 'X-Forwarded-For' in self.headers: options['aTVAddress'] = self.headers['X-Forwarded-For'].split(',', 1)[0] else: options['aTVAddress'] = self.client_address[0] # get aTV hard-/software parameters options['aTVFirmwareVersion'] = self.headers.get('X-Apple-TV-Version', '5.1') options['aTVScreenResolution'] = self.headers.get('X-Apple-TV-Resolution', '720') dprint(__name__, 2, "pms address:\n{0}", PMSaddress) dprint(__name__, 2, "cleaned path:\n{0}", self.path) dprint(__name__, 2, "PlexConnect options:\n{0}", options) dprint(__name__, 2, "additional arguments:\n{0}", query) if 'User-Agent' in self.headers and \ 'AppleTV' in self.headers['User-Agent']: # recieve simple logging messages from the ATV if 'PlexConnectATVLogLevel' in options: dprint('ATVLogger', int(options['PlexConnectATVLogLevel']), options['PlexConnectLog']) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() return # serve "*.cer" - Serve up certificate file to atv if self.path.endswith(".cer"): dprint(__name__, 1, "serving *.cer: "+self.path) if g_param['CSettings'].getSetting('certfile').startswith('.'): # relative to current path cfg_certfile = sys.path[0] + sep + g_param['CSettings'].getSetting('certfile') else: # absolute path cfg_certfile = g_param['CSettings'].getSetting('certfile') cfg_certfile = path.normpath(cfg_certfile) cfg_certfile = path.splitext(cfg_certfile)[0] + '.cer' try: f = open(cfg_certfile, "rb") except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) return self.sendResponse(f.read(), 'text/xml', False) f.close() return # serve .js files to aTV # application, main: ignore path, send /assets/js/application.js # otherwise: path should be '/js', send /assets/js/*.js dirname = path.dirname(self.path) basename = path.basename(self.path) if basename in ("application.js", "main.js", "javascript-packed.js", "bootstrap.js") or \ basename.endswith(".js") and dirname == '/js': if basename in ("main.js", "javascript-packed.js", "bootstrap.js"): basename = "application.js" dprint(__name__, 1, "serving /js/{0}", basename) JS = JSConverter(basename, options) self.sendResponse(JS, 'text/javascript', True) return # serve "*.jpg" - thumbnails for old-style mainpage if self.path.endswith(".jpg"): dprint(__name__, 1, "serving *.jpg: "+self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.sendResponse(f.read(), 'image/jpeg', False) f.close() return # serve "*.png" - only png's support transparent colors if self.path.endswith(".png"): dprint(__name__, 1, "serving *.png: "+self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.sendResponse(f.read(), 'image/png', False) f.close() return # serve subtitle file - transcoded to aTV subtitle json if 'PlexConnect' in options and \ options['PlexConnect']=='Subtitle': dprint(__name__, 1, "serving subtitle: "+self.path) XML = Subtitle.getSubtitleJSON(PMSaddress, self.path + query, options) self.sendResponse(XML, 'application/json', True) return # get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds if True: dprint(__name__, 1, "serving .xml: "+self.path) XML = XMLConverter.XML_PMS2aTV(PMSaddress, self.path + query, options) self.sendResponse(XML, 'text/xml', True) return """ # unexpected request self.send_error(403,"Access denied: %s" % self.path) """ else: self.send_error(403,"Not Serving Client %s" % self.client_address[0]) except IOError: dprint(__name__, 0, 'File Not Found:\n{0}', traceback.format_exc()) self.send_error(404,"File Not Found: %s" % self.path) except: dprint(__name__, 0, 'Internal Server Error:\n{0}', traceback.format_exc()) self.send_error(500,"Internal Server Error: %s" % self.path)
def do_GET(self): global g_param try: dprint(__name__, 2, "http request header:\n{0}", self.headers) dprint(__name__, 2, "http request path:\n{0}", self.path) # check for PMS address PMSaddress = '' pms_end = self.path.find(')') if self.path.startswith('/PMS(') and pms_end > -1: PMSaddress = urllib.unquote_plus(self.path[5:pms_end]) self.path = self.path[pms_end + 1:] # break up path, separate PlexConnect options options = {} while True: cmd_start = self.path.find('&PlexConnect') cmd_end = self.path.find('&', cmd_start + 1) if cmd_start == -1: break if cmd_end > -1: cmd = self.path[cmd_start + 1:cmd_end] self.path = self.path[:cmd_start] + self.path[cmd_end:] else: cmd = self.path[cmd_start + 1:] self.path = self.path[:cmd_start] parts = cmd.split('=', 1) if len(parts) == 1: options[parts[0]] = '' else: options[parts[0]] = urllib.unquote(parts[1]) # break up path, separate additional arguments # clean path needed for filetype decoding... has to be merged back when forwarded. parts = self.path.split('?', 1) if len(parts) == 1: args = '' else: self.path = parts[0] args = '?' + parts[1] # get aTV language setting options['aTVLanguage'] = Localize.pickLanguage( self.headers.get('Accept-Language', 'en')) # add client address - to be used in case UDID is unknown options['aTVAddress'] = self.client_address[0] # get aTV hard-/software parameters options['aTVFirmwareVersion'] = self.headers.get( 'X-Apple-TV-Version', '5.1') options['aTVScreenResolution'] = self.headers.get( 'X-Apple-TV-Resolution', '720') dprint(__name__, 2, "pms address:\n{0}", PMSaddress) dprint(__name__, 2, "cleaned path:\n{0}", self.path) dprint(__name__, 2, "PlexConnect options:\n{0}", options) dprint(__name__, 2, "additional arguments:\n{0}", args) if 'User-Agent' in self.headers and \ 'AppleTV' in self.headers['User-Agent']: # recieve simple logging messages from the ATV if 'PlexConnectATVLogLevel' in options: dprint('ATVLogger', int(options['PlexConnectATVLogLevel']), options['PlexConnectLog']) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() return # serve "*.cer" - Serve up certificate file to atv if self.path.endswith(".cer"): dprint(__name__, 1, "serving *.cer: " + self.path) if g_param['CSettings'].getSetting('certfile').startswith( '.'): # relative to current path cfg_certfile = sys.path[0] + sep + g_param[ 'CSettings'].getSetting('certfile') else: # absolute path cfg_certfile = g_param['CSettings'].getSetting( 'certfile') cfg_certfile = path.normpath(cfg_certfile) cfg_certfile = path.splitext(cfg_certfile)[0] + '.cer' try: f = open(cfg_certfile, "rb") except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) return self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() self.wfile.write(f.read()) f.close() return # serve .js files to aTV # application, main: ignore path, send /assets/js/application.js # otherwise: path should be '/js', send /assets/js/*.js dirname = path.dirname(self.path) basename = path.basename(self.path) if basename in ("application.js", "main.js", "javascript-packed.js") or \ basename.endswith(".js") and dirname == '/js': if basename in ("main.js", "javascript-packed.js"): basename = "application.js" dprint(__name__, 1, "serving /js/{0}", basename) JS = JSConverter(basename, options) self.send_response(200) self.send_header('Content-type', 'text/javascript') self.end_headers() self.wfile.write(JS) return # serve "*.jpg" - thumbnails for old-style mainpage if self.path.endswith(".jpg"): dprint(__name__, 1, "serving *.jpg: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return # serve "*.png" - only png's support transparent colors if self.path.endswith(".png"): dprint(__name__, 1, "serving *.png: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header('Content-type', 'image/png') self.end_headers() self.wfile.write(f.read()) f.close() return # serve subtitle file - transcoded to aTV subtitle json if 'PlexConnect' in options and \ options['PlexConnect']=='Subtitle': dprint(__name__, 1, "serving subtitle: " + self.path) XML = Subtitle.getSubtitleJSON(PMSaddress, self.path + args, options) self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(XML) return # get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds if True: dprint(__name__, 1, "serving .xml: " + self.path) XML = XMLConverter.XML_PMS2aTV(PMSaddress, self.path + args, options) self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() self.wfile.write(XML) return """ # unexpected request self.send_error(403,"Access denied: %s" % self.path) """ else: self.send_error( 403, "Not Serving Client %s" % self.client_address[0]) except IOError: self.send_error(404, "File Not Found: %s" % self.path)
def analyse(self, subtitleFile, wordFrequencyDistribution): global currentSubtitle global nextSubtitle firstRun = True try: subFile = open(subtitleFile) except Exception: return 0 # Get rid of number of lines in file symbol subFile.readline() lineNumber = 0 firstRun = True while (True): subNumber = subFile.readline() subNumber = subNumber.strip() if ((subNumber == '') or (subNumber.isspace())): break else: lineNumber += 1 timeSub = subFile.readline() if (timeSub == None): raise ValueError('Error parsing time subtitle') subtitleString = '' s = None newSubtitleFound = False nextSubtitleText = '' while (True): s = subFile.readline() if ((s == '') or (s.isspace())): break else: if ((s.strip().startswith('-')) and (len(subtitleString) > 0)): newSubtitleFound = True nextSubtitleText = s else: subtitleString += s + ' ' startTime = int(self.parse(timeSub.split('-->')[0])) stopTime = int(self.parse(timeSub.split('-->')[1])) #print(startTime) #print(stopTime) number = int(subNumber) nextSubtitle = Subtitle.Subtitle(number, startTime, stopTime, subtitleString) if (firstRun == True): firstRun = False currentSubtitle = nextSubtitle else: self.addToFrequencyDistributionWithFreq( wordFrequencyDistribution) #self.addToFrequencyDistributionEmpty() if (newSubtitleFound == True): nextSubtitle = Subtitle.Subtitle( number, startTime, stopTime, nextSubtitleText) self.addToFrequencyDistributionWithFreq( wordFrequencyDistribution)
def do_GET(self): global g_param try: dprint(__name__, 2, "http request header:\n{0}", self.headers) dprint(__name__, 2, "http request path:\n{0}", self.path) # check for PMS address PMSaddress = "" pms_end = self.path.find(")") if self.path.startswith("/PMS(") and pms_end > -1: PMSaddress = urllib.unquote_plus(self.path[5:pms_end]) self.path = self.path[pms_end + 1 :] # break up path, separate PlexConnect options # clean path needed for filetype decoding parts = re.split(r"[?&]", self.path, 1) # should be '?' only, but we do some things different :-) if len(parts) == 1: self.path = parts[0] options = {} query = "" else: self.path = parts[0] # break up query string options = {} query = "" parts = parts[1].split("&") for part in parts: if part.startswith("PlexConnect"): # get options[] opt = part.split("=", 1) if len(opt) == 1: options[opt[0]] = "" else: options[opt[0]] = urllib.unquote(opt[1]) else: # recreate query string (non-PlexConnect) - has to be merged back when forwarded if query == "": query = "?" + part else: query += "&" + part # get aTV language setting options["aTVLanguage"] = Localize.pickLanguage(self.headers.get("Accept-Language", "en")) # add client address - to be used in case UDID is unknown if "X-Forwarded-For" in self.headers: options["aTVAddress"] = self.headers["X-Forwarded-For"].split(",", 1)[0] else: options["aTVAddress"] = self.client_address[0] # get aTV hard-/software parameters options["aTVFirmwareVersion"] = self.headers.get("X-Apple-TV-Version", "5.1") options["aTVScreenResolution"] = self.headers.get("X-Apple-TV-Resolution", "720") dprint(__name__, 2, "pms address:\n{0}", PMSaddress) dprint(__name__, 2, "cleaned path:\n{0}", self.path) dprint(__name__, 2, "PlexConnect options:\n{0}", options) dprint(__name__, 2, "additional arguments:\n{0}", query) if "User-Agent" in self.headers and "AppleTV" in self.headers["User-Agent"]: # recieve simple logging messages from the ATV if "PlexConnectATVLogLevel" in options: dprint("ATVLogger", int(options["PlexConnectATVLogLevel"]), options["PlexConnectLog"]) self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() return # serve "*.cer" - Serve up certificate file to atv if self.path.endswith(".cer"): dprint(__name__, 1, "serving *.cer: " + self.path) if g_param["CSettings"].getSetting("certfile").startswith("."): # relative to current path cfg_certfile = sys.path[0] + sep + g_param["CSettings"].getSetting("certfile") else: # absolute path cfg_certfile = g_param["CSettings"].getSetting("certfile") cfg_certfile = path.normpath(cfg_certfile) cfg_certfile = path.splitext(cfg_certfile)[0] + ".cer" try: f = open(cfg_certfile, "rb") except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) return self.send_response(200) self.send_header("Content-type", "text/xml") self.end_headers() self.wfile.write(f.read()) f.close() return # serve .js files to aTV # application, main: ignore path, send /assets/js/application.js # otherwise: path should be '/js', send /assets/js/*.js dirname = path.dirname(self.path) basename = path.basename(self.path) if ( basename in ("application.js", "main.js", "javascript-packed.js", "bootstrap.js") or basename.endswith(".js") and dirname == "/js" ): if basename in ("main.js", "javascript-packed.js", "bootstrap.js"): basename = "application.js" dprint(__name__, 1, "serving /js/{0}", basename) JS = JSConverter(basename, options) self.send_response(200) self.send_header("Content-type", "text/javascript") self.end_headers() self.wfile.write(JS) return # serve "*.jpg" - thumbnails for old-style mainpage if self.path.endswith(".jpg"): dprint(__name__, 1, "serving *.jpg: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header("Content-type", "image/jpeg") self.end_headers() self.wfile.write(f.read()) f.close() return # serve "*.png" - only png's support transparent colors if self.path.endswith(".png"): dprint(__name__, 1, "serving *.png: " + self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header("Content-type", "image/png") self.end_headers() self.wfile.write(f.read()) f.close() return # serve subtitle file - transcoded to aTV subtitle json if "PlexConnect" in options and options["PlexConnect"] == "Subtitle": dprint(__name__, 1, "serving subtitle: " + self.path) XML = Subtitle.getSubtitleJSON(PMSaddress, self.path + query, options) self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(XML) return # get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds if True: dprint(__name__, 1, "serving .xml: " + self.path) XML = XMLConverter.XML_PMS2aTV(PMSaddress, self.path + query, options) self.send_response(200) self.send_header("Content-type", "text/xml") self.end_headers() self.wfile.write(XML) return """ # unexpected request self.send_error(403,"Access denied: %s" % self.path) """ else: self.send_error(403, "Not Serving Client %s" % self.client_address[0]) except IOError: self.send_error(404, "File Not Found: %s" % self.path)
def analyse(self, subtitleFile): global currentSubtitle global nextSubtitle global mostCommonWords global responseGroupId print(responseGroupId) firstRun = True try: print('Attempting to open ' + subtitleFile) subFile = open(subtitleFile, 'r') #subFile = codecs.open(subtitleFile, 'r', encoding=encodingEstimate) except Exception as e: print('Could not open, wrong encoding perhaps?') firstRun = True while (True): try: subNumber = subFile.readline() subNumber = subNumber.strip() if ((subNumber == '') or (subNumber.isspace()) or (not (subNumber.isdigit()))): break else: try: timeSub = subFile.readline() if (timeSub == None): raise ValueError('Error parsing time subtitle') subtitleString = '' s = None newSubtitleFound = False nextSubtitleText = '' while (True): s = subFile.readline() if ((s == '') or (s.isspace())): break else: if ((s.strip().startswith('-')) and (len(subtitleString) > 0)): newSubtitleFound = True nextSubtitleText = s else: subtitleString += s + ' ' startTime = int(self.parse(timeSub.split('-->')[0])) stopTime = int(self.parse(timeSub.split('-->')[1])) #print(startTime) #print(stopTime) number = int(subNumber) nextSubtitle = Subtitle.Subtitle( number, startTime, stopTime, subtitleString) if (firstRun == True): firstRun = False currentSubtitle = nextSubtitle else: self.checkSubtitlesAreOk() if (newSubtitleFound == True): nextSubtitle = Subtitle.Subtitle( number, startTime, stopTime, nextSubtitleText) self.checkSubtitlesAreOk() except Exception as e: print('Could not parse sub, exception was ' + str(e)) #return frequencyDistribution except Exception as e: print('Could not parse sub file, exception was ' + str(e))
def do_GET(self): global g_param try: dprint(__name__, 2, "http request header:\n{0}", self.headers) dprint(__name__, 2, "http request path:\n{0}", self.path) # check for PMS address PMSaddress = '' pms_end = self.path.find(')') if self.path.startswith('/PMS(') and pms_end>-1: PMSaddress = urllib.unquote_plus(self.path[5:pms_end]) self.path = self.path[pms_end+1:] # break up path, separate PlexConnect options options = {} while True: cmd_start = self.path.find('&PlexConnect') cmd_end = self.path.find('&', cmd_start+1) if cmd_start==-1: break if cmd_end>-1: cmd = self.path[cmd_start+1:cmd_end] self.path = self.path[:cmd_start] + self.path[cmd_end:] else: cmd = self.path[cmd_start+1:] self.path = self.path[:cmd_start] parts = cmd.split('=', 1) if len(parts)==1: options[parts[0]] = '' else: options[parts[0]] = urllib.unquote(parts[1]) # break up path, separate additional arguments # clean path needed for filetype decoding... has to be merged back when forwarded. parts = self.path.split('?', 1) if len(parts)==1: args = '' else: self.path = parts[0] args = '?'+parts[1] # get aTV language setting options['aTVLanguage'] = Localize.pickLanguage(self.headers.get('Accept-Language', 'en')) # add client address - to be used in case UDID is unknown options['aTVAddress'] = self.client_address[0] # get aTV hard-/software parameters options['aTVFirmwareVersion'] = self.headers.get('X-Apple-TV-Version', '5.1') options['aTVScreenResolution'] = self.headers.get('X-Apple-TV-Resolution', '720') dprint(__name__, 2, "pms address:\n{0}", PMSaddress) dprint(__name__, 2, "cleaned path:\n{0}", self.path) dprint(__name__, 2, "PlexConnect options:\n{0}", options) dprint(__name__, 2, "additional arguments:\n{0}", args) if 'User-Agent' in self.headers and \ 'AppleTV' in self.headers['User-Agent']: # serve the plex icon if self.headers['Host'] == 'a1.phobos.apple.com' and self.path.endswith(".png"): # possible icon basename = path.basename(self.path) iconname, ext = basename.rsplit('.', 1) dprint(__name__, 2, "serving icon {0}", iconname) name, rez = iconname.split('@') dprint(__name__, 2, "icon name: {0} at {1}", name, rez) hosticons = { 'www.icloud.com': 'Theater', 'atv.hbogo.com': 'HBOGo', 'atv.qello.com': 'QelloV2', 'appletv.app.hulu.com': 'huluplus', 'appletv.vevo.com': 'VevoV1', 'apps.sho.com': 'SmithsonianBlue', 'watchdisneyjunior.go.com': 'DisneyJR', 'watchdisneychannel.go.com': 'DisneyChannel_V2', 'watchdisneyxd.go.com': 'DisneyXD_V2', 'ssl.weather.com': 'weatherchannel' } if name == hosticons.get(g_param['HostToIntercept']): dprint(__name__, 2, "getting plex icon") f = open(sys.path[0] + sep + "assets" + sep + "thumbnails" + sep + "icon@" + rez + ".png", "rb") self.send_response(200) self.send_header('Content-type', 'image/png') self.end_headers() self.wfile.write(f.read()) f.close() return else: dprint(__name__, 2, "getting app icon") self.send_response(200) self.send_header('Content-type', 'image/png') self.end_headers() self.wfile.write(urllib.urlopen('http://' + self.headers['Host'] + self.path).read()) return elif self.headers['Host'] == 'a1.phobos.apple.com': # something other than an icon was requested self.send_response(200) self.send_header('Content-type', self.headers['Content-type']) self.end_headers() self.wfile.write(urllib.urlopen('http://' + self.headers['Host'] + self.path).read()) return # recieve simple logging messages from the ATV if 'PlexConnectATVLogLevel' in options: dprint('ATVLogger', int(options['PlexConnectATVLogLevel']), options['PlexConnectLog']) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() return # serve "*.cer" - Serve up certificate file to atv if self.path.endswith(".cer"): dprint(__name__, 1, "serving *.cer: "+self.path) if g_param['CSettings'].getSetting('certfile').startswith('.'): # relative to current path cfg_certfile = sys.path[0] + sep + g_param['CSettings'].getSetting('certfile') else: # absolute path cfg_certfile = g_param['CSettings'].getSetting('certfile') cfg_certfile = path.normpath(cfg_certfile) cfg_certfile = path.splitext(cfg_certfile)[0] + '.cer' try: f = open(cfg_certfile, "rb") except: dprint(__name__, 0, "Failed to access certificate: {0}", cfg_certfile) return self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() self.wfile.write(f.read()) f.close() return # serve .js files to aTV # application, main: ignore path, send /assets/js/application.js # otherwise: path should be '/js', send /assets/js/*.js dirname = path.dirname(self.path) basename = path.basename(self.path) if basename in ("application.js", "main.js", "javascript-packed.js") or \ basename.endswith(".js") and dirname == '/js': if basename in ("main.js", "javascript-packed.js"): basename = "application.js" dprint(__name__, 1, "serving /js/{0}", basename) JS = JSConverter(basename, options) self.send_response(200) self.send_header('Content-type', 'text/javascript') self.end_headers() self.wfile.write(JS) return # serve "*.jpg" - thumbnails for old-style mainpage if self.path.endswith(".jpg"): dprint(__name__, 1, "serving *.jpg: "+self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header('Content-type', 'image/jpeg') self.end_headers() self.wfile.write(f.read()) f.close() return # serve "*.png" - only png's support transparent colors if self.path.endswith(".png"): dprint(__name__, 1, "serving *.png: "+self.path) f = open(sys.path[0] + sep + "assets" + self.path, "rb") self.send_response(200) self.send_header('Content-type', 'image/png') self.end_headers() self.wfile.write(f.read()) f.close() return # serve subtitle file - transcoded to aTV subtitle json if 'PlexConnect' in options and \ options['PlexConnect']=='Subtitle': dprint(__name__, 1, "serving subtitle: "+self.path) XML = Subtitle.getSubtitleJSON(PMSaddress, self.path + args, options) self.send_response(200) self.send_header('Content-type', 'application/json') self.end_headers() self.wfile.write(XML) return # get everything else from XMLConverter - formerly limited to trailing "/" and &PlexConnect Cmds if True: dprint(__name__, 1, "serving .xml: "+self.path) XML = XMLConverter.XML_PMS2aTV(PMSaddress, self.path + args, options) self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() self.wfile.write(XML) return """ # unexpected request self.send_error(403,"Access denied: %s" % self.path) """ else: self.send_error(403,"Not Serving Client %s" % self.client_address[0]) except IOError: self.send_error(404,"File Not Found: %s" % self.path)