LoginSignup
6
5

More than 5 years have passed since last update.

NICT の自動翻訳 API を Rails で使う

Last updated at Posted at 2017-10-14

NICTの自動翻訳APIのページでは色々な言語で利用例の紹介がされているけれど,PythonとかJavaとかの紹介しかなくて,Rubyから利用する方法は書いてなかったので書いてみた.Railsで使えるようになるとWebサービスと連携するときも便利.

NICT のサイトで登録

  1. NICTのサイトでユーザ登録.
  2. ログインしてから,「ツール」>「WebAPI」>「自動翻訳リクエスト」の「登録」の順にクリック
  3. 用途に合わせてどれかクリック.今回は「汎用NMT 【日本語 - 英語】」の右にある「URL」をクリック
  4. リクエストURL,API key, API secret の三つをメモ.あとは,ログインのときのユーザ名も必要.

Railsのサイトを作成

rails new sampleApp でサイトを作成

% rails new sampleApp

Gemfile に gem 'oauth' を追加して,oauth をインストール.

Gemfile
gem 'oauth'
% bundle install

適当にコントローラーを作成.ここでは,Welcome というコントローラに index というメソッドを定義した.

% rails g controller welcome index

welcome controller 関係のファイルを次のように変更.動作確認するだけなので,まずは ruby ファイルに直接keyとかpasswordとか書いてしまう.このままgithubなどに上げないように注意!

app/controllers/welcome_controller.rb
require 'json'
require 'oauth'

class WelcomeController < ApplicationController
  def index
    consumer_key = 'API key'
    consumer_secret = 'API secret'
    url = 'リクエストURL(https://....)'
    name = 'ログインのときのユーザ名'
    text = '隣の客はよく柿食う客だ'

    consumer = OAuth::Consumer.new(consumer_key, consumer_secret)
    endpoint = OAuth::AccessToken.new(consumer)

    response = endpoint.post(url,{key: consumer_key, type: 'json', name: name, text: text})
    @result = JSON.parse(response.body)
  end
end

app/views/welcome/index.html.erb
<%= @result['resultset']['result']['text'] %>

動作確認

Rails サーバを起動.
shell-session
% bundle exex rails server

http://localhost:3000/welcome/index を見て,テキストが翻訳されていることを確認.たぶんこんなことが書いてある.

Our neighbor's guest is a guest who eats lots of persimmons.

問題点・注意点

  • API Key をrubyソースに直接書くべきではないので,secrets.ymlなどから読み込むように改良すべし
  • 翻訳したいテキストが直接rubyのソースに書いてあるのは変なので,フォームで入力できるようにするなり,どこかから取ってくるなり適当に変更すべし
  • 思いがけない翻訳結果が出てきたりして面白い
  • 商用に使う場合にはお問い合わせを
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5