Merge branch 'develop'

This commit is contained in:
mzl
2025-07-11 18:01:23 +08:00
parent 642c25503d
commit 925c5501f7
83 changed files with 4869 additions and 1162 deletions
+14
View File
@@ -0,0 +1,14 @@
<?php
return [
// 定义所有需要多语言支持的实体
'entities' => [
'ticket_categorie' => [
'translation_model' => \app\ticket\model\CategorieTranslation::class,
'foreign_key' => 'categorie_id',
],
],
// 默认支持的目标语种列表
'locales' => ['zh','en','ru','ar'],
];
@@ -0,0 +1,64 @@
<?php
namespace app\queue\translation\jobs;
use support\Log;
use app\queue\translation\service\TranslatorClient;
class TranslationJob
{
protected $config = [];
protected array $payload;
public function __construct(array $payload)
{
$this->config = getConfig('/queue/translation/config/trans.php');
$this->payload = $payload;
}
public function handle(): void
{
$cfgAll = $this->config['entities'];
$pt = $this->payload;
$type = $pt['entityType'];
$id = $pt['entityId'];
$locale = $pt['locale'];
$sourceLocale = $pt['sourceLocale'];
$sourceFields = $pt['sourceFields'];
$clientFields = $pt['clientFields'];
if (! isset($cfgAll[$type])) {
Log::warning("TranslationJob: 未配置实体 {$type}");
return;
}
$cfg = $cfgAll[$type];
$modelClass = $cfg['translation_model'];
$foreignKey = $cfg['foreign_key'];
// 决定采用前端提供、源语种还是第三方翻译
if (! empty($clientFields)) {
$fields = $clientFields;
} elseif ($locale === $sourceLocale) {
$fields = $sourceFields;
} else {
$translator = new TranslatorClient();
$fields = [];
foreach ($sourceFields as $key => $text) {
$fields[$key] = $translator->translate($text, $sourceLocale, $locale);
}
}
// 写库
try {
$modelClass::updateOrCreate(
[
$foreignKey => $id,
'locale' => $locale,
],
array_merge($fields, ['locale' => $locale])
);
} catch (\Throwable $e) {
Log::error("TranslationJob 保存失败: {$type}#{$id} locale={$locale}: ".$e->getMessage());
}
}
}
@@ -0,0 +1,50 @@
<?php
namespace app\queue\translation\queue;
use support\Log;
use Webman\RedisQueue\Consumer;
use app\queue\translation\jobs\TranslationJob;
class Translation implements Consumer
{
// 要消费的队列名
public $queue = 'transTask';
// 连接名,对应 plugin/webman/redis-queue/redis.php 里的连接`
public $connection = 'default';
// 消费
public function consume($data)
{
try {
// 无需反序列化
// var_export($data); // 输出 ['to' => 'tom@gmail.com', 'content' => 'hello']
$job = new TranslationJob($data);
$job->handle();
} catch (\Throwable $e) {
Log::error("TranslationService 异步任务异常: ".$e->getMessage());
}
}
// 消费失败回调
/*
$package = [
'id' => 1357277951, // 消息ID
'time' => 1709170510, // 消息时间
'delay' => 0, // 延迟时间
'attempts' => 2, // 消费次数
'queue' => 'send-mail', // 队列名
'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
'max_attempts' => 5, // 最大重试次数
'error' => '错误信息' // 错误信息
]
*/
public function onConsumeFailure(\Throwable $e, $package)
{
echo "consume failure\n";
echo $e->getMessage() . "\n";
// 无需反序列化
var_export($package);
}
}
@@ -0,0 +1,41 @@
<?php
namespace app\queue\translation\service;
// use Webman\RedisQueue\Client;
use Webman\RedisQueue\Redis;
class TranslationService
{
// 配置
protected $config = [];
public function __construct()
{
$this->config = getConfig('/queue/translation/config/trans.php');
}
/**
* 异步排队所有语种的翻译任务
*
* @param string $entityType 实体名,如 'vehicle'
* @param int $entityId 主表 ID
* @param string $sourceLocale 源语种,如 'zh'
* @param array $sourceFields 源语种字段 ['name'=>…,'condition_desc'=>…]
* @param array $clientFields 前端已传翻译 ['en'=>[...], …]
*/
public function queueTranslations(string $entityType, int $entityId, string $sourceLocale, array $sourceFields, array $clientFields = []): void
{
foreach ($this->config['locales'] as $locale) {
$payload = [
'entityType' => $entityType,
'entityId' => $entityId,
'locale' => $locale,
'sourceLocale' => $sourceLocale,
'sourceFields' => $sourceFields,
'clientFields' => $clientFields[$locale] ?? [],
];
Redis::send('transTask', $payload);
}
}
}
@@ -0,0 +1,38 @@
<?php
namespace app\queue\translation\service;
use app\queue\utils\XunfeiFanyi;
use support\Log;
class TranslatorClient
{
// protected string $endpoint;
// protected string $apiKey;
// public function __construct()
// {
// $this->endpoint = env('TRANSLATION_API_URL');
// $this->apiKey = env('TRANSLATION_API_KEY');
// }
/**
* 翻译文本
* @throws \RuntimeException
*/
public function translate(string $text, string $from = 'cn', string $to = 'ru'): string
{
try {
$xunfei = new XunfeiFanyi();
$rst_dst = $xunfei->fanyi($text, $from, $to);
if ($rst_dst) {
return $rst_dst["trans_result"]["dst"];
} else {
return '';
}
} catch (\Throwable $e) {
Log::error("TranslatorClient 错误: ".$e->getMessage());
throw new \RuntimeException('翻译服务调用失败');
}
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace app\queue\utils;
class Translat
{
/**
* 从$data中提取出源文本字段,并从$data里删除它们
*/
public static function extractSourceFields(array &$data,array $translat): array
{
$source = [];
foreach ($translat as $field) {
if (array_key_exists($field, $data)) {
$source[$field] = $data[$field];
unset($data[$field]);
}
}
return $source;
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
namespace app\queue\utils;
class XunfeiFanyi
{
protected $error = "";
public function tocurl($url, $header, $content)
{
$ch = curl_init();
if(substr($url,0,5)=='https'){
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
if (is_array($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_POST, true);
if (!empty($content)) {
if (is_array($content)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
} else if (is_string($content)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
}
}
$response = curl_exec($ch);
$error=curl_error($ch);
//var_dump($error);
if($error){
die($error);
}
$header = curl_getinfo($ch);
curl_close($ch);
$data = array('header' => $header,'body' => $response);
return $data;
}
public function xfyun($text = "中华人民共和国于1949年成立", $from = "cn", $to = "en")
{
//在控制台-我的应用-机器翻译获取
$app_id = "3d46198c";
//在控制台-我的应用-机器翻译获取
$api_sec = "ZWY2MmUyNjJjYmFkOTFlYTVmYWVhMGYy";
//在控制台-我的应用-机器翻译获取
$api_key = "b6d805f240176ecaea85130cb5f2bca1";
// 机器翻译接口地址
$url = "https://ntrans.xfyun.cn/v2/ots";
//body组装
// $text = "中华人民共和国于1949年成立";//待翻译文本
$body = json_encode($this->getBody($app_id, $from, $to, $text));
// 组装http请求头
$date =gmdate('D, d M Y H:i:s') . ' GMT';
$digestBase64 = "SHA-256=".base64_encode(hash("sha256", $body, true));
$builder = sprintf("host: %s
date: %s
POST /v2/ots HTTP/1.1
digest: %s", "ntrans.xfyun.cn", $date, $digestBase64);
// echo($builder);
$sha = base64_encode(hash_hmac("sha256", $builder, $api_sec, true));
$authorization = sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", $api_key,"hmac-sha256",
"host date request-line digest", $sha);
$header = [
"Authorization: ".$authorization,
'Content-Type: application/json',
'Accept: application/json,version=1.0',
'Host: ntrans.xfyun.cn',
'Date: ' .$date,
'Digest: '.$digestBase64
];
$response = $this->tocurl($url, $header, $body);
// var_dump($response['body']);
return $response;
}
public function getBody($app_id, $from, $to, $text)
{
$common_param = [
'app_id' => $app_id
];
$business = [
'from' => $from,
'to' => $to,
];
$data = [
"text" => base64_encode($text)
];
return $body = [
'common' => $common_param,
'business' => $business,
'data' => $data
];
}
// 翻译
public function fanyi($text = "", $from = "", $to = "")
{
try {
$res = $this->xfyun($text, $from, $to);
$data = json_decode($res["body"], true);
if ($data["code"] === 0) {
return $data["data"]["result"];
} else {
$this->error = $data["message"];
return false;
}
} catch (\Throwable $th) {
$this->error = $th->getMessage();
return false;
}
}
// 异常
public function error()
{
return $this->error;
}
}