From dccdc96146f4c6553b48549e26fae52a56d962ef Mon Sep 17 00:00:00 2001 From: dan Date: Mon, 6 Jun 2022 00:43:04 +0200 Subject: [PATCH] scripto --- json2srt.py | 79 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100755 json2srt.py diff --git a/json2srt.py b/json2srt.py new file mode 100755 index 0000000..ab22441 --- /dev/null +++ b/json2srt.py @@ -0,0 +1,79 @@ +#!/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())