Skip to content

Instantly share code, notes, and snippets.

@joesteele
Created June 25, 2013 17:05
Show Gist options
  • Save joesteele/5860271 to your computer and use it in GitHub Desktop.
Save joesteele/5860271 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'time'
if ARGV.size < 2
fail "Please supply shift modifier\n" +
"USAGE: ./caption_shifter <caption-input> <shift-modifier>\n" +
"EXAMPLE: ./caption_shifter html.vtt 2"
elsif ARGV.size < 1
fail "Please supply caption file\n" +
"USAGE: ./caption_shifter <caption-input> <shift-modifier>\n" +
"EXAMPLE: ./caption_shifter html.vtt 2"
end
caption_file = ARGV[0]
shift_modifier = ARGV[1]
output_file = "#{File.basename(caption_file, File.extname(caption_file))}_shifted.vtt"
puts "caption_file: #{caption_file}, modifier: #{shift_modifier}"
module CaptionShifter
def self.parse(lines)
captions = []
grouped_lines = []
lines.shift while lines.first.empty?
lines.each_with_index do |line, index|
line.strip!
if line.empty? && grouped_lines.length > 0
captions << Caption.parse(grouped_lines)
grouped_lines = []
next
end
unless line.empty?
grouped_lines << line
end
if grouped_lines.length > 0 && lines.length == index + 1
captions << Caption.parse(grouped_lines)
end
end
captions
end
Caption = Struct.new(:id, :start_time, :end_time, :caption) do
TIME_FORMAT = "%H:%M:%S,000"
def self.parse(lines)
lines.shift while lines.first.empty?
id = lines[0].chomp
start_time, end_time = lines[1].chomp.split(" --> ")
caption = lines[2..-1].map(&:chomp).join(" ")
new(id, start_time, end_time, caption)
end
def to_s
[id, time_range, caption].join("\n")
end
def time_range
"#{start_time} --> #{end_time}"
end
def shift!(modifier)
modifier = modifier.to_i
_start_time = Time.parse(start_time.gsub(/,\d+$/, ''))
_end_time = Time.parse(end_time.gsub(/,\d+$/, ''))
unless [_start_time.hour, _start_time.min, _start_time.sec].all? {|time| time == 0}
self.start_time = (_start_time + modifier).strftime(TIME_FORMAT)
end
unless [_end_time.hour, _end_time.min, _end_time.sec].all? {|time| time == 0}
self.end_time = (_end_time + modifier).strftime(TIME_FORMAT)
end
end
end
end
captions = CaptionShifter.parse(File.readlines(caption_file))
captions.each { |caption| caption.shift!(shift_modifier) }
File.open(output_file, 'w+') { |file| file.write(captions.join("\n\n") + "\n\n") }
puts "wrote #{captions.length} captions to #{output_file}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment