How to use the srt.parse function in srt

To help you get started, we’ve selected a few srt examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github foone / SplitBySubs / split_by_subs.py View on Github external
# check the file for an embedded subtitle stream
subtitles = None
embedded_subtitles = None
srt_data = None
for stream in info['streams']:
	if stream.get('codec_name') == 'subrip':
		embedded_subtitles = stream
		break


if args.srt is None:
	if embedded_subtitles:
		srt_data = subprocess.check_output(
			['ffmpeg','-v','quiet','-i',args.movie,'-vn','-an', '-codec:s','srt','-f','srt','-']
		)
		subtitles=list(srt.parse(srt_data))
	else:
		args.srt = os.path.splitext(args.movie)[0] + '.srt'
		if not os.path.exists(args.srt):
			print >>sys.stderr,"Couldn't find SRT file! (guessed {})".format(args.srt)
			print >>sys.stderr,"Please specify SRT path explicitly!"

			sys.exit(1)

if not subtitles:
	with open(args.srt,'rb') as f:
		subtitles=list(srt.parse(f.read().decode(args.encoding)))

if args.shift is not None:
	shifted_subs = []
	shift_amount = datetime.timedelta(seconds=-args.shift)
	for e in subtitles:
github jasoneppink / multicaptions / multicaptions.py View on Github external
retry+=1
			if retry >= 5000:
				print "ERROR"
				raise SystemExit

	#import SRT subtitle files into one "subtitles" dict
	subtitles = collections.OrderedDict()
	os.chdir(subtitle_directory)

	#first add default language
	for subs in glob.glob("*.srt"):
	        lang = subs.split('.')[1]
		if(lang == default_lang):
		        with io.open(subs, "r", encoding="utf-8-sig") as myfile:
		                subfile = myfile.read()
		        subtitle_generator = srt.parse(subfile)
		        subtitles[lang] = list(subtitle_generator)

	#then add other languages
	for subs in glob.glob("*.srt"):
		lang = subs.split('.')[1]
		with io.open(subs, "r", encoding="utf-8-sig") as myfile:
			subfile = myfile.read()
		subtitle_generator = srt.parse(subfile)
		subtitles[lang] = list(subtitle_generator)

	#iterate through and print subtitles	
	i = 0
	next_i = 0
	position = "0"
	duration = "0"
	while duration == "0":
github jasoneppink / multicaptions / multicaptions.py View on Github external
#first add default language
	for subs in glob.glob("*.srt"):
	        lang = subs.split('.')[1]
		if(lang == default_lang):
		        with io.open(subs, "r", encoding="utf-8-sig") as myfile:
		                subfile = myfile.read()
		        subtitle_generator = srt.parse(subfile)
		        subtitles[lang] = list(subtitle_generator)

	#then add other languages
	for subs in glob.glob("*.srt"):
		lang = subs.split('.')[1]
		with io.open(subs, "r", encoding="utf-8-sig") as myfile:
			subfile = myfile.read()
		subtitle_generator = srt.parse(subfile)
		subtitles[lang] = list(subtitle_generator)

	#iterate through and print subtitles	
	i = 0
	next_i = 0
	position = "0"
	duration = "0"
	while duration == "0":
		try:
			duration = chop_digits(str(dbusIfaceProp.Duration()))
		except:
			pass

	while long(duration) > long(position):
		start = tc_to_ms(str(subtitles[language][i].start))
		end = tc_to_ms(str(subtitles[language][i].end))
github mrinflated / SrtTranslate / process.py View on Github external
def process(mode,path,source,target):
    fileName = path
    with open(path,'rt',encoding='utf-8',errors='ignore') as f:
        data = f.read()
        f.close()
    
    subs = list(srt.parse(data))

    for k in tqdm(subs):
        text = k.content
        translation = translate(text,source,target,mode)

        k.content = translation
  
    srtTranslated = srt.compose(subs)

    # write the srt file translated...
    with open("%s_%s_Translated.srt"%(os.path.splitext(os.path.split(path)[-1])[0],mode),'xt',encoding='utf-8',errors='ignore') as f:
        f.write(data)
        f.write(srtTranslated)
        f.close()
github stephanos / subvoc / domain / parse.py View on Github external
def _parse_lines(self, subtitle):
        lines = []
        text_buffer = []
        for entry in srt.parse(subtitle.strip()):
            for line in entry.content.split("\n"):
                line_text = line.strip()
                if line_text.startswith('...'):
                    line_text = line_text[3:].strip()
                if line_text.endswith('...'):
                    line_text = line_text[:-3].strip()
                if line_text.startswith('-'):
                    line_text = line_text[1:].strip()
                line_text = BeautifulSoup(line_text, 'html.parser').text

                lines.append(SubtitleLine(line_text, entry.start))
                text_buffer.append(line_text)
        full_text = ' '.join(text_buffer)
        return lines, full_text
github smacke / subsync / subsync / subtitle_parsers.py View on Github external
def _srt_parse(s, max_subtitle_seconds=None, start_seconds=0, tolerant=True):
    start_time = timedelta(seconds=start_seconds)
    subs = srt.parse(s)
    subs_list = []
    max_duration = timedelta(days=1)
    if max_subtitle_seconds is not None:
        max_duration = timedelta(seconds=max_subtitle_seconds)
    while True:
        try:
            next_sub = next(subs)
            if next_sub.start < start_time:
                continue
            next_sub.end = min(next_sub.end, next_sub.start + max_duration)
            subs_list.append(next_sub)
        # We don't catch SRTParseError here b/c that typically raised when we
        # are trying to parse with the wrong encoding, in which case we might
        # be able to try another one on the *entire* set of subtitles elsewhere.
        except ValueError as e:
            if tolerant:

srt

A tiny library for parsing, modifying, and composing SRT files.

MIT
Latest version published 2 years ago

Package Health Score

52 / 100
Full package analysis

Popular srt functions

Similar packages