Files
GEOVizor_PHP/monitoring/translation_api.php
2023-11-07 19:51:49 +06:00

230 lines
8.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Key</title>
<script>
/*if (location.protocol != 'https:')
{
location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}*/
function getXmlHttp()
{
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (ee) {
}
}
if (typeof XMLHttpRequest!='undefined') {
return new XMLHttpRequest();
}
}
function Request()
{
let data={
sourceLanguageCode: "ru",
targetLanguageCode: "en",
texts: ["Книга"]
};
let xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function(xmlhttp)
{
return function()
{
if (xmlhttp.readyState == 4)
{
alert(xmlhttp.responseText);
}
}
}(xmlhttp);
xmlhttp.open("POST",'https://translate.api.cloud.yandex.net/translate/v2/translate',true);
alert(JSON.stringify(data));
xmlhttp.send(JSON.stringify(data));
}
</script>
</head>
<body>
Перевожу:<br>
<?php
//Пытаюсь перевести недостающие слова с русского на английски если перевода нет (к слову приписываю признак автоматического перевода)
require_once("./config.php");
require_once("../resources/metadata/include/tools.php");
/*
//Для того чтобы отсылать в ГУГЕЛ нужно авторизоваться! Делаю это по инструкции из: https://usefulangle.com/post/9/google-login-api-with-php-curl
$clientId = "232776754177";
$clientSecret = "AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI";
$clientRedirectURL = "http://127.0.0.1";
$login_url = 'https://accounts.google.com/o/oauth2/v2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/cloud-translation') . '&redirect_uri=' . urlencode($clientRedirectURL) . '&response_type=code&client_id=' . $clientId . '&access_type=online';
if (!isset($_GET['code'])){
header("location: $login_url");
} else {
$code = filter_var($_GET['code'], FILTER_SANITIZE_STRING);
$curlGet = '?client_id=' . $clientId . '&redirect_uri=' . $clientRedirectURL . '&client_secret=' . $clientSecret . '&code='. $code . '&grant_type=authorization_code';
$url = 'https://www.googleapis.com/oauth2/v4/token' . $curlGet;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$data = curl_exec($ch);
$data = json_decode($data, true);
curl_close($ch);
$accessToken = $data['access_token'];
$apiKey = "AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI";
$projectID = "232776754177";
$target = "https://translation.googleapis.com/v3/projects/$projectID:translateText?key=$apiKey";
$headers = array(
"Content-Type: application/json; charset=utf-8",
"Authorization: Bearer " . $accessToken,
"x-goog-encode-response-if-executable: base64",
"Accept-language: en-US,en;q=0.9,es;q=0.8"
);
$requestBody = array();
$requestBody['sourceLanguageCode'] = "en";
$requestBody['targetLanguageCode'] = "pt";
$requestBody['contents'] = array("So, I guess this thing works?");
$requestBody['mimeType'] = "text/plain";
$ch = curl_init($target);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestBody));
$data = curl_exec($ch);
curl_close($ch);
echo $data;
}
*/
$db=connectToDB();
$db->exec("SET NAMES 'UTF8';");
$sql="select identifier from main._translations where del=false group by identifier";
$res = NULL;
try
{
$res = $db->query($sql);
}catch (Exception $e)
{
echo $e->getMessage();
}
if($res!=NULL && $res->rowCount()>0) {
while ($row = $res->fetch(PDO::FETCH_NUM)) {
//Выбираю перевод на русском
$type="NULL";
$translate="";
$sql="select translation,type from main._translations where identifier='".$row[0]."' and language_id=(select id from main._languages where short_name='ru');";
$res2 = NULL;
try
{
$res2 = $db->query($sql);
}catch (Exception $e)
{
echo $e->getMessage();
}
if($res2!=NULL && $res2->rowCount()>0) {
while ($row2 = $res2->fetch(PDO::FETCH_NUM)) {
$translate=$row2[0];
if($row2[1]===true) $type='true';
if($row2[1]===false) $type='false';
}
}
if($translate!=''){
$sql="select l.*,(select translation from main._translations t where t.del=false and t.language_id=l.id and identifier='".$row[0]."' limit 1) as translation from main._languages l where l.del=false;";
$res3 = NULL;
try
{
$res3 = $db->query($sql);
}catch (Exception $e)
{
echo $e->getMessage();
}
if($res3!=NULL && $res3->rowCount()>0) {
while ($row3 = $res3->fetch(PDO::FETCH_ASSOC)) {
//$translate=$row3[0];
if($row3['translation']==''){ //Если не переведён то пытаюсь перевести
echo 'short_name='.$row3['short_name'].' identifier='.$row[0].' text='.$translate.'<br>';
$myObj = new stdClass();
$myObj->target = $row3['short_name'];
$myObj->q = array($translate);
$json=json_encode($myObj);
//$json='{"q": ["Hello world", "My name is Jeff"], "target": "de"}';
echo $json."<br>";
$json=getURLText("https://translation.googleapis.com/language/translate/v2?key=AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI",$json);
echo $json;
echo "<br>";
/*
$myObj = new stdClass();
$myObj->sourceLanguageCode = "ru";
$myObj->targetLanguageCode = $row3['short_name'];
$myObj->contents = array($translate);
$json=json_encode($myObj);
$json='{"sourceLanguageCode": "en","targetLanguageCode": "ru","contents": ["Dr. Watson, come here!", "Bring me some coffee!"]}';
echo getURLText("https://translation.googleapis.com/v3/projects/AIzaSyAOtc8E9Yg0O1uuZ_0EMYgqFP7W3p_0LGI:translateText",$json);
*/
$myObj=json_decode($json); //{ "data": { "translations": [ { "translatedText": "km / h", "detectedSourceLanguage": "bg" } ] } }
if(!property_exists($myObj,'error')) {
echo '<br>';
$sql = "insert into main._translations(language_id,identifier,translation,type,auto)values(" . $row3['id'] . ",'" . $row[0] . "','" . addslashes($myObj->data->translations[0]->translatedText) . "',$type,true);";
echo $sql . '<br>';
try
{
$db->query($sql);
}catch (Exception $e)
{
echo $e->getMessage();
exit;
}
}
}
}
}
}
}
}
//http://translate.google.com/translate_a/t?client=x&text=hello&sl=en&tl=ru
//Если есть перевод с Русского то переводим с него если нет то с Английского
?>
<h2>Генерация</h2>
<table>
<tr><td>Параметр</td><td><input id="data" type="text" size="30" value="012345678912"></td></tr>
<tr><td></td><td style="text-align: right;"><button onclick="Request();">Отправить</button></td></tr>
</table>
</body>
</html>