sboby/json2srt.py

80 lines
1.8 KiB
Python
Raw Normal View History

2022-06-06 00:43:04 +02:00
#!/usr/bin/env python3
# by Bomboclat
# for great justice!
import sys
import json
import argparse
from datetime import timedelta
def convert(seconds):
sec_to_convert = seconds
converted_sec = timedelta(seconds = sec_to_convert)
dot = str(converted_sec).find('.')
if dot != -1:
timestamp = str(converted_sec)[:-3].replace('.',',')
else:
timestamp = str(converted_sec).replace('.',',')
return timestamp
def write_file(srt, outfile):
for d in srt:
with open(outfile, 'a') as f:
for value in d.values():
f.write('%s\n' % (str(value)))
return 0
def json_to_srt(f):
'''
SRT file format:
sequence number
two-hash arrow to separate beginning and ending timecodes
caption
empty line
example:
1
00:00:00,000 --> 00:00:04,440
here the subtitle caption string
2
-8<--snip!--
'''
srt = []
for d in f:
sequence_number = f.index(d) + 1
startstop = convert(float(d['start'])) + " --> " + convert(float(d['end']))
#print(startstop)
new_sub = { 'seq': sequence_number, 'startstop': startstop, 'caption': d['content'], 'newline': '' }
srt.append(new_sub)
return srt
def main():
# parse command line options
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--infile', help='input file in json format', type=argparse.FileType('r'))
parser.add_argument('-o', '--outfile', action='store', dest='outfile', help="Directs the output to a name of your choice")
args = parser.parse_args()
# loads a list of dicts
f = json.load(args.infile)
outfile = args.outfile
srt = json_to_srt(f)
write_file(srt, outfile)
return 0
if __name__ == '__main__':
sys.exit(main())