🇺🇸

Google Translate API で一括多言語翻訳の例

2022/08/31に公開

手動でGoogle翻訳をポチポチしている場合ではない

多言語対応で翻訳データを作るときはGoogle翻訳が便利だが、言語と文言が増え続けると手動では手に負えなくなってくる。いや、言語と文言が増え続けるのは予想がつくので最初から完全自動化しておくべきである。

コード

require "bundler/inline"

gemfile do
  source "https://rubygems.org"
  gem "google-cloud-translate", "1.4.0"
end

API_KEY = "..."

source = {
  :index   => "一覧",
  :show    => "詳細",
  :create  => "作成",
  :update  => "更新",
  :delete  => "削除",
  :confirm => "確認",
}

langs = [:en, :es, :de, :zh_cn]

gcloud = Google::Cloud.new
translate = gcloud.translate(API_KEY)
other = langs.inject({}) do |a, lang|
  hv = source.inject({}) do |a, (key, text)|
    text = translate.translate(text, from: :ja, to: lang).text
    a.merge(key => text)
  end
  a.merge(lang => hv)
end

puts JSON.pretty_generate({ja: source, **other})
# > {
# >   "ja": {
# >     "index": "一覧",
# >     "show": "詳細",
# >     "create": "作成",
# >     "update": "更新",
# >     "delete": "削除",
# >     "confirm": "確認"
# >   },
# >   "en": {
# >     "index": "list",
# >     "show": "detail",
# >     "create": "create",
# >     "update": "update",
# >     "delete": "delete",
# >     "confirm": "confirmation"
# >   },
# >   "es": {
# >     "index": "lista",
# >     "show": "detalle",
# >     "create": "crear",
# >     "update": "actualizar",
# >     "delete": "Eliminar",
# >     "confirm": "confirmación"
# >   },
# >   "de": {
# >     "index": "aufführen",
# >     "show": "Detail",
# >     "create": "schaffen",
# >     "update": "aktualisieren",
# >     "delete": "löschen",
# >     "confirm": "Bestätigung"
# >   },
# >   "zh_cn": {
# >     "index": "列表",
# >     "show": "细节",
# >     "create": "创造",
# >     "update": "更新",
# >     "delete": "删除",
# >     "confirm": "确认"
# >   }
# > }

Discussion