腾讯云机器翻译实现入门实例

南国老符 南国老符 最后更新于:2026-06-19 浏览:15

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;
    }
}

点赞 (0)

收藏 (0)
转载请务必注明: 来源:《建站管家》https://www.df81.com/news/565.html

本站部分信息来源网络,如有侵权,请联系QQ:1062129401删除。

上一篇: webman框架+腾讯云滑动验证码功能代码实例

下一篇: 暂无数据

请先登录后,再发表评论 ~ ~
发表评论
发表帖子
广告位招租( ¥5 / 天 )
点击咨询
最新帖子

南国老符
2025-09-10 03:48
南国老符
2025-07-13 19:36
南国老符
2025-05-26 16:54
南国老符
2024-09-29 10:29
广告位招租( ¥5 / 天 )
点击咨询
最近评论

Y
yuanis90
回复:在后台->全局管理->网站设置->网站html代码,把你申请的分享代码贴到这里保存即可。以后发问题,请贴出具体版本号
南国老符
回复:发表帖子发不了  乱码
南国老符
回复:第一位参与的老总,是做洗衣店saas系统的,需要的请联系
9
9252
回复:新版已经修复了的,升级忘记覆盖了,你重新下载即可。
U
user1304
回复:PHP开启fileinfo扩展即可
U
user1379
回复:版本号多少?
购买VIP
购买授权
余额充值
发表帖子
客服微信