Watson Natural Language Understandingの感情分析触ってみた

<img src="https://cl.ly/1X153z1g1t05/ss001.png">

Watson Natural Language Understandingの感情分析触ってみたところ面白そうだったのでメモ。他にもNLUのAPIあるんですけど、あんまり細かくは分からないんですよね。

# 翻訳

感情抽出に関しては英語にしか対応していませんので、まずはMicrosoft Translator APIで日本語を英語に翻訳しましょう。

[Microsoft Translator](https://www.microsoft.com/ja-jp/translator/getstarted.aspx)でKey取得しておいて下さい。

こんな感じ。

```translate.php
<?php

define('AZURE_KEY', 'YOUR_AZURE_KEY');
define('AUTH_URL', 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');

$text = $_GET['text'];
$from = $_GET['from'];
$to = $_GET['to'];

try
{
  $accessToken = GetAccessToken();
  $params = 'text=' . urlencode($text) . '&from=' . $from . '&to=' . $to . '&appId=Bearer+' . $accessToken;;
  $url = 'http://api.microsofttranslator.com/v2/Http.svc/Translate?'  .$params;
  $response = Request( $url );
  echo $response;
} catch(Exception $e) {
    echo $e->getMessage();
}

function GetAccessToken()
{
  $params = json_encode('{body}');
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, AUTH_URL );
  curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
  curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($params),
    'Ocp-Apim-Subscription-Key: ' . AZURE_KEY
    )
  );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

  $response = curl_exec($ch);
  if(curl_errno($ch)){
    throw new Exception( curl_error( $ch ) );
  }
  curl_close( $ch );

  return $response;
}

function Request( $url )
{
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: text/xml' ) );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

  $response = curl_exec($ch);
  if(curl_errno($ch)) {
    throw new Exception(curl_error($ch));
  }
  curl_close( $ch );

  return $response;
}

?>
```

# 感情分析

```html:page.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="ja" xml:lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" />
<title>Watson NLU Test</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
  $("#text").focus();
  $('#text').keypress(function(e) {
    if (e.which == 13) {
      $("#button").click();
    }
  });
  $("#button").click(function(){
    $("#result").html("Understanding...");
    var translated = "";
    $.ajax({
      type: "GET",
      url: "translate.php?from=ja&to=en&text=" + encodeURI($("#text").val()),
      async: false,
      success:function(data){
        console.log("success");
        console.log(data);
        translated = data;
      },
      error:function(){}
    });

    var url = "https://watson-api-explorer.mybluemix.net/natural-language-understanding/api/v1/analyze?version=2017-02-27&features=emotion&text=" + encodeURI(translated);
    console.log(url);
    $.ajax({
      type: "GET",
      url: url,
      success: function( data ){
        console.log("success");
        var emotions = data.emotion.document.emotion;
        console.log(data);
        console.log(emotions);
        $("#result").html("<span style='font-size:" + (20 + 50 * (emotions.anger / 1.0)) +
          "pt'>😡</span><span style='font-size:" + (20 + 50 * (emotions.disgust / 1.0)) +
          "pt'>😵</span><span style='font-size:" + (20 + 50 * (emotions.fear / 1.0)) +
          "pt'>😱</span><span style='font-size:" + (20 + 50 * (emotions.joy / 1.0)) +
          "pt'>😃</span><span style='font-size:" + (20 + 50 * (emotions.sadness / 1.0)) +
          "pt'>😭</span>");
      },
      error: function( XMLHttpRequest, textStatus, errorThrown ){}
    });
  });

});
</script>
</head>
<body>
  <h1>Watson NLU Test</h1>
  <input type="text" id="text">
  <button id="button">Tap Me</button>
  <div id="result"></div>
</body>
</html>
```

# 分析してみる

<img src="https://cl.ly/1X153z1g1t05/ss001.png">
<img src="https://cl.ly/1p1D3I1C3C0N/ss002.png">
<img src="https://cl.ly/0g1C40103Q1w/ss003.png">
<img src="https://cl.ly/3b3D1d3Z1D1N/ss004.png">

# まとめ

翻訳通さずに直接英語渡すとかなり精度出るんですが、翻訳挟むとそうでもないですね。

# 宣伝

<img src="https://cl.ly/0N3r3l1v2t0T/%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%202017-05-19%2014.20.00.png" width=50%>

[LINE BOTを作ろう! Messaging APIを使ったチャットボットの基礎と利用例](https://www.amazon.co.jp/dp/4798150738)

好評発売中！