ArticleTranslateService.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. <?php
  2. namespace App\Services\AIAssistant;
  3. use App\Services\ArticleService;
  4. use App\Services\PaliContentService;
  5. use App\Services\SentenceService;
  6. use App\Models\CustomBook;
  7. use Illuminate\Support\Facades\Log;
  8. use App\Http\Api\ChannelApi;
  9. class ArticleTranslateService
  10. {
  11. protected ArticleService $articleService;
  12. protected PaliContentService $paliContentService;
  13. protected TranslateService $translateService;
  14. protected SentenceService $sentenceService;
  15. protected string $modelId;
  16. protected array $translation = [];
  17. protected string $outputChannelId;
  18. protected string $systemPrompt = <<<PROMPT
  19. 请根据提供的原文,翻译为简体中文。
  20. 原文为逐句数据,翻译时请依照句子的上下文翻译。
  21. id:句子编号
  22. content:内容
  23. # 翻译要求:
  24. 1. 缅文巴利要给出罗马巴利转写
  25. 2. 使用现代汉语
  26. 3. 逐句翻译
  27. # 输出格式要求:
  28. - jsonl 格式
  29. - 每条记录是一个句子
  30. - 每个句子只输出两个字段
  31. 1. id(句子编号)
  32. 2. content(译文)
  33. - 无需输出原文
  34. - 只输出jsonl格式的译文 无需出处额外的解释
  35. # 输出范例
  36. ```jsonl
  37. {"id":"1-2-3-4","content":"译文"}
  38. {"id":"2-3-4-5","content":"译文"}
  39. ```
  40. PROMPT;
  41. public function __construct(
  42. ArticleService $article,
  43. PaliContentService $paliContent,
  44. TranslateService $translateService,
  45. SentenceService $sentenceService
  46. ) {
  47. $this->articleService = $article;
  48. $this->paliContentService = $paliContent;
  49. $this->translateService = $translateService;
  50. $this->sentenceService = $sentenceService;
  51. }
  52. /**
  53. * 设置模型配置
  54. *
  55. * @param string $model
  56. * @return self
  57. */
  58. public function setModel(string $model): self
  59. {
  60. $this->modelId = $model;
  61. return $this;
  62. }
  63. /**
  64. * 设置模型配置
  65. *
  66. * @param string $model
  67. * @return self
  68. */
  69. public function setChannel(string $id): self
  70. {
  71. $this->outputChannelId = $id;
  72. return $this;
  73. }
  74. public function translateAnthology($anthologyId, ?callable $onEach = null): int
  75. {
  76. $articles = $this->articleService->articlesInAnthology($anthologyId);
  77. foreach ($articles as $article) {
  78. $sentences = $this->translateArticle($article)->save();
  79. if ($onEach) {
  80. $onEach($article, $sentences);
  81. }
  82. }
  83. return count($articles);
  84. }
  85. public function translateArticle(string $articleId)
  86. {
  87. //获取文章中的句子id
  88. $sentenceIds = $this->articleService->sentenceIds($articleId);
  89. if (!$sentenceIds || count($sentenceIds) === 0) {
  90. $this->translation = [];
  91. return $this;
  92. }
  93. $bookId = (int)explode('-', $sentenceIds[0])[0];
  94. //提取原文
  95. $originalChannelId = CustomBook::where('book_id', $bookId)->value('channel_id');
  96. $original = $this->paliContentService->sentences($sentenceIds, [$originalChannelId], 'read');
  97. $orgData = [];
  98. foreach ($original as $key => $paragraph) {
  99. foreach ($paragraph['children'] as $key => $sent) {
  100. $org = $sent['origin'][0];
  101. $orgData[] = [
  102. 'id' => "{$org['book']}-{$org['para']}-{$org['wordStart']}-{$org['wordEnd']}",
  103. 'content' => !empty($org['content']) ? $org['content'] : $org['html'],
  104. ];
  105. }
  106. }
  107. //翻译
  108. $result = $this->translateService->setModel($this->modelId)
  109. ->setSystemPrompt($this->systemPrompt)
  110. ->setTranslatePrompt("# 原文\n\n" .
  111. "```json\n" .
  112. json_encode($orgData, JSON_UNESCAPED_UNICODE) .
  113. "\n```")
  114. ->translate();
  115. Log::debug('ai translation', ['data' => $result->toArray()['data']]);
  116. $this->translation = $result->toArray()['data'];
  117. return $this;
  118. }
  119. //写入结果channel
  120. public function save()
  121. {
  122. if (
  123. !is_array($this->translation) ||
  124. count($this->translation) === 0
  125. ) {
  126. return 0;
  127. }
  128. $channelInfo = ChannelApi::getById($this->outputChannelId);
  129. $sentData = [];
  130. $sentData = array_map(function ($n) use ($channelInfo) {
  131. $sId = explode('-', $n['id']);
  132. return [
  133. 'book_id' => $sId[0],
  134. 'paragraph' => $sId[1],
  135. 'word_start' => $sId[2],
  136. 'word_end' => $sId[3],
  137. 'channel_uid' => $channelInfo['id'],
  138. 'content' => $n['content'],
  139. 'content_type' => $n['content_type'] ?? 'markdown',
  140. 'lang' => $channelInfo['lang'],
  141. 'status' => $channelInfo['status'],
  142. 'editor_uid' => $this->modelId,
  143. ];
  144. }, $this->translation);
  145. foreach ($sentData as $value) {
  146. $this->sentenceService->save($value);
  147. }
  148. return count($sentData);
  149. }
  150. public function get()
  151. {
  152. return $this->translation;
  153. }
  154. }