Skip to content

Instantly share code, notes, and snippets.

@KyleJamesWalker
Last active December 15, 2018 01:51
Show Gist options
  • Save KyleJamesWalker/f0962c3496da4d6b0caf to your computer and use it in GitHub Desktop.
Save KyleJamesWalker/f0962c3496da4d6b0caf to your computer and use it in GitHub Desktop.
Converts a folder of srt files into a single srt
# -*- coding: utf-8 -*-
'''
Quick script to embed into Automator to concat a folder of srt files into
a single srt.
Note: This also removes extra blanks lines, to allow pycaption to process
the files. This won't be needed if https://github.com/pbs/pycaption/pull/39
is merged.
'''
import argparse
import codecs
import re
import traceback
from os import walk
def detect_by_bom(path, default):
print path, default
with open(path, 'rb') as f:
raw = f.read(4)
for enc, boms in \
('utf-8-sig', (codecs.BOM_UTF8,)),\
('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)),\
('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE)):
if any(raw.startswith(bom) for bom in boms):
return enc
return default
def srt_it(srt_folder, srt_out):
srt_file = codecs.open(srt_out, "w", "utf-8")
files = []
for (_, _, filenames) in walk(srt_folder):
files.extend([x for x in filenames
if x.lower().rsplit('.', 1)[1] is 'srt'])
break
counter = 0
last_blank = False
for f in files:
filename = "{}/{}".format(srt_folder, f)
encoding = detect_by_bom(filename, 'utf-8')
print encoding
for l in codecs.open(filename, "r", encoding):
# Convert Line Ending
l = l.rstrip() + '\n'
# For some reason the first line of a files isn't catching so
# adding a . seems to catch it...
if re.match(r"\d+$", l):
last_blank = False
counter += 1
srt_file.write("{}\n".format(counter))
elif l == "\n":
if not last_blank:
srt_file.write(l)
last_blank = True
else:
last_blank = False
srt_file.write(l)
srt_file.close()
if __name__ == "__main__":
try:
parser = argparse.ArgumentParser(description='Merge Folder of SRTs.')
parser.add_argument(dest='srt_folders', metavar='file', nargs='+',
help='Folders full of srt files.')
args = parser.parse_args()
for srt_folder in args.srt_folders:
if srt_folder[-1] in ['\\', '/']:
srt_folder = srt_folder[:-1]
srt_out = "{}.srt".format(srt_folder)
srt_it(srt_folder, srt_out)
except Exception as e:
print ("Connection failed:\n{}\n{}\n{}".
format(str(e),
type(e).__name__,
traceback.format_exc()))
@KyleJamesWalker
Copy link
Author

Note: This script is embedded into an automator program so added manual print out of exception, to allow debugging.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment