class SrtTranslate
Class to translate subtitles
Public Class Methods
new(api_key, target_lang, input_path, result_path)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 10 def initialize(api_key, target_lang, input_path, result_path) @file = SRT::File.parse(File.new(input_path)) @deepl_request = DeeplRequest.new(api_key) @target_lang = target_lang FileUtils.touch(result_path) unless File.exist?(result_path) @result_path = result_path end
Public Instance Methods
parse(from_line)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 18 def parse(from_line) @new_content = '' @file.lines.drop(from_line.to_i).each_with_index do |line, index| @new_content << parse_part(line, index + from_line.to_i) end @new_content end
Private Instance Methods
parse_part(line, index)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 28 def parse_part(line, index) str = '' str << "#{index + 1}\n" str << "#{line.time_str}\n" json = translate(line.text.join('\n')) result = shorter(JSON.parse(json)['translations'][0]['text']) str << "#{result}\n\n" save_line(str) end
save_line(line)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 47 def save_line(line) File.open(@result_path, 'a+') { |file| file.write(line) } end
shorter(line)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 42 def shorter(line) short = line.split.each_slice(6).map { |a| a.join ' ' } short.join("\n") end
translate(text)
click to toggle source
# File lib/deepl_srt/srt_translate.rb, line 38 def translate(text) @deepl_request.request(@target_lang, text).body end