17:31 2022/06/02 3622
[vue3+element-plus+webman]机器翻译聚合接口
依次看了阿里云,腾讯云,百度云的机器翻译接口,阿里云一个月有100w字符的免费额度,腾讯云一个月有500w字符免费额度,百度云一年500w字符免费额度,但是百度翻译有个开放平台,这上面最基础版的完全免费的但是限制QPS为1,对于轻度个人使用完全够了,高级版一个月也是有200w字符的免费额度,由此,腾讯云和百度感觉比较“良心啊”。
阿里云
他有php的sdk可供使用,支持composer包管理composer require alibabacloud/sdk
调用也很方便
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
// 创建一个全局客户端
AlibabaCloud::accessKeyClient('<your-access-key-id>', '<your-access-key-secret>')
->regionId('cn-hangzhou')
->asGlobalClient();
try {
$result = AlibabaCloud::alimt()
->v20181012() //通用版本
->translateGeneral()
->method('POST') //设置请求POST
->withSourceLanguage('en') //源语言
->withSourceText('book') //原文
->withFormatType('text') //翻译文本的格式
->withTargetLanguage('zh') //目标语言
->request();
\print_r($result->toArray());
} catch (ServerException $e) {
\print_r($e->getErrorMessage());
\print_r($e->getRequestId());
} catch (ClientException $e) {
\print_r($e->getErrorMessage());
}
也不需要自己去组装签名什么的了,很方便。
腾讯云
他也有php的sdk可供使用,支持composer包管理composer require tencentcloud/tencentcloud-sdk-php
他的调用代码可以去腾讯云后台ApiExplorer自动生成
require_once 'vendor/autoload.php';
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Tmt\V20180321\TmtClient;
use TencentCloud\Tmt\V20180321\Models\TextTranslateRequest;
try {
$cred = new Credential("SecretId", "SecretKey");
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("tmt.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new TmtClient($cred, "ap-chongqing", $clientProfile);
$req = new TextTranslateRequest();
$params = array(
"SourceText" => "hello world",
"Source" => "auto",
"Target" => "zh",
"ProjectId" => 0
);
$req->fromJsonString(json_encode($params));
$resp = $client->TextTranslate($req);
print_r($resp->toJsonString());
}
catch(TencentCloudSDKException $e) {
echo $e;
}
这个也是一样,当然自己拼接签名这些也是可以的,腾讯云阿里云都有提供签名生成算法。
百度翻译开放平台(不是百度云)
这个就没有现成的php sdk使用了,不过他的签名方式很简单,下面是一个官方的完整请求的示例,php用curl就可以了,也支持post方式请求。http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
$params = [
'q'=>$text,
'from'=>$source,
'to'=>$target,
'appid'=>'你的appid',
'salt'=>md5(time().rand(1000,9999))
];
$params['sign'] = get_bd_sign($params,'你的key');
$rst = curlPost('https://fanyi-api.baidu.com/api/trans/vip/translate',http_build_query($params),['Content-Type:application/x-www-form-urlencoded']);
function get_bd_sign(array $arr,string $app_key)
{
return md5($arr['appid'].$arr['q'].$arr['salt'].$app_key);
}
这样的话,就可以选择性使用接口了,但是腾讯云的接口重复翻译相同内容,也会计算字符数的,所以可以在本地数据库缓存一下翻译的内容。