1、控制器代码如下:
<?php
namespace app\admin\controller;
use app\admin\model\Trans as transModel;
use think\facade\Db;
class Trans extends Base{
/*腾讯单条文本翻译*/
public function index(){
try {
$text = input('text','蔡琳我爱你');
$source = input('source','zh');
$target = input('target','ja');
$resText = transModel::single($text, $source, $target);
return json(['code' => 200,
'msg' => 'success',
'data' => [
'source_text' => $text,
'target_text' => $resText
]]);
} catch (\Exception $e) {
return json(['code' => 500,
'msg' => $e->getMessage(),
'data' => []]);
}
}
/*批量翻译*/
public function batch()
{
try {
$list = input('list/a', ['蔡琳','蔡琳我爱你','蔡琳是一个漂亮的韩国女生']);
$source = input('source', 'zh');
$target = input('target', 'en');
$result = transModel::batch($list, $source, $target);
return json([
'code' => 200,
'data' => $result
]);
} catch (\Exception $e) {
return json(['code' => 500, 'msg' => $e->getMessage()]);
}
}
}2、模型代码如下:
<?php
namespace app\admin\model;
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;
use think\Model;
class Trans extends Model{
/**
* 腾讯单条文本翻译
* @param string $text 待翻译文本
* @param string $source 源语言 zh
* @param string $target 目标语言 en/fr/es
* @return string
* @throws \Exception
*/
public static function single(string $text, string $source = 'zh', string $target = 'en'): string
{
// 缓存优化:减少请求消耗
$cacheKey = 'tmt_' . md5("{$source}_{$target}_{$text}");
$cacheVal = cache($cacheKey);
if ($cacheVal !== null) {
return $cacheVal;
}
try {
$cred = new Credential(config('trans.qcloud.secret_id'), config('trans.qcloud.secret_key'));
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("tmt.tencentcloudapi.com");
$httpProfile->setReqTimeout(10);
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
$client = new TmtClient($cred, config('trans.qcloud.region'), $clientProfile);
$params = [
'SourceText' => $text,
'Source' => $source,
'Target' => $target,
'ProjectId' => 0
];
$req = new TextTranslateRequest();
$req->fromJsonString(json_encode($params, JSON_UNESCAPED_UNICODE));
$resp = $client->TextTranslate($req);
$respJson = $resp->toJsonString();
$respData = json_decode($respJson, true);
// 兼容两种返回结构:外层带Response / 直接顶层字段
if (isset($respData['Response'])) {
$response = $respData['Response'];
} else {
$response = $respData;
}
// 判断接口业务错误
if (isset($response['Error'])) {
$err = $response['Error'];
throw new \Exception("API错误[{$err['Code']}]:{$err['Message']}");
}
// 获取译文
$targetText = trim($response['TargetText'] ?? '');
if ($targetText === '') {
throw new \Exception("接口返回译文为空,原始返回:" . $respJson);
}
// 写入缓存
cache($cacheKey, $targetText, 86400);
return $targetText;
} catch (TencentCloudSDKException $e) {
$msg = "SDK异常:{$e->getMessage()} | Code:{$e->getErrorCode()} | RequestId:{$e->getRequestId()}";
throw new \Exception($msg);
} catch (\Exception $e) {
throw $e;
}
}
/*批量翻译*/
public static function batch(array $data, string $source = 'zh', string $target = 'en'): array
{
$result = [];
foreach ($data as $key => $val) {
$result[$key] = self::single((string)$val, $source, $target);
}
return $result;
}
} 下一篇: 暂无数据