secret
anonymous / Eduardo
Last active

  • Download Gist
Eduardo
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#!/usr/local/bin/ruby
 
require 'optparse'
 
def s2t(s)
s =~ /([0-9]{2}):([0-9]{2}):([0-9]{2}),([0-9]{3})/
t = $1.to_i * 3600000 + $2.to_i * 60000 + $3.to_i * 1000 + $4.to_i
end
 
def t2s(t)
h = t / 3600000; t -= h * 3600000
m = t / 60000; t -= m * 60000
s = t / 1000; t -= s * 1000
ms = t
format("%02d:%02d:%02d,%03d", h, m, s, ms)
end
 
optparse = OptionParser.new do |opts|
opts.banner = "Usage: shift_subtitle --operation --time "
opts.on('-o', '--operation OPERATION', [:add, :sub], "Operation") do |s|
operation = s
end
opts.on('-t', '--time TIME', "Time") do |s|
time = s
end
end
 
optparse.parse!
 
if ARGV.length == 2
input_file = ARGV[0]
output_file = ARGV[1]
else
print optparse.banner
exit(1)
end
 
if !(time =~ /[1-9][0-9]*|[1-9][0-9]*,[0-9]{1,3}/) then
print "invalid time\n"
exit(2)
end
 
ms = (time.gsub(",", ".").to_f * 1000.0).to_i
ms = -ms if operation == 'sub'
 
if !File.exist?(input_file) then
print "input_file #{input_file} not found\n"
exit(3)
end
 
f = File.new(output_file, 'w+')
 
File.open(input_file, 'r').each_line do |s|
s = "#{t2s(s2t($1) + ms)} --> #{t2s(s2t($2) + ms)}\n"if s =~ /([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}) --> ([0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3})/
f << s
end
 
f.close

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.