Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# 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:
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":
#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))
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()
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
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:
shifted_subs.append(srt.Subtitle(e.index,e.start+shift_amount,e.end+shift_amount,e.content,e.proprietary))
subtitles = shifted_subs
EXTENSION = os.path.splitext(args.movie)[1]
if args.twitter:
EXTENSION='.mp4'
quiet_mkdir(args.outdir)
match_pattern='*'
if args.match:
match_pattern = '*{}*'.format(args.match.lower())
if args.subs:
# We need the subs in a filename with no spaces, because ffmpeg filter parsing is terrible
# so we save it locally and then delete at the end.
quiet_erase(TMPFILE)
def fit(self, subs, *_):
offset_subs = []
for sub in subs:
offset_subs.append(srt.Subtitle(index=sub.index,
start=sub.start + self.td_seconds,
end=sub.end + self.td_seconds,
content=sub.content))
self.subs_ = SrtSubtitles(offset_subs, encoding=subs.encoding)
return self
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()
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:
def generate_subtitles(sentences, durations_in_seconds):
subtitles = []
start = timedelta(seconds=0)
for i, (sentence, duration) in enumerate(zip(sentences, durations_in_seconds)):
end = start + timedelta(seconds=duration)
subtitles.append(srt.Subtitle(index=i + 1, start=start, end=end, content=sentence))
start = end
return subtitles