ArticleTranslateService.php 6.4 KB

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