Skip to content

Instantly share code, notes, and snippets.

@rosenfeld
Created October 6, 2009 03:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rosenfeld/202717 to your computer and use it in GitHub Desktop.
Save rosenfeld/202717 to your computer and use it in GitHub Desktop.
First Ruby Challenge - Shift Subtitle
require 'optparse'
optparse = OptionParser.new do |opts|
opts.banner = 'Usage: shift_subtitle.rb --operation add|sub --time ss,mmm input_file output_file'
opts.on('--operation OPERATION', /^add|sub$/, 'OPERATION must be add or sub'){|o| @operation=o}
opts.on('--time TIME_SHIFT', /^\d{2},\d{3}$/,
'TIME_SHIFT must be in format ss,mmm, where ss are the seconds and mmm are the milliseconds to shift') do |o|
@time_shift = o.sub(',', '.').to_f
end
opts.on('-f', '--force', 'Forces overwrite of output file without prompt'){|o| @force=true}
end
begin
optparse.parse!
rescue OptionParser::ParseError => e
puts "\n", e, "\n"
end
def exit_with_msg(msg); puts msg; exit(1); end
exit_with_msg optparse.help unless ARGV.size==2 and @operation and @time_shift
exit_with_msg "Input file '#{ARGV[0]}' doesn't exist." unless File.exists?(ARGV[0])
exit_with_msg "Output file '#{ARGV[1]}' already exists. Use --force switch to overwrite it." unless @force or not File.exists?(ARGV[1])
TIME_FORMAT = '\d{2}:\d{2}:\d{2},\d{3}'
TIME_FORMAT_REGEXP = /(\d{2}):(\d{2}):(\d{2}),(\d{3})/
def shift_time(time)
h, m, s, ms = TIME_FORMAT_REGEXP.match(time)[1..-1].collect{|v| v.to_i}
t=Time.utc(0,'jan',1,h,m,s,ms*1000) + @time_shift*(@operation == 'add' ? 1 : -1)
t.strftime('%H:%M:%S,')+ "%03d" % (t.usec/1000).to_s
end
input = File.open(ARGV[0])
new_line = input.readline[-2] == "\r"[0] ? "\r\n" : "\n" # \r == 13
empty_line = new_line*2
input.rewind
File.open(ARGV[1], 'w') do |output|
while (subtitle=input.gets(empty_line))
matched, start_time, end_time = /\A\d*#{new_line}(#{TIME_FORMAT}) --> (#{TIME_FORMAT}).*/m.match(subtitle).to_a
exit_with_msg "Invalid file format. Output file is truncated. Context: \n#{subtitle}" unless matched
output << subtitle.sub(/#{TIME_FORMAT} --> #{TIME_FORMAT}/, "#{shift_time(start_time)} --> #{shift_time(end_time)}")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment