Skip to content

Instantly share code, notes, and snippets.

@s-mage
Last active April 1, 2023 16:19
Show Gist options
  • Save s-mage/30ea5e4d49f0fa9daf2fdd014381604b to your computer and use it in GitHub Desktop.
Save s-mage/30ea5e4d49f0fa9daf2fdd014381604b to your computer and use it in GitHub Desktop.
Update rails translations using openAI. Usage: `OpenAITranslation.call`
class HashDiff
class << self
def t(target)
en = YAML.load_file("config/locales/en.yml")["en"]
target = YAML.load_file("config/locales/#{target}.yml")[target.to_s]
for_translation(en, target)
end
def push(target_language, update)
filename = "config/locales/#{target_language}.yml"
target = YAML.load_file(filename)[target_language.to_s]
value = { target_language.to_s => target.deep_merge(update) }
File.write(filename, value.to_yaml)
end
# assume en is always complete and target is maybe not
def for_translation(en, target)
(en.keys | target.keys).index_with do |k|
if en[k] == target[k] || !target[k]
en[k]
elsif Hash === en[k] && Hash === target[k]
HashDiff.for_translation(en[k], target[k])
end
end.compact.select { |_k, v| v.present? }
end
end
end
require "openai"
require_relative("./hash_diff")
OpenAI.configure do |config|
config.access_token = ENV.fetch("OPENAI_ACCESS_TOKEN")
config.organization_id = ENV.fetch("OPENAI_ORGANIZATION")
end
class OpenAITranslation
class << self
def chat(content, lang)
client = OpenAI::Client.new
response = client.chat(
parameters: {
model: "gpt-3.5-turbo",
messages: [
{ role: "system", content: "User sends content in JSON. Translate values of the content to #{lang}, keep keys in English." },
{ role: "user", content: }
],
},
)
response.dig("choices", 0, "message", "content") || raise(response.to_yaml)
end
def t_content(lang)
diff = HashDiff.t(lang)
return if diff.blank?
diff.to_json
end
def t(lang)
content = t_content(lang)
return if content.blank?
update = chat(content, lang)
puts update
HashDiff.push(lang, JSON.parse(update))
end
def call
langs = Dir.entries("config/locales")[2..].map { |x| x.sub(".yml", "") }
langs.map { |lang| t(lang) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment