Class: Epub::Translator::Prompt::Translate
- Inherits:
-
Object
- Object
- Epub::Translator::Prompt::Translate
- Defined in:
- lib/epub/translator/prompt/translate.rb
Instance Attribute Summary collapse
-
#prompt ⇒ Object
readonly
Returns the value of attribute prompt.
Instance Method Summary collapse
Instance Attribute Details
#prompt ⇒ Object (readonly)
Returns the value of attribute prompt.
12 13 14 |
# File 'lib/epub/translator/prompt/translate.rb', line 12 def prompt @prompt end |
Instance Method Details
#execute(epub_path:, config_path: nil, prompt: ::TTY::Prompt.new) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/epub/translator/prompt/translate.rb', line 14 def execute(epub_path:, config_path: nil, prompt: ::TTY::Prompt.new) begin EPUB::Parser.parse(epub_path) rescue Errno::ENOENT warn 'Epub not found' return rescue Archive::Zip::UnzipError warn 'Not an Epub' return end translator = Natsukantou::Setup::ConfigLoadOrPrompt.new.execute( prompt: prompt, config_path: config_path, ) lang_from = prompt.ask("Language code to translate from?") lang_from = Natsukantou::LanguageCode.new(lang_from) lang_to = prompt.ask("Language code to translate to?") lang_to = Natsukantou::LanguageCode.new(lang_to) # Make a copy for modification new_epub_path = prompt.ask( 'Where do you want to save the result?', value: epub_path.pathmap("%X.#{lang_to.code}%x") ) FileUtils.copy(epub_path, new_epub_path) book = EPUB::Parser.parse(new_epub_path) items = book.each_page_on_spine.select(&:xhtml?) items_untranslated_index = items.map.with_index do |item, index| if (doc_lang_code = item.content_document.oga.lang) lang = Natsukantou::LanguageCode.new(doc_lang_code) lang.is?(lang_to) ? nil : index else index end end.compact choices = items.map.with_index do |item, index| translated = !items_untranslated_index.include?(index) [item_label(item, translated), item] end.to_h targets = prompt.multi_select( "Select items to translate:", choices, default: items_untranslated_index.map { |index| index + 1 }, per_page: 30, echo: false ) targets.each do |item| output_translation_progress(item) env = Natsukantou::Env.new( dom: item.content_document.oga, lang_from: lang_from, lang_to: lang_to ) translator.call(env) item.content = env[:dom].to_xml item.save end if !targets.empty? puts 'Translation complete.' end end |