CRMEB/backend/crmeb/utils/Translate.php
2026-09-23 15:15:02 +08:00

94 lines
3.2 KiB
PHP
Raw Permalink 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.

<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2026 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------
namespace crmeb\utils;
use crmeb\exceptions\ApiException;
use Volc\Base\V4Curl;
/**
* 机器翻译
*/
class Translate extends V4Curl
{
protected $apiList = [
"LangDetect" => [
"url" => "/",
"method" => "post",
"config" => [
"query" => [
"Action" => "LangDetect",
"Version" => "2020-06-01",
],
],
],
"TranslateText" => [
"url" => "/",
"method" => "post",
"config" => [
"query" => [
"Action" => "TranslateText",
"Version" => "2020-06-01",
],
],
],
];
protected function getConfig(string $region)
{
return [
"host" => "https://open.volcengineapi.com",
"config" => [
"timeout" => 5.0,
"headers" => [
"Accept" => "application/json"
],
"v4_credentials" => [
"region" => "cn-north-1",
"service" => "translate",
],
],
];
}
public function langDetect(array $textList): array
{
$req = array('TextList' => $textList);
try {
$resp = $this->request('LangDetect', ['json' => $req]);
} catch (\Throwable $e) {
throw $e;
}
if ($resp->getStatusCode() != 200) {
throw new ApiException("failed to detect language: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
}
return json_decode($resp->getBody()->getContents(), true)["DetectedLanguageList"];
}
public function translateText(string $sourceLanguage, string $targetLanguage, array $textList): array
{
$req = array('SourceLanguage' => $sourceLanguage, 'TargetLanguage' => $targetLanguage, 'TextList' => $textList);
try {
$resp = $this->request('TranslateText', ['json' => $req]);
} catch (\Throwable $e) {
throw $e;
}
if ($resp->getStatusCode() != 200) {
throw new ApiException("failed to translate: status_code=%d, resp=%s", $resp->getStatusCode(), $resp->getBody());
}
$result = json_decode($resp->getBody()->getContents(), true);
if (isset($result["TranslationList"])) {
return $result["TranslationList"];
} else {
throw new ApiException("failed to translate: " . $result["ResponseMetadata"]['Error']['Message']);
}
}
}