TranslateService.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace App\Services\AIAssistant;
  3. use App\Services\NissayaParser;
  4. use App\Services\OpenAIService;
  5. use App\Services\RomanizeService;
  6. use App\Services\AIModelService;
  7. use App\Services\AuthService;
  8. use Illuminate\Support\Facades\Log;
  9. use App\Http\Resources\AiModelResource;
  10. use App\DTO\LLMTranslation\TranslationResponseDTO;
  11. class TranslateService
  12. {
  13. protected OpenAIService $openAIService;
  14. protected NissayaParser $nissayaParser;
  15. protected RomanizeService $romanizeService;
  16. protected AIModelService $aiModelService;
  17. protected AiModelResource $model;
  18. protected string $modelToken;
  19. protected bool $thinking;
  20. protected bool $stream = false;
  21. protected array $original; //需要被翻译的原文
  22. protected string $systemPrompt = '';
  23. /**
  24. * 翻译提示词模板
  25. */
  26. protected string $translatePrompt = '';
  27. public function __construct(
  28. OpenAIService $openAIService,
  29. AIModelService $aiModelService,
  30. ) {
  31. $this->openAIService = $openAIService;
  32. $this->aiModelService = $aiModelService;
  33. }
  34. /**
  35. * 设置模型配置
  36. *
  37. * @param string $model
  38. * @return self
  39. */
  40. public function setModel(string $model): self
  41. {
  42. $this->model = $this->aiModelService->getModelById($model);
  43. $this->modelToken = AuthService::getUserToken($model);
  44. return $this;
  45. }
  46. /**
  47. * 设置模型配置
  48. *
  49. * @param bool $thinking
  50. * @return self
  51. */
  52. public function setThinking(bool $thinking): self
  53. {
  54. $this->thinking = $thinking;
  55. return $this;
  56. }
  57. /**
  58. * 设置翻译提示词
  59. *
  60. * @param string $prompt
  61. * @return self
  62. */
  63. public function setSystemPrompt(string $prompt): self
  64. {
  65. $this->systemPrompt = $prompt;
  66. return $this;
  67. }
  68. /**
  69. * 设置翻译提示词
  70. *
  71. * @param string $prompt
  72. * @return self
  73. */
  74. public function setTranslatePrompt(string $prompt): self
  75. {
  76. $this->translatePrompt = $prompt;
  77. return $this;
  78. }
  79. /**
  80. * 翻译缅文版逐词解析
  81. *
  82. * @param string $text 格式: 巴利文=缅文
  83. * @param bool $stream 是否流式输出
  84. * @return TranslationResponseDTO
  85. * @throws \Exception
  86. */
  87. public function translate(): TranslationResponseDTO
  88. {
  89. $startAt = time();
  90. try {
  91. Log::debug('准备翻译', [
  92. 'systemPrompt' => $this->systemPrompt,
  93. 'translatePrompt' => $this->translatePrompt,
  94. ]);
  95. // 3. 调用LLM进行翻译
  96. $llm = $this->openAIService
  97. ->setApiUrl($this->model['url'])
  98. ->setModel($this->model['model'])
  99. ->setApiKey($this->model['key'])
  100. ->setSystemPrompt($this->systemPrompt)
  101. ->setTemperature(0.3)
  102. ->setStream($this->stream);
  103. if (isset($this->thinking)) {
  104. $llm = $llm->setThinking($this->thinking);
  105. }
  106. $response = $llm->send($this->translatePrompt);
  107. $complete = time() - $startAt;
  108. $content = $response['choices'][0]['message']['content'] ?? '';
  109. if (empty($content)) {
  110. throw new \Exception('LLM返回内容为空');
  111. }
  112. Log::debug('翻译完成', [
  113. 'content' => $content,
  114. 'duration' => $complete,
  115. 'input_tokens' => $response['usage']['prompt_tokens'] ?? 0,
  116. 'output_tokens' => $response['usage']['completion_tokens'] ?? 0,
  117. ]);
  118. // 4. 解析JSONL格式的翻译结果
  119. $translatedData = $this->jsonlToArray($content);
  120. Log::debug('解析完成', [
  121. 'output_items' => count($translatedData),
  122. ]);
  123. return TranslationResponseDTO::fromArray([
  124. 'success' => true,
  125. 'data' => $translatedData,
  126. 'meta' => [
  127. 'duration' => $complete,
  128. 'items_count' => count($translatedData),
  129. 'usage' => $response['usage'] ?? [],
  130. ],
  131. ]);
  132. } catch (\Exception $e) {
  133. Log::error('NissayaTranslate: 翻译失败', [
  134. 'error' => $e->getMessage(),
  135. 'trace' => $e->getTraceAsString(),
  136. ]);
  137. return TranslationResponseDTO::fromArray([
  138. 'success' => false,
  139. 'error' => $e->getMessage(),
  140. 'data' => [],
  141. ]);
  142. }
  143. }
  144. /**
  145. * 将数组转换为JSONL格式
  146. *
  147. * @param array $data
  148. * @return string
  149. */
  150. protected function arrayToJsonl(array $data): string
  151. {
  152. $lines = [];
  153. foreach ($data as $item) {
  154. $lines[] = json_encode($item, JSON_UNESCAPED_UNICODE);
  155. }
  156. return implode("\n", $lines);
  157. }
  158. /**
  159. * 将JSONL格式转换为数组
  160. *
  161. * @param string $jsonl
  162. * @return array
  163. */
  164. protected function jsonlToArray(string $jsonl): array
  165. {
  166. // 清理可能的markdown代码块标记
  167. $jsonl = preg_replace('/```json\s*|\s*```/', '', $jsonl);
  168. $jsonl = trim($jsonl);
  169. $lines = explode("\n", $jsonl);
  170. $result = [];
  171. foreach ($lines as $line) {
  172. $line = trim($line);
  173. if (empty($line)) {
  174. continue;
  175. }
  176. $decoded = json_decode($line, true);
  177. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  178. $result[] = $decoded;
  179. } else {
  180. Log::warning('无法解析JSON行', [
  181. 'line' => $line,
  182. 'error' => json_last_error_msg(),
  183. ]);
  184. }
  185. }
  186. return $result;
  187. }
  188. /**
  189. * 批量翻译(将大文本分批处理)
  190. *
  191. * @param string $text
  192. * @param int $batchSize 每批处理的条目数
  193. * @return array
  194. */
  195. public function translateInBatches(string $text, int $batchSize = 50): array
  196. {
  197. try {
  198. $parsedData = $this->nissayaParser->parse($text);
  199. $batches = array_chunk($parsedData, $batchSize);
  200. $allResults = [];
  201. $totalDuration = 0;
  202. $totalUsage = [
  203. 'prompt_tokens' => 0,
  204. 'completion_tokens' => 0,
  205. 'total_tokens' => 0,
  206. ];
  207. foreach ($batches as $index => $batch) {
  208. Log::info("NissayaTranslate: 处理批次 " . ($index + 1) . "/" . count($batches));
  209. $jsonlInput = $this->arrayToJsonl($batch);
  210. $response = $this->openAIService
  211. ->setApiUrl($this->model['url'])
  212. ->setModel($this->model['model'])
  213. ->setApiKey($this->model['key'])
  214. ->setSystemPrompt($this->translatePrompt)
  215. ->setTemperature(0.7)
  216. ->setStream(false)
  217. ->send($jsonlInput);
  218. $content = $response['choices'][0]['message']['content'] ?? '';
  219. $translatedBatch = $this->jsonlToArray($content);
  220. $allResults = array_merge($allResults, $translatedBatch);
  221. // 累计使用统计
  222. if (isset($response['usage'])) {
  223. $totalUsage['prompt_tokens'] += $response['usage']['prompt_tokens'] ?? 0;
  224. $totalUsage['completion_tokens'] += $response['usage']['completion_tokens'] ?? 0;
  225. $totalUsage['total_tokens'] += $response['usage']['total_tokens'] ?? 0;
  226. }
  227. }
  228. return [
  229. 'success' => true,
  230. 'data' => $allResults,
  231. 'meta' => [
  232. 'batches' => count($batches),
  233. 'items_count' => count($allResults),
  234. 'usage' => $totalUsage,
  235. ],
  236. ];
  237. } catch (\Exception $e) {
  238. Log::error('NissayaTranslate: 批量翻译失败', [
  239. 'error' => $e->getMessage(),
  240. ]);
  241. return [
  242. 'success' => false,
  243. 'error' => $e->getMessage(),
  244. 'data' => [],
  245. ];
  246. }
  247. }
  248. }