Skip to content

Instantly share code, notes, and snippets.

@SwagDevOps
Last active May 24, 2021 22:44
Show Gist options
  • Select an option

  • Save SwagDevOps/2716019324b94cd5954ca18b1fa3468d to your computer and use it in GitHub Desktop.

Select an option

Save SwagDevOps/2716019324b94cd5954ca18b1fa3468d to your computer and use it in GitHub Desktop.
Fix srt file with sentences on identical tiemestamps
#!/usr/bin/env ruby
# frozen_string_literal: true
class SrtFix
autoload(:Pathname, 'pathname')
def initialize(filepath)
@filepath = Pathname.new(filepath)
end
def parse
filepath.read.split(/\n{2,}/).map do |s|
{
position: s.lines.fetch(0).chomp,
time: s.lines.fetch(1).chomp,
sentence: s.lines[2..-1].map(&:chomp).join("\n"),
}
end
end
def lines
[].tap do |result|
parse.each do |parsed|
last = result&.last || {}
{
position: parsed[:position],
time: parsed[:time],
sentence: parsed[:time] != last[:time] ? parsed[:sentence] : [
last[:sentence],
parsed[:sentence],
].join("\n")
}.yield_self do |v|
if parsed[:time] != last[:time]
result.push(v)
else
result[result.size - 1] = v
end
end
end
end.map do |item|
[item.values, nil].join("\n")
end.join("\n").lines
end
def call
lines.tap { |v| filepath.write(v.join) }
end
protected
attr_reader :filepath
end
if __FILE__ == $0
ARGV.fetch(0).yield_self { |file| SrtFix.new(file).call }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment