Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- #Python 2 compatible (tested with 2.6.6)
- #This script assumes a lot, and doesn't follow many DRY guidelines. There's a lot of room for improvement.
- #It also only works with positive offsets, as it was what I needed. Might update it to work with negative offsets.
- #Created to resync some Curb Your Enthusiasm subtitles. Great show by the way. :)
- """
- srt_resync.py: Give it 2 parameters: first the path to the file, and second an offset in positive seconds (can be fractional).
- The script produces a file with the same name with "-resync" appended to the end of the filename (before the extension)
- """
- __author__ = "Nuno Melo";
- __copyright__ = "Copyleft 2012";
- __credits__ = ["Nuno Melo"];
- __license__ = "WTFPL";
- __version__ = "1.0b";
- import re, sys, math, os;
- HOURS_IN_SECONDS = 59*59;
- MINUTES_IN_SECONDS = 59;
- LINE_BREAK = "\n";
- args = sys.argv;
- def resync(time, hours, minutes, seconds, ms):
- tokens = time.split(':');
- new_hours = int(tokens[0]) + hours;
- new_minutes = int(tokens[1]) + minutes;
- tokens = tokens[2].split(',');
- new_seconds = int(tokens[0]) + seconds;
- new_ms = int(tokens[1]) + ms;
- while new_ms-999 >= 0:
- new_ms -= 999;
- new_seconds += 1;
- while new_seconds-59 >= 0:
- new_seconds -= 59;
- new_minutes += 1;
- while new_minutes-59 >= 0:
- new_minutes -= 59;
- new_hours += 1;
- return "%s:%s:%s,%s" % (str(new_hours).zfill(2), str(new_minutes).zfill(2), str(new_seconds).zfill(2), str(new_ms).zfill(3));
- if len(args) == 3:
- srtf = args[1];
- try:
- diff = float(args[2]);
- except ValueError:
- print "Usage: python %s file_path number_seconds" % args[0];
- sys.exit(1);
- #get actual numbers
- hours = 0;
- minutes = 0;
- seconds = 0;
- ms = 0;
- while diff-HOURS_IN_SECONDS >= 0:
- hours += 1;
- diff -= HOURS_IN_SECONDS;
- while diff-MINUTES_IN_SECONDS >= 0:
- minutes += 1;
- diff -= MINUTES_IN_SECONDS;
- seconds = int(diff);
- ms = int((diff-seconds)*999);
- try:
- f = open(args[1], 'r');
- except IOError:
- print "File does not exist. Exiting...";
- sys.exit(1);
- data = f.read();
- lines = re.findall(r"([0-9]{1,3})(?:\r)?\n?([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}) --> ([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3})(?:\r)?\n(.*?(?:\r)?\n(?:\r)?\n)", data, re.DOTALL);
- file_ext = os.path.splitext(args[1])[1];
- new_file = args[1].replace(file_ext, "-resync" + file_ext);
- out = open(new_file, 'w');
- for nuple in lines:
- new_start = resync(nuple[1], hours, minutes, seconds, ms);
- new_end = resync(nuple[2], hours, minutes, seconds, ms);
- out.write(nuple[0] + LINE_BREAK);
- out.write(new_start + " --> " + new_end + LINE_BREAK);
- out.write(re.sub('(?:\r)\n', LINE_BREAK, nuple[3]));
- f.close();
- out.close();
- print "Resynced %s." % args[1];
- else:
- print "Usage: python %s file_path number_seconds" % args[0];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement