71 lines
2.3 KiB
PHP
71 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace app\common\service;
|
|
|
|
use app\common\model\ai\AiConfig;
|
|
|
|
class MTranServerService
|
|
{
|
|
public static function translate(string $text, string $target = 'zh-Hans', string $source = 'auto'): array
|
|
{
|
|
$text = trim($text);
|
|
if ($text === '') {
|
|
return ['success' => false, 'error' => '翻译内容为空'];
|
|
}
|
|
|
|
$baseUrl = rtrim(AiConfig::getVal('mtranserver_base_url', 'http://127.0.0.1:8989'), '/');
|
|
$apiToken = trim(AiConfig::getVal('mtranserver_api_token', ''));
|
|
|
|
$payload = [
|
|
'from' => $source ?: 'auto',
|
|
'to' => $target ?: 'zh-Hans',
|
|
'text' => $text,
|
|
];
|
|
|
|
$headers = ['Content-Type: application/json'];
|
|
if ($apiToken !== '') {
|
|
$headers[] = 'Authorization: Bearer ' . $apiToken;
|
|
}
|
|
|
|
$startTime = microtime(true);
|
|
$ch = curl_init($baseUrl . '/translate');
|
|
curl_setopt_array($ch, [
|
|
CURLOPT_POST => true,
|
|
CURLOPT_HTTPHEADER => $headers,
|
|
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_TIMEOUT => 120,
|
|
CURLOPT_SSL_VERIFYPEER => false,
|
|
]);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$error = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
$costMs = (int) ((microtime(true) - $startTime) * 1000);
|
|
|
|
if ($error) {
|
|
return ['success' => false, 'error' => 'MTranServer 请求失败: ' . $error, 'tokens' => 0, 'cost_ms' => $costMs];
|
|
}
|
|
|
|
$data = json_decode((string) $response, true);
|
|
if ($httpCode !== 200) {
|
|
$message = is_array($data) ? ($data['message'] ?? $data['error'] ?? ('HTTP ' . $httpCode)) : ('HTTP ' . $httpCode);
|
|
return ['success' => false, 'error' => 'MTranServer 返回异常: ' . $message, 'tokens' => 0, 'cost_ms' => $costMs];
|
|
}
|
|
|
|
$result = trim((string) ($data['result'] ?? ''));
|
|
if ($result === '') {
|
|
return ['success' => false, 'error' => 'MTranServer 翻译结果为空', 'tokens' => 0, 'cost_ms' => $costMs];
|
|
}
|
|
|
|
return [
|
|
'success' => true,
|
|
'content' => $result,
|
|
'tokens' => 0,
|
|
'cost_ms' => $costMs,
|
|
];
|
|
}
|
|
}
|