Last active
December 20, 2022 18:57
-
-
Save diego-aslz/865f690777d798cf2769d385226051eb to your computer and use it in GitHub Desktop.
Extract and translate MKV subtitles
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
#!/usr/bin/env ruby | |
# Ruby script to extract and translate subtitles from MKV files from English to Portuguese (but you can customize this) | |
# | |
# Dependencies: | |
# | |
# 1. `gem install srt` | |
# 2. `brew install translate-shell mkvtoolnix` | |
# | |
# Usage: | |
# | |
# translate_subs.rb [FILE] | |
# | |
# Notice: it assumes the subtitles are on track index 3, which may change from file to file. | |
# Tracks can be checked using `mkvinfo file.mkv` | |
require 'shellwords' | |
require 'pathname' | |
require 'srt' | |
ARGV.each do |file| | |
path = Pathname(file) | |
en_srt = Shellwords.escape("#{path.basename('.*')}.en.srt") | |
pt_srt = Shellwords.escape("#{path.basename('.*')}.srt") | |
`mkvextract tracks #{Shellwords.escape(file)} 3:#{en_srt}` | |
# Join split lines for better translation | |
srt = SRT::File.parse(File.new(en_srt)) | |
total = srt.lines.size | |
srt.lines.each_with_index do |l, idx| | |
l.text = [`trans -no-warn -no-autocorrect -brief en:pt-BR #{Shellwords.escape(l.text.join(' '))}`.strip] | |
printf("\r#{file} - %d%%", (idx + 1) * 100 / total) | |
end | |
printf("\r#{file} - %d%%", 100) | |
puts | |
IO.write(pt_srt, srt.to_s) | |
`rm #{en_srt}` | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment