TranslateService.php 7.8 KB

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