PHPにて「みんなの自動翻訳」のAPIで指定したテキストの言語判定する方法
2024/10/03
迷惑メール対策等でメール本文が日本語のもののみ受信したい場合がある。ただ、本文内にURLやメールアドレスが入ることもあると思われるので正規表現でどうこうするというのは難しそう。そこで「みんなの自動翻訳」の言語判定APIを使えばいいんじゃないかと思った。以下に利用方法をメモ。
事前準備
「みんなの自動翻訳」についてと、事前準備については過去記事を参照すること。
利用方法
ソースコード
定数部分は適宜書き換えること。
<?php
define('API_KEY', 'xxxxxxxxxxxx');
define('API_SECRET', 'xxxxxxxxxxxx');
define('API_NAME', 'xxxxxxxxxxxx');
//アクセストークンの取得
$token_url = 'https://mt-auto-minhon-mlt.ucri.jgn-x.jp/oauth2/token.php';
$data = [
'grant_type' => 'client_credentials',
'client_id' => API_KEY,
'client_secret' => API_SECRET
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if( !curl_errno($ch) && $http_code == '200' ){
$res = json_decode($res, true);
$access_token = $res['access_token'];
}else{
echo 'ERROR: ' . curl_error($ch);
exit();
}
curl_close($ch);
//翻訳
$translation_url = 'https://mt-auto-minhon-mlt.ucri.jgn-x.jp/api/langdetect/';
$text = "Quickly translate text and document files, whether you're working as an individual or as a team.テキストや文書ファイルを瞬時に翻訳します。個人でもチームでも、高精度の翻訳をご活用いただけます。";
$data = [
'text' => $text,
'key' => API_KEY,
'access_token' => $access_token,
'name' => API_NAME,
'type' => 'json',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $translation_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if( !curl_errno($ch) && $http_code == '200' ){
$res = json_decode($res, true);
}else{
echo 'ERROR: ' . curl_error($ch);
exit();
}
curl_close($ch);
var_dump($res['resultset']['result']);
出力結果
以下のように「言語は日本語で類似度が91%」という結果が出力された。
array(1) {
["langdetect"]=>
array(1) {
[0]=>
array(2) {
["lang"]=>
string(2) "ja"
["rate"]=>
float(0.91)
}
}
}
所感
言語が日本語且つ類似度が〇%以上ならメール送信する、みたいな処理を入れることで迷惑メール対策になりそう。
関連記事
-
-
画像をアップロードすると複数サムネイルを生成する方法
フォームで画像をアップロードすると、予め定めておいた大中小のサイズでサムネイル画 ...
-
-
MySQLでランダムにデータを取得しつつページング機能も実装する方法
MySQLからデータを持ってくる際にランダムな表示を行ってほしいと言われた。ただ ...
-
-
formにGoogle reCAPTCHA v3を組み込み、PHPでスコア判定する方法
だいぶ前にGoogle reCAPTCHA v2をformに組み込むという記事を ...
-
-
PHPにて同一サーバの別ディレクトリでセッションを振り分ける方法
同じサーバ内にmemberとownerの別ディレクトリがあり、それぞれにsess ...
-
-
eval関数について
ちょくちょく見ることがあったeval関数について、 なんとなく分かってきたのでメ ...