Created
January 21, 2010 21:05
-
-
Save adamlum/283194 to your computer and use it in GitHub Desktop.
Adam Lum's solution for RPCFN #1 (Shift Subtitle)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Adam Lum's solution for RPCFN #1 | |
# http://rubylearning.com/blog/2009/09/24/rpcfn-shift-subtitle-1/ | |
require 'optparse' | |
# Get the command line arguments | |
options = {} | |
OptionParser.new do |opts| | |
opts.banner = "Usage: shift_subtitle.rb [options] input_file output_file" | |
opts.on("--operation [OPERATION]") do |o| | |
options[:operation] = o | |
end | |
opts.on("--time [TIME]") do |t| | |
time_split = t.split(",") | |
options[:seconds] = time_split[0].to_i | |
options[:milliseconds] = time_split[1].to_i | |
if options[:operation] == "sub" | |
options[:seconds] = options[:seconds] * -1 | |
options[:milliseconds] = options[:milliseconds] * -1 | |
end | |
end | |
end.parse! | |
# Read in the file | |
subtitle_entries = File.read(ARGV[0]).split("\n\n") | |
output_string = "" | |
# Process the shift | |
subtitle_entries.each do |subtitle_entry| | |
subtitle_parts = subtitle_entry.split("\n") | |
time_range = subtitle_parts[1].split(" --> ") | |
start_time = time_range[0].gsub(",", ":").split(":") | |
end_time = time_range[1].gsub(",", ":").split(":") | |
start_total_milliseconds = start_time[3].to_i + options[:milliseconds] | |
start_time[3] = start_total_milliseconds % 1000 | |
start_time[2] = start_time[2].to_i + (start_total_milliseconds / 1000) | |
start_total_seconds = start_time[2].to_i + options[:seconds].to_i | |
start_time[2] = start_total_seconds % 60 | |
start_time[1] = start_time[1].to_i + (start_total_seconds / 60) | |
start_time[0] = start_time[0].to_i + (start_time[1] / 60) | |
start_time[1] = start_time[1] % 60 | |
end_total_milliseconds = end_time[3].to_i + options[:milliseconds] | |
end_time[3] = end_total_milliseconds % 1000 | |
end_time[2] = end_time[2].to_i + (end_total_milliseconds / 1000) | |
end_total_seconds = end_time[2].to_i + options[:seconds].to_i | |
end_time[2] = end_total_seconds % 60 | |
end_time[1] = end_time[1].to_i + (end_total_seconds / 60) | |
end_time[0] = end_time[0].to_i + (end_time[1] / 60) | |
end_time[1] = (end_time[1] % 60) | |
output_string += "#{subtitle_parts[0]}\n%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d" % [start_time[0], start_time[1], start_time[2], start_time[3], end_time[0], end_time[1], end_time[2], end_time[3]] | |
(2..subtitle_parts.size - 1).each do |i| | |
output_string += "\n#{subtitle_parts[i]}" | |
end | |
output_string += "\n\n" | |
end | |
# Write the file | |
File.open(ARGV[1], 'w') {|f| f.write(output_string.strip)} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment