Azure Translator Text APIを使ってphpで翻訳する

file_get_contentsしたjsonをdecodeします。

$key = 'hogehoge';

$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";
$params = "&to=en";
$text = "1文をバラバラにして単語レベルで翻訳をするのではなく、1文をひとまとめにして翻訳";

if(!function_exists('com_create_guid')){
	function com_create_guid(){
		return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
		mt_rand(0, 0xffff), mt_rand(0, 0xffff),
		mt_rand(0, 0xffff),
		mt_rand(0, 0x0fff) | 0x4000,
		mt_rand(0, 0x3fff) | 0x8000,
		mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
	}
}

function Translate ($host, $path, $key, $params, $content) {
    $headers = "Content-type: application/json\r\n" .
        "Content-length: " . strlen($content) . "\r\n" .
        "Ocp-Apim-Subscription-Key: $key\r\n" .
        "X-ClientTraceId: " . com_create_guid() . "\r\n";
    $options = array (
        'http' => array (
            'header' => $headers,
            'method' => 'POST',
            'content' => $content
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents ($host . $path . $params, false, $context);
    return $result;
}

$requestBody = array (
    array (
        'Text' => $text,
    ),
);
$content = json_encode($requestBody);
$result = Translate($host, $path, $key, $params, $content);


$json = json_decode($result);
echo $json[0]->translations[0]->text;

これは。。。

eminem lose yourself
——-
Look, if you had one shot, one opportunity
To seize everything you ever wanted
One moment
Would you capture it or just let it slip?
Yo
His palms are sweaty, knees weak, arms are heavy
There’s vomit on his sweater already, mom’s spaghetti
He’s nervous, but on the surface he looks calm and ready
To drop bombs, but he keeps on forgettin’
What he wrote down, the whole crowd goes so loud
He opens his mouth, but the words won’t come out
He’s chokin’, how, everybody’s jokin’ now
The clocks run out, times up, over, blaow!
Snap back to reality, oh there goes gravity
Oh, there goes Rabbit, he choked
He’s so mad, but he won’t give up that easy? No
He won’t have it, he knows his whole back city’s ropes
It don’t matter,
He’s dope,…

ラップの翻訳って難しいと思うが、
結果

ほお

翻訳のアルゴリズムは?

前:ルールベース翻訳や統計翻訳
->文法や単語などのルールを一つ一つ登録して翻訳

後:ニューラルネットワーク
->1文をバラバラにして単語レベルで翻訳をするのではなく、1文をひとまとめにして翻訳

そうなのか、VoiceTraとかも統計翻訳の機械学習かと思ってた。。
NICT(情報通信研究機構)
http://www.nict.go.jp/
ここは興味ある。金融庁以来。

しかし予算500億も使ってんのかよ。。コロプラの売上高と一緒じゃんか。。ちくしょー羨ましすぎる。。
https://www.nict.go.jp/pdf/business-report-2016.pdf

ibm translator

使ってみる。

[vagrant@localhost translator]$ curl -u "username":pass" \
> -H "Accept: application/json" \
> "https://gateway.watsonplatform.net/language-translator/api/v2/translate?model_id=en-ja&text=ibm+translator"
{
  "translations" : [ {
    "translation" : "IBM変換プログラム"
  } ],
  "word_count" : 2,
  "character_count" : 14
}

幾つか試したが、レスポンスがなかったり、tokyo -> “translation” : “統教” と精度がイマイチだったり。。。
やってることは凄いんだろうけど、これ以上深堀りする気ナシ。

IBM developerWorks

IBMって、どうなんでしょう?
勝屋さんが元IBMのVCですよね。

とりあえず、翻訳系のサービスが作りたい。
っま、動かしながら考えましょう。

watson APIs Language Translator

The IBM Watson Language Translator service converts text input in one language into a destination language for the end user using background from domain-specific models. Translation is available among Arabic, Chinese (Simplified and Traditional), English, French, Portuguese, German, Spanish, Dutch, Turkish, Russian, Korean, Italian and Polish (some languages may not be available for all domains).

日本語 原文

現在、我が国では、IT投資が活発化するとともに、グローバルな事業展開が一層の拡大傾向にあります。一方で、先端IT技術を活用した新しいビジネスモデルへの需要が高まっています。企業に対しても、持続可能な社会の実現を見据えた投資によってイノベーションを発揮し、事業を通じた社会課題の解決に積極的に取り組んでいくことが求められています。

watson 翻訳結果(英語)
想像以上に悪くない気がする。。

In Japan, IT investment is becoming more active, and global business expansion is becoming more and more expanding.On the other hand, there is a growing demand for new business models using cutting-edge IT technologies.It is also necessary for companies to exert innovation through investment that is a view to realizing a sustainable society, and to actively work on solving social issues through business.

あああああああああああああああああ
Japanese からは Englishしかないいいいいいいいいいいい
というか、英語以外は、ほとんど英語への翻訳しかないですね。

tableの背景色を縞々にする

偶数なら tr:nth-child(even)、奇数なら tr:nth-child(odd)で指定します。

#table tr:nth-child(even) { 
   background-color: #ECECEC;
  }

PC版

SP版

大分見た目が良くなった(笑)

さあ、次は、ドメインを取得して、Vagrant -> VPSのサーバー側の構築。
バーチャルホスト、mongoDB、php mongoDBドライバーのインストールまでは何も問題なく終了。

trafficの分類

document.referrerで取得したURLにRegular Expressionで該当すればフラグを立てたい。

1.Organic Search
https://www.google.co.jp
https://www.bing.com/
https://www.yahoo.co.jp/
https://www.msn.com/ja-jp/
http://www.baidu.com/

2.Social
https://www.facebook.com/
https://twitter.com/?lang=ja
https://www.instagram.com/?hl=ja
https://line.me/ja/

3.Direct

4.Referral

早速書いてみる。

$url = "ttps://www.google.co.jp/search?q=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&oq=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&aqs=chrome..69i57j69i61l3j0l2.3764j0j7&sourceid=chrome&ie=UTF-8";
if(preg_match("/www.google/", $url)){
  $channel = "Organic Search"; 
  $media = "google";
} else{
  $channel = "else";
}
echo $channel;

項目を増やします。yahooはco.jpもcomも検索時に、https://search.yahoo.comとサブドメインにsearchが付きます。(分かり易い!)

$url = "http://hpscript.com/ip/";
if(empty($url)){
  $channel = "Direct"; 
}elseif(preg_match("/www.google/", $url)){
  $channel = "Organic Search"; 
  $media = "google";
}elseif(preg_match("/www.bing/", $url)){
  $channel = "Organic Search"; 
  $media = "bing";
}elseif(preg_match("/search.yahoo/", $url)){
  $channel = "Organic Search"; 
  $media = "yahoo";
}elseif(preg_match("/www.baidu/", $url)){
  $channel = "Organic Search"; 
  $media = "baidu";
}elseif(preg_match("/www.facebook/", $url)){
  $channel = "Social"; 
  $media = "facebook";
}elseif(preg_match("/twitter/", $url)){
  $channel = "Social"; 
  $media = "twitter";
}elseif(preg_match("/www.instagram/", $url)){
  $channel = "Social"; 
  $media = "twitter";
}elseif(preg_match("/line/", $url)){
  $channel = "Social"; 
  $media = "line";
}else{
  $channel = "Referral";
}
echo $channel;

doubleclick.php(js受け取り)のphpで処理を書いていきます。

if(!is_null($data["acquisition"])){
	$url = $data["acquisition"];
	if(empty($url)){
	  $channel = "Direct"; 
	  $media = "(not set)";
	}elseif(preg_match("/www.google/", $url)){
	  $channel = "Organic Search"; 
	  $media = "google";
	}elseif(preg_match("/www.bing/", $url)){
	  $channel = "Organic Search"; 
	  $media = "bing";
	}elseif(preg_match("/search.yahoo/", $url)){
	  $channel = "Organic Search"; 
	  $media = "yahoo";
	}elseif(preg_match("/www.baidu/", $url)){
	  $channel = "Organic Search"; 
	  $media = "baidu";
	}elseif(preg_match("/www.facebook/", $url)){
	  $channel = "Social"; 
	  $media = "facebook";
	}elseif(preg_match("/twitter/", $url)){
	  $channel = "Social"; 
	  $media = "twitter";
	}elseif(preg_match("/www.instagram/", $url)){
	  $channel = "Social"; 
	  $media = "twitter";
	}elseif(preg_match("/line/", $url)){
	  $channel = "Social"; 
	  $media = "line";
	}else{
	  $channel = "Referral";
	  $media = $url;
	}
	$data = $data + array('channel'=>$channel, 'media'=>$media);
}

directの場合は、mediaは(not set)

urlがbingにマッチしたら、channelはorganic searchになります。

mongoDBにも入っています。

つづいて、データを入れてanalytics側のviewをつくっていきます。
organic, social, direct, refferalの分類はchart.jsを使いたい。

OK!!!!!!!!!!!!!!!!!!!!!!!
リファクタリングして、次はスタイリングです!
今回はweb fontを使って、fontにもこだわりたい。

document.referrer

document.referrerでどう入るか?
hpscript.comにipのディレクトリを作って、aタグを設置する。

js

a.push(['acquisition',document.referrer]);

document.referrerだと、プロトコルから入る。

リファラーを定義

<script>
Object.defineProperty(document,"referrer",
{value:"https://www.google.com/"});
console.log(document.referrer);
</script>
<a href="http://192.168.33.10:8000/wwwroot/view.php">リンク</a>

例えば、google, yahooで「機械学習」と検索すると、検索結果のURLは以下のようになる。

https://www.google.co.jp/search?q=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&oq=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&aqs=chrome..69i57j69i61l3j0l2.3764j0j7&sourceid=chrome&ie=UTF-8

https://search.yahoo.co.jp/search;_ylt=A2RA0Dp_2OVaYhIAmnaJBtF7?p=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&search.x=1&fr=top_ga1_sa&tid=top_ga1_sa&ei=UTF-8&aq=-1&oq=%E6%A9%9F%E6%A2%B0%E5%AD%A6%E7%BF%92&at=&aa=&ai=s2uf6ZtEQS6rZIfyd2LYHA&ts=4050

マルチドメインの場合は
-https://wwww.hoge
-https://hoge
-http://www.hoge
-http://hoge

その他検討事項
-メールの場合
-直リンク
-サブドメインがある場合

ページごとのユニークなユーザー数(cookie単位)を取得する

cookieとpageを文字列で連結して、array_uniqueでcookieとpage完全一致の重複を削除して、そこからsubstrでurlのみ切り抜いて、array_count_valuesする。
※最初、cookieとpageで連想配列をつくって、そこから、連想配列のvalueの重複削除しようとしたが、何度やってもうまくいかず、これ考えるのに、4~5時間くらいかかった。。。

foreach ($cursor as $document) {
  if(!is_null($document->referrer) and $document->referrer != ""){
  $referrer = $document->referrer;
  $avgtime = $document->avgtime;
  $data1[] = array($referrer=>$avgtime); 
  }
  $page[] = $document->page;

  $a = $document->cookie;
  $b = $document->page;
  $data2[] = $a.$b;
}

$unique = array_values(array_unique($data2));
foreach($unique as $value){
    $urls[] = substr($value, 10);
}
$urls = array_count_values($urls);
arsort($urls);
var_dump($urls);

よしよしよし

繋げると

viewに反映

次は鬼門のリファラー関係
1.document.referrer でどれだけ取れるか
2.ga.js・twitterのsessionがどうやって定義しているか参考にする
3.vagrantだけでなく、実ドメインからのリンクでテストしながらつくる
->GAのようにorganic searchの検索ワードは抽出できないので、代替案を考える