def convert_vtt_to_srt(dir): for vtt_file in glob.glob(os.path.join(dir, "*.vtt")): with open(os.path.splitext(vtt_file)[0] + '.srt', 'w') as srt: vtt = open(vtt_file, 'r') vttsub = vtt.read().decode('UTF-8') srtsub = SRTWriter().write(WebVTTReader().read(vttsub)) srt.write(srtsub.encode('UTF-8')) vtt.close() os.remove(vtt_file)
def run_pipeline(url=None, hmm=None, lm=None, dict=None, caption_format="webvtt", out_file=None): if url is None: raise Exception("No URL specified!") pipeline = Gst.parse_launch( "uridecodebin name=source ! audioconvert !" + " audioresample ! pocketsphinx name=asr !" + " fakesink" ) source = pipeline.get_by_name("source") source.set_property("uri", url) pocketsphinx = pipeline.get_by_name("asr") if hmm: pocketsphinx.set_property("hmm", hmm) if lm: pocketsphinx.set_property("lm", lm) if dict: pocketsphinx.set_property("dict", dict) bus = pipeline.get_bus() # Start playing pipeline.set_state(Gst.State.PLAYING) cap_set = CaptionSet() captions = [] # Wait until error or EOS while True: try: msg = bus.timed_pop(Gst.CLOCK_TIME_NONE) if msg: # if msg.get_structure(): # print(msg.get_structure().to_string()) if msg.type == Gst.MessageType.EOS: break struct = msg.get_structure() if struct and struct.get_name() == "pocketsphinx": if struct["final"]: c = Caption() c.start = struct["start_time"] / Gst.USECOND c.end = struct["end_time"] / Gst.USECOND c.nodes.append(CaptionNode.create_text(struct["hypothesis"])) captions.append(c) except KeyboardInterrupt: pipeline.send_event(Gst.Event.new_eos()) # Free resources pipeline.set_state(Gst.State.NULL) cap_set.set_captions("en-US", captions) writer = SRTWriter() if caption_format == "srt" else WebVTTWriter() caption_data = writer.write(cap_set) if out_file is not None: codecs.open(out_file, "w", "utf-8").write(caption_data) else: print(caption_data)
def play(url): try: params = utils.get_url(url) p = comm.get_program(params["program_id"]) listitem = xbmcgui.ListItem( label=p.get_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail, path=p.get_url() ) listitem.setInfo("video", p.get_xbmc_list_item()) if hasattr(listitem, "addStreamInfo"): listitem.addStreamInfo("audio", p.get_xbmc_audio_stream_info()) listitem.addStreamInfo("video", p.get_xbmc_video_stream_info()) player = xbmc.Player() # Pull subtitles if available if addon.getSetting("subtitles_enabled") == "true": if p.subtitle: utils.log("Enabling subtitles: %s" % p.subtitle) profile = addon.getAddonInfo("profile") subfilename = xbmc.translatePath(os.path.join(profile, "subtitle.srt")) profiledir = xbmc.translatePath(os.path.join(profile)) if not os.path.isdir(profiledir): os.makedirs(profiledir) dfxp_data = urllib2.urlopen(p.subtitle).read().decode("utf-8") if dfxp_data: f = open(subfilename, "w") dfxp_subtitle = DFXPReader().read(dfxp_data) srt_subtitle = SRTWriter().write(dfxp_subtitle) srt_unicode = srt_subtitle.encode("utf-8") f.write(srt_unicode) f.close() if hasattr(listitem, "setSubtitles"): # This function only supported from Kodi v14+ listitem.setSubtitles([subfilename]) # Play video utils.log("Attempting to play: %s" % p.get_title()) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem) # Enable subtitles for XBMC v13 if addon.getSetting("subtitles_enabled") == "true": if p.subtitle: if not hasattr(listitem, "setSubtitles"): while not player.isPlaying(): xbmc.sleep(100) # wait until video is being played player.setSubtitles(subfilename) except: utils.handle_error("Unable to play video")
def get(content_id, lang): args = { 'content_id': content_id } CClist = requests.get(api_url, params = args) CClink = etree.HTML(CClist.content).xpath('//transcripts/' + lang + '/text()')[0].replace('captions','captions_webvtt').replace('smi','vtt') origCC = requests.get(CClink) srtCC = SRTWriter().write(WebVTTReader().read(origCC.text)) srt_file = open(content_id + '.' + lang + '.srt', 'w') srt_file.write(srtCC.replace('\n', '\r\n').encode('utf-8')) srt_file.close() return 0
def download_subtitle(url, destination): if not url: return False r = requests.get(url) if not r.ok: return False reader = detect_format(r.text) if not reader: return False srt = SRTWriter().write(reader().read(r.text)) if xbmcvfs.exists(destination): xbmcvfs.delete(destination) f = xbmcvfs.File(destination, 'w') f.write(srt.encode("utf-8")) f.close() return True
def test_multiple_lines_for_one_sentence(self, samples_srt_same_time): caption_set = SRTReader().read(samples_srt_same_time) results = SRTWriter().write(caption_set) sentences = re.split(r"\d{2}:\d{2}:\d{2},\d{3} -->", results) sentences.pop(0) assert 3 == len(sentences)
def convert_subtitles(closedcaption): str_output = '' count = 0 for closedcaption_url, i in closedcaption: count = int(i) + 1 if closedcaption_url is not None: try: cc_content = common.smart_unicode( connection.getURL(closedcaption_url, connectiontype=0).replace(' 9137', '')) reader = detect_format(cc_content) if reader: str_output = common.smart_utf8(SRTWriter().write( reader().read(cc_content))) file = open( os.path.join(ustvpaths.DATAPATH, 'subtitle-%s.srt' % str(count)), 'w') file.write(str_output) str_output = '' file.close() else: print "Unknown sub type" except Exception, e: print "Exception with Subs: ", e
def convert_subtitles_to_srt(i: str, o: str): ext = os.path.splitext(i)[1] if ext == '.srt': import shutil shutil.copy(i, o) elif ext in ('.ttml', '.xml', '.dfxp', '.tt'): # TTML from media_management_scripts.support.ttml2srt import convert_to_srt convert_to_srt(i, o) else: # VTT, SCC, etc from pycaption import detect_format, SRTWriter subtitle_str = _read_file(i) reader = detect_format(subtitle_str) if reader: subtitle_str = SRTWriter().write(reader().read(subtitle_str)) with open(o, 'w') as file: file.write(subtitle_str) else: # Attempt to use FFMPEG from media_management_scripts.support.executables import ffmpeg from media_management_scripts.support.executables import execute_with_output args = [ ffmpeg(), '-loglevel', 'fatal', '-y', '-i', i, '-c:s', 'srt', o ] ret, output = execute_with_output(args) if ret != 0: raise Exception( 'Exception during subtitle conversion: {}'.format(output))
def _test_srt_to_scc_to_srt_conversion(self, srt_captions): captions_1 = SRTReader().read(srt_captions) scc_results = SCCWriter().write(captions_1) scc_captions = SCCReader().read(scc_results) srt_results = SRTWriter().write(scc_captions) captions_2 = SRTReader().read(srt_results) self.assertCaptionSetAlmostEquals(captions_1, captions_2, TOLERANCE_MICROSECONDS)
def _srt_gen_from_url(base_url, end_time=3660, verbose=True): dt = 60 t0 = 0 t1 = t0 + dt has_next = True first = True srt = '' last_end = 0.0 while has_next: if verbose: print('fetching captions from ' + base_url + '?t={}/{}'.format(t0, t1)) if first: first = False res = requests.get(base_url, params={'t': '{}/{}'.format(t0, t1)}) res.raise_for_status() srt = res.text.replace(u'\ufeff', '') else: res = requests.get(base_url, params={'t': '{}/{}'.format(t0, t1)}) res.raise_for_status() srt = res.text t0 = t1 + 1 t1 = t1 + dt has_next = t1 <= end_time if srt: cc = CaptionConverter() cc.read(srt, SRTReader()) captions = cc.captions.get_captions(lang='en-US') if first: last_end = captions[-1].end else: for caption in captions: caption.start += last_end caption.end += last_end last_end = captions[-1].end srt = cc.write(SRTWriter()) yield srt.replace('\n\n', ' \n\n') else: yield ''
def ttml2srt(ttml_file_path, srt_file_path=None): """Convert TTML subtitles to SubRip subtitles. Arguments: ttml_file_path {string} -- The path to the TTML file. srt_file_path {string} -- The path to the SubRip file. """ converter = CaptionConverter() with open(ttml_file_path, "r", encoding="utf8") as file: converter.read(file.read(), DFXPReader()) if srt_file_path is None: srt_file_path = ttml_file_path.replace(".xml", ".srt") with open(srt_file_path, "wb") as file: file.write(converter.write(SRTWriter()).encode("utf-8"))
def ttml2srt(ttml_file_path: str, srt_file_path: Optional[str] = None) -> None: """Convert TTML subtitles to SubRip subtitles. Arguments: ttml_file_path {string} -- The path to the TTML file. srt_file_path {string} -- The path to the SubRip file. """ file: Union[TextIO, BinaryIO] converter = CaptionConverter() encoding = Utils.detect_encoding(ttml_file_path) with open(ttml_file_path, "r", encoding=encoding) as file: converter.read(file.read(), DFXPReader()) if srt_file_path is None: srt_file_path = ttml_file_path.replace(".xml", ".srt") with open(srt_file_path, "wb") as file: file.write(converter.write(SRTWriter()).encode(encoding))
def sami2srt(sami_file_path: str, srt_file_path: Optional[str] = None) -> None: """Convert SAMI subtitles to SubRip subtitles. Arguments: sami_file_path {string} -- The path to the SAMI file. srt_file_path {string} -- The path to the SubRip file. """ file: Union[TextIO, BinaryIO] converter = CaptionConverter() encoding = Utils.detect_encoding(sami_file_path) with open(sami_file_path, "r", encoding=encoding) as file: converter.read(file.read(), SAMIReader()) if srt_file_path is None: srt_file_path = sami_file_path.replace(".smi", ".srt") with open(srt_file_path, "wb") as file: file.write(converter.write(SRTWriter()).encode(encoding)) Utils.remove_trailing_newlines(srt_file_path, encoding)
def get_subtitles(self, captions): subtitles = [] for idx, caption in enumerate(captions): try: r = self._session.get(caption['file']) reader = detect_format(r.text) srt = SRTWriter().write(reader().read(r.text)) except: log.debug('Failed to parse subtitle: {}'.format( caption['file'])) else: srtfile = xbmc.translatePath( 'special://temp/curiosity{}.{}.srt'.format( idx, caption['code'])).decode('utf-8') with codecs.open(srtfile, "w", "utf-8") as f: f.write(srt) subtitles.append(srtfile) return subtitles
new_captions = [] for s, sentence in enumerate(self.sentences): for c, caption in enumerate(sentence.captions): trans = match[s][c] new_caption = deepcopy(caption.raw_caption) new_caption.nodes = [CaptionNode.create_text(trans.strip())] new_captions.append(new_caption) # print(f'"{caption.raw_text}"', f'"{trans}"') new_caption_set = CaptionSet({'en': new_captions}) return new_caption_set input_file = Path("./sendung-vom-15112020-video-ut102~_type-webvtt.vtt") read_srt = WebVTTReader().read(input_file.read_text('UTF-8'), lang='de') sentence_manager = SentenceManager() for raw_caption in read_srt.get_captions('de'): caption = MyCaption(raw_caption) sentence_manager.add_caption(caption) # sentence_manager.finish() # print(sentence_manager) # sentence_manager.write_to_file(Path("./output.txt")) match = sentence_manager.match_translation_from_file( Path("./output_fixed.txt"), Path("./translated.txt")) new_caption_set = sentence_manager.new_caption_set_from_match(match) srt_output = SRTWriter().write(new_caption_set) print(srt_output) Path("./translated.srt").write_text(srt_output, 'UTF-8')
def test_dfxp_to_srt_conversion(self): results = SRTWriter().write(self.captions) self.assertTrue(isinstance(results, unicode)) self.assertSRTEquals(SAMPLE_SRT.decode(u'utf-8'), results)
def play(url): try: # Remove cookies.dat for Kodi < 17.0 - causes issues with playback addon = xbmcaddon.Addon() cookies_dat = xbmc.translatePath('special://home/cache/cookies.dat') if os.path.isfile(cookies_dat): os.remove(cookies_dat) p = classes.Program() p.parse_kodi_url(url) stream_data = comm.get_stream_url(p.get_house_number(), p.get_url()) stream_url = stream_data.get('stream_url') if not stream_url: utils.log('Not Playable: {0}'.format(repr(stream_data))) raise AussieAddonsException( 'Not available: {0}\n{1}'.format(stream_data.get('msg'), stream_data.get( 'availability'))) use_ia = addon.getSetting('USE_IA') == 'true' if use_ia: if addon.getSetting('IGNORE_DRM') == 'false': try: import drmhelper if not drmhelper.check_inputstream(drm=False): return except ImportError: utils.log("Failed to import drmhelper") utils.dialog_message( 'DRM Helper is needed for inputstream.adaptive ' 'playback. Disable "Use inputstream.adaptive for ' 'playback" in settings or install drmhelper. For ' 'more information, please visit: ' 'http://aussieaddons.com/drm') return hdrs = stream_url[stream_url.find('|') + 1:] listitem = xbmcgui.ListItem(label=p.get_list_title(), path=stream_url) thumb = p.get_thumb() listitem.setArt({'icon': thumb, 'thumb': thumb}) if use_ia: listitem.setProperty('inputstreamaddon', 'inputstream.adaptive') listitem.setProperty('inputstream.adaptive.manifest_type', 'hls') listitem.setProperty('inputstream.adaptive.stream_headers', hdrs) listitem.setProperty('inputstream.adaptive.license_key', stream_url) listitem.setInfo('video', p.get_kodi_list_item()) # Add subtitles if available if p.is_captions(): captions_url = stream_data.get('captions_url') profile = xbmcaddon.Addon().getAddonInfo('profile') path = xbmc.translatePath(profile) if not os.path.isdir(path): os.makedirs(path) caption_file = os.path.join(path, 'subtitles.eng.srt') if os.path.isfile(caption_file): os.remove(caption_file) try: sess = session.Session() webvtt_data = sess.get(captions_url).text if webvtt_data: with io.BytesIO() as buf: webvtt_captions = WebVTTReader().read(webvtt_data) srt_captions = SRTWriter().write(webvtt_captions) srt_unicode = srt_captions.encode('utf-8') buf.write(srt_unicode) with io.open(caption_file, "wb") as f: f.write(buf.getvalue()) if hasattr(listitem, 'setSubtitles'): listitem.setSubtitles([caption_file]) except Exception as e: utils.log( 'Subtitles not available for this program: {0}'.format(e)) if hasattr(listitem, 'addStreamInfo'): listitem.addStreamInfo('audio', p.get_kodi_audio_stream_info()) listitem.addStreamInfo('video', p.get_kodi_video_stream_info()) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem) except Exception: utils.handle_error('Unable to play video')
stories = codecs.open('story.txt', 'r', 'utf-8').readlines() def microsec(t): return t * 1000000 offset = 0.0 captions = [] for line in sys.stdin: if line.startswith(' '): continue tokens = line.split() if len(tokens) != 3: continue dirname = tokens[0] index = int(dirname.split('/')[-1]) - 1 duration = float(tokens[2]) print duration text = stories[index] cap = Caption(microsec(offset), microsec(offset + duration), [CaptionNode.create_text(text)]) offset += duration captions.append(cap) caps = CaptionSet({'en': captions}) srt = codecs.open('output.srt', 'w', 'utf-8') srt.write(SRTWriter().write(caps)) srt.close()
def test_dfxp_empty_cue_to_srt(self, sample_srt_empty_cue_output, sample_dfxp_empty_cue): caption_set = DFXPReader().read(sample_dfxp_empty_cue) results = SRTWriter().write(caption_set) self.assert_srt_equals(sample_srt_empty_cue_output, results)
def convertVTTtoSRT(fileContents): caption_set = WebVTTReader().read(fileContents) converted = SRTWriter().write(caption_set) return converted
def test_webvtt_to_srt_conversion(self): caption_set = WebVTTReader().read(SAMPLE_WEBVTT) results = SRTWriter().write(caption_set) self.assertTrue(isinstance(results, six.text_type)) self.assertSRTEquals(SAMPLE_SRT, results)
def play(params): try: p = comm.get_program(params) # enable HD streams if ADDON.getSetting('hd_enabled') == 'true': if p.dash_url: if '&rule=sd-only' in p.dash_url: p.dash_url = p.dash_url.replace('&rule=sd-only', '') if p.hls_url: if '&rule=sd-only' in p.hls_url: p.hls_url = p.hls_url.replace('&rule=sd-only', '') listitem = xbmcgui.ListItem(label=p.get_title(), path=p.get_url()) listitem.setInfo('video', p.get_kodi_list_item()) if hasattr(listitem, 'addStreamInfo'): listitem.addStreamInfo('audio', p.get_kodi_audio_stream_info()) listitem.addStreamInfo('video', p.get_kodi_video_stream_info()) if (p.dash_preferred and p.dash_url) or not p.hls_url: import drmhelper drm = p.drm_key is not None if drmhelper.check_inputstream(drm=drm): listitem.setProperty('inputstreamaddon', 'inputstream.adaptive') listitem.setProperty('inputstream.adaptive.manifest_type', 'mpd') if drm: listitem.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') listitem.setProperty( 'inputstream.adaptive.license_key', p.drm_key+'|Content-Type=application%2F' 'x-www-form-urlencoded|A{SSM}|') else: if drm: xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path=None)) return else: pass # let's try to play hls if available # Pull subtitles if available if p.subtitle: utils.log('Enabling subtitles: {0}'.format(p.subtitle)) profile = ADDON.getAddonInfo('profile') subfilename = xbmc.translatePath(os.path.join(profile, 'subtitle.srt')) profiledir = xbmc.translatePath(os.path.join(profile)) if not os.path.isdir(profiledir): os.makedirs(profiledir) webvtt_data = session.Session().get( p.subtitle).text if webvtt_data: with open(subfilename, 'w') as f: webvtt_subtitle = WebVTTReader().read(webvtt_data) srt_subtitle = SRTWriter().write(webvtt_subtitle) srt_unicode = srt_subtitle.encode('utf-8') f.write(srt_unicode) if hasattr(listitem, 'setSubtitles'): # This function only supported from Kodi v14+ listitem.setSubtitles([subfilename]) # Play video utils.log('Attempting to play: {0} : {1}'.format(p.get_title(), p.get_url())) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem) except Exception: utils.handle_error('Unable to play video')
def test_dfxp_to_srt_conversion(self): caption_set = DFXPReader().read(SAMPLE_DFXP) results = SRTWriter().write(caption_set) self.assertTrue(isinstance(results, str)) self.assertSRTEquals(SAMPLE_SRT, results)
def play_video(params): """ Determine content and pass url to Kodi for playback """ try: json_url = config.BRIGHTCOVE_DRM_URL.format(config.BRIGHTCOVE_ACCOUNT, params['id']) if params['drm'] == 'True': if xbmcaddon.Addon().getSetting('ignore_drm') == 'false': if not drmhelper.check_inputstream(): return widevine = comm.get_widevine_auth(json_url) url = widevine['url'] sub_url = widevine['sub_url'] play_item = xbmcgui.ListItem(path=url) play_item.setProperty('inputstream.adaptive.manifest_type', 'mpd') play_item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') play_item.setProperty( 'inputstream.adaptive.license_key', widevine['key'] + ('|Content-Type=application%2F' 'x-www-form-urlencoded|A{SSM}|')) else: if params['action'] == 'listchannels': qual = int(xbmcaddon.Addon().getSetting('LIVEQUALITY')) live = True else: qual = int(xbmcaddon.Addon().getSetting('HLSQUALITY')) live = False stream_data = comm.get_stream(json_url, live=live) m3u8 = stream_data.get('url') sub_url = stream_data.get('sub_url') url = parse_m3u8(m3u8, qual=qual, live=live) play_item = xbmcgui.ListItem(path=url) utils.log('Playing {0} - {1}'.format(params.get('title'), url)) if sub_url: try: utils.log("Enabling subtitles: {0}".format(sub_url)) profile = xbmcaddon.Addon().getAddonInfo('profile') subfilename = xbmc.translatePath( os.path.join(profile, 'subtitle.srt')) profiledir = xbmc.translatePath(os.path.join(profile)) if not os.path.isdir(profiledir): os.makedirs(profiledir) with custom_session.Session() as s: webvtt_data = s.get(sub_url).text if webvtt_data: with open(subfilename, 'w') as f: webvtt_subtitle = WebVTTReader().read(webvtt_data) srt_subtitle = SRTWriter().write(webvtt_subtitle) srt_unicode = srt_subtitle.encode('utf-8') f.write(srt_unicode) if hasattr(play_item, 'setSubtitles'): # This function only supported from Kodi v14+ play_item.setSubtitles([subfilename]) except Exception as e: utils.log('Unable to add subtitles: {0}'.format(e)) xbmcplugin.setResolvedUrl(_handle, True, play_item) except Exception: utils.handle_error('Unable to play video')
def play(url): try: # Remove cookies.dat for Kodi < 17.0 - causes issues with playback addon = xbmcaddon.Addon() cookies_dat = xbmc.translatePath('special://home/cache/cookies.dat') if os.path.isfile(cookies_dat): os.remove(cookies_dat) p = classes.Program() p.parse_xbmc_url(url) stream = comm.get_stream_url(p.get_house_number(), p.get_url()) use_ia = addon.getSetting('use_ia') == 'true' if use_ia: if addon.getSetting('ignore_drm') == 'false': try: import drmhelper if not drmhelper.check_inputstream(drm=False): return except ImportError: utils.log("Failed to import drmhelper") utils.dialog_message( 'DRM Helper is needed for inputstream.adaptive ' 'playback. Disable "Use inputstream.adaptive for ' 'playback" in settings or install drmhelper. For ' 'more information, please visit: ' 'http://aussieaddons.com/drm') return hdrs = stream[stream.find('|') + 1:] listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail, path=stream) if use_ia: listitem.setProperty('inputstreamaddon', 'inputstream.adaptive') listitem.setProperty('inputstream.adaptive.manifest_type', 'hls') listitem.setProperty('inputstream.adaptive.stream_headers', hdrs) listitem.setProperty('inputstream.adaptive.license_key', stream) listitem.setInfo('video', p.get_kodi_list_item()) # Add subtitles if available if p.subtitle_url: profile = xbmcaddon.Addon().getAddonInfo('profile') path = xbmc.translatePath(profile).decode('utf-8') if not os.path.isdir(path): os.makedirs(path) subfile = xbmc.translatePath( os.path.join(path, 'subtitles.eng.srt')) if os.path.isfile(subfile): os.remove(subfile) try: webvtt_data = urllib2.urlopen( p.subtitle_url).read().decode('utf-8') if webvtt_data: with open(subfile, 'w') as f: webvtt_subtitle = WebVTTReader().read(webvtt_data) srt_subtitle = SRTWriter().write(webvtt_subtitle) srt_unicode = srt_subtitle.encode('utf-8') f.write(srt_unicode) if hasattr(listitem, 'setSubtitles'): listitem.setSubtitles([subfile]) except Exception as e: utils.log( 'Subtitles not available for this program {0}'.format(e)) if hasattr(listitem, 'addStreamInfo'): listitem.addStreamInfo('audio', p.get_kodi_audio_stream_info()) listitem.addStreamInfo('video', p.get_kodi_video_stream_info()) xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem) except Exception: utils.handle_error('Unable to play video')
def play_video(params): """ Determine content and pass url to Kodi for playback """ try: _url = sys.argv[0] _handle = int(sys.argv[1]) json_url = config.BRIGHTCOVE_DRM_URL.format(config.BRIGHTCOVE_ACCOUNT, params['id']) play_item = xbmcgui.ListItem() play_item.setProperty('inputstreamaddon', 'inputstream.adaptive') play_item.setProperty('inputstream', 'inputstream.adaptive') if params.get('drm') == 'True': if xbmcaddon.Addon().getSetting('ignore_drm') == 'false': if not drmhelper.check_inputstream(): return widevine = comm.get_widevine_auth(json_url) url = widevine['url'] sub_url = widevine['sub_url'] play_item.setPath(url) play_item.setProperty('inputstream.adaptive.manifest_type', 'mpd') play_item.setProperty('inputstream.adaptive.license_type', 'com.widevine.alpha') play_item.setProperty( 'inputstream.adaptive.license_key', widevine['key'] + ('|Content-Type=application%2F' 'x-www-form-urlencoded|A{SSM}|')) else: live = params['action'] == 'listchannels' stream_data = comm.get_stream(json_url, live=live) url = str(stream_data.get('url')) sub_url = stream_data.get('sub_url') play_item.setPath(url) play_item.setProperty('inputstream.adaptive.manifest_type', 'hls') utils.log('Playing {0} - {1}'.format(params.get('title'), url)) if sub_url: try: utils.log("Enabling subtitles: {0}".format(sub_url)) profile = xbmcaddon.Addon().getAddonInfo('profile') subfilename = xbmc.translatePath( os.path.join(profile, 'subtitle.srt')) profiledir = xbmc.translatePath(os.path.join(profile)) if not os.path.isdir(profiledir): os.makedirs(profiledir) with custom_session.Session() as s: webvtt_data = s.get(sub_url).text if webvtt_data: with open(subfilename, 'w') as f: webvtt_subtitle = WebVTTReader().read(webvtt_data) srt_subtitle = SRTWriter().write(webvtt_subtitle) srt_unicode = srt_subtitle.encode('utf-8') f.write(srt_unicode) if hasattr(play_item, 'setSubtitles'): # This function only supported from Kodi v14+ play_item.setSubtitles([subfilename]) except Exception as e: utils.log('Unable to add subtitles: {0}'.format(e)) play_item.setProperty('isPlayable', 'true') if hasattr(play_item, 'setIsFolder'): play_item.setIsFolder(False) # TODO: add more info play_item.setInfo( 'video', { 'mediatype': 'episode', 'tvshowtitle': params.get('series_title', ''), 'title': params.get('episode_name', ''), 'plot': params.get('desc', ''), 'plotoutline': params.get('desc', ''), 'duration': params.get('duration', ''), 'aired': params.get('airdate', ''), 'season': params.get('season_no', ''), 'episode': params.get('episode_no', '') }) xbmcplugin.setResolvedUrl(_handle, True, play_item) if params['action'] != 'listepisodes': return next_item = comm.get_next_episode(params) if not next_item: return try: import upnext except Exception as e: utils.log('UpNext addon not installed: %s' % e) return upnext_info = dict(current_episode=dict( episodeid=params.get('id', ''), tvshowid=params.get('series_slug', ''), title=params.get('episode_name', ''), art={ 'thumb': params.get('thumb', ''), 'tvshow.fanart': params.get('fanart', ''), }, season=params.get('season_no', ''), episode=params.get('episode_no', ''), showtitle=params.get('series_title', ''), plot=params.get('desc', ''), playcount=0, rating=None, firstaired=params.get('airdate', ''), runtime=params.get('duration', ''), ), next_episode=dict( episodeid=next_item.id, tvshowid=next_item.series_slug, title=next_item.episode_name, art={ 'thumb': next_item.thumb, 'tvshow.fanart': next_item.fanart, }, season=next_item.season_no, episode=next_item.episode_no, showtitle=next_item.series_title, plot=next_item.desc, playcount=0, rating=None, firstaired=next_item.airdate, runtime=next_item.duration, ), play_url='{0}?action=listepisodes{1}'.format( _url, next_item.make_kodi_url())) upnext.send_signal(xbmcaddon.Addon().getAddonInfo('id'), upnext_info) except Exception: utils.handle_error('Unable to play video')
def test_webvtt_to_srt_conversion(self): results = SRTWriter().write(self.captions) self.assertTrue(isinstance(results, unicode)) self.assertSRTEquals(SAMPLE_SRT_UNICODE, results)
def test_dfxp_to_srt_conversion(self, sample_srt, sample_dfxp): caption_set = DFXPReader().read(sample_dfxp) results = SRTWriter().write(caption_set) assert isinstance(results, str) self.assert_srt_equals(sample_srt, results)
def test_sami_to_srt_conversion(self): caption_set = SAMIReader().read(SAMPLE_SAMI) results = SRTWriter().write(caption_set) self.assertTrue(isinstance(results, unicode)) self.assertSRTEquals(SAMPLE_SRT, results)
def convert_content(file_contents): '''convert_content convert vvt content to srt content using pycaption''' caption_set = WebVTTReader().read(file_contents) srt_content = SRTWriter().write(caption_set) return srt_content
def run_pipeline(url=None, hmm=None, lm=None, dict=None, caption_format='webvtt', out_file=None): if url is None: raise Exception('No URL specified!') pipeline = Gst.parse_launch('uridecodebin name=source ! audioconvert !' + ' audioresample ! pocketsphinx name=asr !' + ' fakesink') source = pipeline.get_by_name('source') source.set_property('uri', url) pocketsphinx = pipeline.get_by_name('asr') if hmm: pocketsphinx.set_property('hmm', hmm) if lm: pocketsphinx.set_property('lm', lm) if dict: pocketsphinx.set_property('dict', dict) bus = pipeline.get_bus() # Start playing pipeline.set_state(Gst.State.PLAYING) cap_set = CaptionSet() captions = [] # Wait until error or EOS while True: try: msg = bus.timed_pop(Gst.CLOCK_TIME_NONE) if msg: #if msg.get_structure(): # print(msg.get_structure().to_string()) if msg.type == Gst.MessageType.EOS: break struct = msg.get_structure() if struct and struct.get_name() == 'pocketsphinx': if struct['final']: c = Caption() c.start = struct['start_time'] / Gst.USECOND c.end = struct['end_time'] / Gst.USECOND c.nodes.append( CaptionNode.create_text(struct['hypothesis'])) captions.append(c) except KeyboardInterrupt: pipeline.send_event(Gst.Event.new_eos()) # Free resources pipeline.set_state(Gst.State.NULL) cap_set.set_captions('en-US', captions) writer = SRTWriter() if caption_format == 'srt' else WebVTTWriter() caption_data = writer.write(cap_set) if out_file is not None: codecs.open(out_file, 'w', 'utf-8').write(caption_data) else: print(caption_data)
def test_webvtt_to_srt_conversion(self, sample_srt, sample_webvtt): caption_set = WebVTTReader().read(sample_webvtt) results = SRTWriter().write(caption_set) assert isinstance(results, str) self.assert_srt_equals(sample_srt, results)