Class: I18nTranslator
- Inherits:
-
Object
- Object
- I18nTranslator
- Defined in:
- lib/i18n_translator.rb
Class Method Summary collapse
- .deep_translate(from_hash, to_hash, from_locale, to_locale) ⇒ Object
-
.translate(str) ⇒ Object
don’t need to test this method.
- .translator ⇒ Object
- .update_dictionary!(from_locale, to_locales) ⇒ Object
Class Method Details
.deep_translate(from_hash, to_hash, from_locale, to_locale) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/i18n_translator.rb', line 18 def self.deep_translate(from_hash, to_hash, from_locale, to_locale) ret = {} from_hash.each do |key, val| if val.is_a?(Hash) h = deep_translate(val, to_hash[key] || {}, from_locale, to_locale) ret[key] = Hash[h.sort] else md5_key = "#{key}_md5" md5 = ::Digest::MD5.hexdigest(val) if to_hash[md5_key].nil? || to_hash[md5_key] != md5 ret[md5_key] = md5 ret[key] = translate(val) else ret[md5_key] = to_hash[md5_key] ret[key] = to_hash[key] end end end ret end |
.translate(str) ⇒ Object
don’t need to test this method
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/i18n_translator.rb', line 44 def self.translate(str) # DeepLのほうが望ましいがLLMで代用 ret = self.translator.chat(parameters: { messages: [ { role: "system", content: "You are an excellent translator. We translate strings sent by users into accurate English.\n" + \ "We do not output any content other than the translation.\n" + \ "Please keep the position and number of the new line code(\\n).\n" + \ "Never omit the line feed code at the end of a sentence.", }, { role: "user", content: str, }, ], }) translated = ret.dig("choices", 0, "message", "content") puts("#{str} => #{translated.green}") sleep(1) translated end |
.translator ⇒ Object
39 40 41 |
# File 'lib/i18n_translator.rb', line 39 def self.translator @translator ||= ::Llm::Clients::AzureOpenAi.new end |
.update_dictionary!(from_locale, to_locales) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/i18n_translator.rb', line 3 def self.update_dictionary!(from_locale, to_locales) from_file_paths = I18n.load_path.select { |path| path.match(/#{from_locale}\.yml$/) } from_file_paths.each do |from_file_path| to_locales.each do |to_locale| from_hash = { to_locale.to_s => YAML.load(File.read(from_file_path))[from_locale.to_s], } to_file_path = from_file_path.gsub(/#{from_locale}\.yml$/, "#{to_locale}.yml") to_hash = File.exist?(to_file_path) ? YAML.load(File.read(to_file_path)) : {} to_hash = deep_translate(from_hash, to_hash, from_locale, to_locale) File.write(to_file_path, YAML.dump(to_hash)) end end end |