NissayaTranslateService.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. <?php
  2. namespace App\Services\AIAssistant;
  3. use App\Http\Resources\AiModelResource;
  4. use App\Services\NissayaParser;
  5. use App\Services\OpenAIService;
  6. use App\Services\RomanizeService;
  7. use Illuminate\Support\Facades\Log;
  8. class NissayaTranslateService
  9. {
  10. protected AiModelResource $model;
  11. protected bool $romanize;
  12. protected ?bool $thinking = null;
  13. /**
  14. * 翻译提示词模板
  15. */
  16. protected string $translatePrompt = <<<'PROMPT'
  17. 你是一个专业的缅甸语翻译专家。你的任务是将缅文逐词解析(Nissaya)翻译成中文。
  18. 输入格式:
  19. - 每行包含三个部分: original(巴利文), translation(缅文译文), note(缅文注释,可能没有)
  20. - 输入为JSON Lines格式
  21. 输出要求:
  22. 1. 保持巴利文(original)原样输出,不做任何修改
  23. 2. 将巴利文(original)直接翻译成中文
  24. 2. 将缅文译文(translation)翻译成中文
  25. 3. 将缅文注释(note)翻译成中文
  26. 4. 输出必须是严格的JSON Lines格式,每行一个有效的JSON对象
  27. 5. 不要添加任何解释、说明或markdown代码块标记
  28. 6. 保持原有的数据结构和字段名称
  29. 7. 输出三个字段
  30. 1. original:原巴利文
  31. 2. translation:巴利文的中文译文>缅文的中文译文
  32. 3. note:缅文注释的中文译文
  33. 3. confidence:两个译文的语义相似度(0-100)
  34. 示例输入:
  35. {"original":"buddha","translation":"ဗုဒ္ဓ","note":"အဘိဓာန်"}
  36. 示例输出:
  37. {"original":"buddha","translation":"佛>佛陀","note":"词汇表","confidence":100}
  38. 请翻译以下内容:
  39. PROMPT;
  40. public function __construct(
  41. protected OpenAIService $openAIService,
  42. protected NissayaParser $nissayaParser,
  43. protected RomanizeService $romanizeService
  44. ) {
  45. $this->romanize = true;
  46. }
  47. /**
  48. * 设置模型配置
  49. */
  50. public function setModel(AiModelResource $model): self
  51. {
  52. $this->model = $model;
  53. return $this;
  54. }
  55. /**
  56. * 设置模型配置
  57. */
  58. public function setThinking(?bool $thinking): self
  59. {
  60. if ($thinking === null) {
  61. return $this;
  62. }
  63. $this->thinking = $thinking;
  64. return $this;
  65. }
  66. /**
  67. * 设置翻译提示词
  68. */
  69. public function setTranslatePrompt(string $prompt): self
  70. {
  71. $this->translatePrompt = $prompt;
  72. return $this;
  73. }
  74. /**
  75. * 设置翻译提示词
  76. *
  77. * @param string $prompt
  78. */
  79. public function setRomanize(bool $romanize): self
  80. {
  81. $this->romanize = $romanize;
  82. return $this;
  83. }
  84. /**
  85. * 翻译缅文版逐词解析
  86. *
  87. * @param string $text 格式: 巴利文=缅文
  88. * @param bool $stream 是否流式输出
  89. *
  90. * @throws \Exception
  91. */
  92. public function translate(string $text, bool $stream = false): array
  93. {
  94. $startAt = time();
  95. try {
  96. // 1. 解析nissaya文本为数组
  97. $parsedData = $this->nissayaParser->parse($text);
  98. if (empty($parsedData)) {
  99. throw new \Exception('解析nissaya文本失败,返回空数组');
  100. }
  101. $parsedData = $this->romanize($parsedData);
  102. foreach ($parsedData as $key => $value) {
  103. if (isset($value['notes']) && is_array($value['notes'])) {
  104. $parsedData[$key]['note'] = implode("\n\n----\n\n", $value['notes']);
  105. $parsedData[$key]['note'] = str_replace("\n**", "\n\n-----\n\n", $parsedData[$key]['note']);
  106. unset($parsedData[$key]['notes']);
  107. }
  108. }
  109. // 2. 将解析后的数组转换为JSONL格式
  110. $jsonlInput = $this->arrayToJsonl($parsedData);
  111. Log::info('NissayaTranslate: 准备翻译', [
  112. 'items_count' => count($parsedData),
  113. 'input_length' => strlen($jsonlInput),
  114. ]);
  115. // 3. 调用LLM进行翻译
  116. $response = $this->openAIService
  117. ->setApiUrl($this->model['url'])
  118. ->setModel($this->model['model'])
  119. ->setApiKey($this->model['key'])
  120. ->setSystemPrompt($this->translatePrompt)
  121. ->setTemperature(0.3)
  122. ->setStream($stream)
  123. ->setThinking($this->thinking)
  124. ->send($jsonlInput);
  125. $complete = time() - $startAt;
  126. $content = $response['choices'][0]['message']['content'] ?? '';
  127. if (empty($content)) {
  128. throw new \Exception('LLM返回内容为空');
  129. }
  130. // 4. 解析JSONL格式的翻译结果
  131. $translatedData = $this->jsonlToArray($content);
  132. Log::debug('NissayaTranslate: 翻译完成', [
  133. 'duration' => $complete,
  134. 'output_items' => count($translatedData),
  135. 'input_tokens' => $response['usage']['prompt_tokens'] ?? 0,
  136. 'output_tokens' => $response['usage']['completion_tokens'] ?? 0,
  137. ]);
  138. return [
  139. 'success' => true,
  140. 'data' => $translatedData,
  141. 'meta' => [
  142. 'duration' => $complete,
  143. 'items_count' => count($translatedData),
  144. 'usage' => $response['usage'] ?? [],
  145. ],
  146. ];
  147. } catch (\Exception $e) {
  148. Log::error('NissayaTranslate: 翻译失败', [
  149. 'error' => $e->getMessage(),
  150. 'trace' => $e->getTraceAsString(),
  151. ]);
  152. return [
  153. 'success' => false,
  154. 'error' => $e->getMessage(),
  155. 'data' => [],
  156. ];
  157. }
  158. }
  159. protected function romanize(array $data): array
  160. {
  161. if ($this->romanize) {
  162. foreach ($data as $key => $value) {
  163. $data[$key]['original'] = $this->romanizeService->myanmarToRoman($value['original']);
  164. }
  165. }
  166. return $data;
  167. }
  168. /**
  169. * 将数组转换为JSONL格式
  170. */
  171. protected function arrayToJsonl(array $data): string
  172. {
  173. $lines = [];
  174. foreach ($data as $item) {
  175. $lines[] = json_encode($item, JSON_UNESCAPED_UNICODE);
  176. }
  177. return implode("\n", $lines);
  178. }
  179. /**
  180. * 将JSONL格式转换为数组
  181. */
  182. protected function jsonlToArray(string $jsonl): array
  183. {
  184. // 清理可能的markdown代码块标记
  185. $jsonl = preg_replace('/```json\s*|\s*```/', '', $jsonl);
  186. $jsonl = trim($jsonl);
  187. $lines = explode("\n", $jsonl);
  188. $result = [];
  189. foreach ($lines as $line) {
  190. $line = trim($line);
  191. if (empty($line)) {
  192. continue;
  193. }
  194. $decoded = json_decode($line, true);
  195. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  196. $result[] = $decoded;
  197. } else {
  198. Log::warning('NissayaTranslate: 无法解析JSON行', [
  199. 'line' => $line,
  200. 'error' => json_last_error_msg(),
  201. ]);
  202. }
  203. }
  204. return $result;
  205. }
  206. /**
  207. * 批量翻译(将大文本分批处理)
  208. *
  209. * @param int $batchSize 每批处理的条目数
  210. */
  211. public function translateInBatches(string $text, int $batchSize = 50): array
  212. {
  213. try {
  214. $parsedData = $this->nissayaParser->parse($text);
  215. $batches = array_chunk($parsedData, $batchSize);
  216. $allResults = [];
  217. $totalDuration = 0;
  218. $totalUsage = [
  219. 'prompt_tokens' => 0,
  220. 'completion_tokens' => 0,
  221. 'total_tokens' => 0,
  222. ];
  223. foreach ($batches as $index => $batch) {
  224. Log::debug('NissayaTranslate: 处理批次 ' . ($index + 1) . '/' . count($batches));
  225. $jsonlInput = $this->arrayToJsonl($batch);
  226. $response = $this->openAIService
  227. ->setApiUrl($this->model['url'])
  228. ->setModel($this->model['model'])
  229. ->setApiKey($this->model['key'])
  230. ->setSystemPrompt($this->translatePrompt)
  231. ->setTemperature(0.7)
  232. ->setStream(false)
  233. ->setThinking($this->thinking)
  234. ->send($jsonlInput);
  235. $content = $response['choices'][0]['message']['content'] ?? '';
  236. $translatedBatch = $this->jsonlToArray($content);
  237. $allResults = array_merge($allResults, $translatedBatch);
  238. // 累计使用统计
  239. if (isset($response['usage'])) {
  240. $totalUsage['prompt_tokens'] += $response['usage']['prompt_tokens'] ?? 0;
  241. $totalUsage['completion_tokens'] += $response['usage']['completion_tokens'] ?? 0;
  242. $totalUsage['total_tokens'] += $response['usage']['total_tokens'] ?? 0;
  243. }
  244. }
  245. return [
  246. 'success' => true,
  247. 'data' => $allResults,
  248. 'meta' => [
  249. 'batches' => count($batches),
  250. 'items_count' => count($allResults),
  251. 'usage' => $totalUsage,
  252. ],
  253. ];
  254. } catch (\Exception $e) {
  255. Log::error('NissayaTranslate: 批量翻译失败', [
  256. 'error' => $e->getMessage(),
  257. ]);
  258. return [
  259. 'success' => false,
  260. 'error' => $e->getMessage(),
  261. 'data' => [],
  262. ];
  263. }
  264. }
  265. }