Friday, June 24, 2011

srt subtitle offset delay adjust fix utility

A quick and dirty basic python utility to adjust delay offset all the timestamps in a .srt (subtitle) file by a fixed number of seconds or fractions of a second. I know there are other .srt subtitle utilities, with far more functionality, and I have used them in the past. Since I only needed one basic function for what I want to do, I thought throwing this together would be just as fast as searching for it on the web or transferring .srt and video files to the other computer where I have subtitle editing utilities installed, .
# srt-offset.py
# offset srt timestamp
import sys
import re

if len(sys.argv) < 3:
 print("usage: " + sys.argv[0] + " <srt file> <timestamp adjust (sec)>")
 exit()

filename = sys.argv[1]
sec = int(float(sys.argv[2]))
msec = int((float(sys.argv[2])-sec)*1000)

#print(sec, msec)

f = open(filename, "r")

lines = f.readlines()

y = (2,3,4)

# format: 00:56:44,621 --> 00:56:49,998
r = re.compile(r'(..):(..):(..),(...) --> (..):(..):(..),(...)')
for l in lines:
 if l.find(' --> ') > 0 :
  m = r.search(l)
  g = list(m.groups())
  for i in range(0,len(g)):
    g[i] = int(g[i])
  g[3]  = msec
  g[2]  = sec
  if g[3]%1000 != g[3]:
   g[2]  = (g[3] - g[3]%1000)/1000
   g[3] = g[3]%1000
  if g[2]%60 != g[2]:
   g[1]  = (g[2] - g[2]%60)/60
   g[2] = g[2]%60
  if g[1]%60 != g[1]:
   g[0]  = (g[1] - g[1]%60)/60
   g[1] = g[1]%60
  g[7]  = msec
  g[6]  = sec
  if g[7]%1000 != g[7]:
   g[6]  = (g[7] - g[7]%1000)/1000
   g[7] = g[7]%1000
  if g[6]%60 != g[6]:
   g[5]  = (g[6] - g[6]%60)/60
   g[6] = g[6]%60
  if g[5]%60 != g[5]:
   g[4]  = (g[5] - g[5]%60)/60
   g[5] = g[5]%60

#  print('*', end='')
  l = "%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n" % tuple(g)

 print(l, end='')

No comments:

Post a Comment