Microsoft Translator APIを使ってLINEから翻訳させてみた

引続き自分に使えるLINEBotシリーズをひたすら研究中。 海外輸入でサポートに問い合わせることが多いので翻訳できるLINEBotを作ってみた。

翻訳ライブラリ

Google Cloud Translation APIは有料のようなので、Microsoft Translator APIを利用することにした。 200百万文字/月までは無料で利用できるようだ、Microsoftありがとう。

登録方法などはこの記事が詳しい。

Microsoft Translator APIを使ってみる - Qiita
Microsoft Translator APIを使ってみる - Qiita...

プログラム

プログラムはこの記事をほぼ真似させてもらった。

Microsoft Translator APIを使ってみた - Qiita
Microsoft Translator APIを使ってみた - Qiita...

日本語が混じっていれば入力は日本語と判定し英語に翻訳、それ以外は逆とした。

<?php

require_once('./LINEBotTiny.php');

$channelAccessToken = 'YOUR_ACCESS_TOKEN';
$channelSecret = 'YOUR_SECRET';

$client = new LINEBotTiny($channelAccessToken, $channelSecret);

foreach ($client->parseEvents() as $event) {
    switch ($event['type']) {
        case 'message':
            $message = $event['message'];

            switch ($message['type']) {
                case 'text':

                    $client->replyMessage(array(
                        'replyToken' => $event['replyToken'],
                        'messages' => array(
                            array(
                                'type' => 'text',
                                'text' => translation($message['text'])
                            )
                        )
                    ));

                    break;
                default:
                    error_log("Unsupporeted message type: " . $message['type']);
                    break;
            }
            break;
        default:
            error_log("Unsupporeted event type: " . $event['type']);
            break;
    }
};

function translation($text) {
  $client_id = "YOUR_ID";
  $client_secret = "YOUR_SECRET";
  $access_token = getAccessToken($client_id, $client_secret)->access_token;

  $text = mb_convert_kana($text, 'KVas');

  $from = '';
  $to = '';
  if (preg_match('/[ぁ-んァ-ヶー一-龠、。]/u',$text)) {
    $from = 'ja';
    $to = 'en';
  }
  else{
    $from = 'en';
    $to = 'ja';
  }


  return tranlator($access_token, array(
          'text' => $text,
              'to' => $to,
              'from' => $from));

}


  function getAccessToken($client_id, $client_secret, $grant_type = "client_credentials", $scope = "http://api.microsofttranslator.com"){
      $ch = curl_init();
      curl_setopt_array($ch, array(
          CURLOPT_URL => "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/",
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_POST => true,
          CURLOPT_POSTFIELDS => http_build_query(array(
              "grant_type" => $grant_type,
              "scope" => $scope,
              "client_id" => $client_id,
              "client_secret" => $client_secret
              ))
          ));
      return json_decode(curl_exec($ch));
  }

  function tranlator($access_token, $params){
      $ch = curl_init();
      curl_setopt_array($ch, array(
          CURLOPT_URL => "https://api.microsofttranslator.com/v2/Http.svc/Translate?".http_build_query($params),
          CURLOPT_SSL_VERIFYPEER => false,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_HEADER => true,
          CURLOPT_HTTPHEADER => array(
              "Authorization: Bearer ". $access_token),
          ));
      preg_match('/>(.+?)<\/string>/',curl_exec($ch), $m);
      return $m[1];
  }

動作

精度や速度は全く問題なしだ。これはかなり使えそうな予感。 cap.PNG

(追記) ちょうどこの記事を見て、 ニューラルネット翻訳に対応してみた。

Microsoft Translate API を用いた Slack ニューラルネット翻訳コマンドの実装 - Qiita
Microsoft Translate API を用いた Slack ニューラルネット翻訳コマンドの実装 - Qiita...