UpgradeAITranslation.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Helpers\LlmResponseParser;
  4. use App\Http\Api\ChannelApi;
  5. use App\Http\Resources\AiModelResource;
  6. use App\Models\PaliText;
  7. use App\Models\Sentence;
  8. use App\Services\AIAssistant\NissayaTranslateService;
  9. use App\Services\AIAssistant\PaliTranslateService;
  10. use App\Services\AIModelService;
  11. use App\Services\AuthService;
  12. use App\Services\OpenAIService;
  13. use App\Services\SentenceService;
  14. use Illuminate\Console\Command;
  15. use Illuminate\Support\Facades\Cache;
  16. use Illuminate\Support\Facades\Log;
  17. class UpgradeAITranslation extends Command
  18. {
  19. /**
  20. * The name and signature of the console command.
  21. * php artisan upgrade:ai.translation translation --book=131 --para=27
  22. * php artisan upgrade:ai.translation nissaya --book=207 --para=1247
  23. *
  24. * nissaya 参考资料用法示例(--nissaya 指定哪些步骤注入 nissaya 逐词缅文释义):
  25. * - 默认(不传) translate/review/evaluate 全部注入 nissaya
  26. * php artisan upgrade:ai.translation translation {channel} --book=131 --para=27 --steps=translate,review,revise,evaluate
  27. * - 仅 review 注入
  28. * php artisan upgrade:ai.translation translation {channel} --book=131 --para=27 --steps=translate,review,evaluate --nissaya=review
  29. * - review + evaluate 注入,translate 不注入
  30. * php artisan upgrade:ai.translation translation {channel} --book=131 --para=27 --steps=translate,review,evaluate --nissaya=review,evaluate
  31. * - 全部不注入
  32. * php artisan upgrade:ai.translation translation {channel} --book=131 --para=27 --steps=translate,review,evaluate --nissaya=
  33. *
  34. * @var string
  35. */
  36. protected $signature = 'upgrade:ai.translation
  37. {type}
  38. {channel}
  39. {--book=}
  40. {--para=}
  41. {--resume}
  42. {--model=}
  43. {--thinking= : 开启和关闭deepseek thinking true | false}
  44. {--steps=translate : translation 工作流步骤,逗号分隔,可选 translate,review,revise,evaluate(evaluate 为质量评估,须放最后)}
  45. {--nissaya=translate,review,evaluate : 启用 nissaya 参考资料的步骤,逗号分隔,可选 translate,review,evaluate;传空字符串则全部不注入}
  46. {--fresh : 清除缓存断点,从头开始}';
  47. // 缓存键前缀:以 type、channel 区分,记录已完成的 "book|para" 集合,中断后重跑自动跳过
  48. private const CACHE_KEY_PREFIX = 'upgrade:ai.translation:done';
  49. /**
  50. * The console command description.
  51. *
  52. * @var string
  53. */
  54. protected $description = 'Command description';
  55. protected AiModelResource $model;
  56. protected string $modelToken;
  57. protected array $workChannel;
  58. protected string $accessToken;
  59. protected bool $thinking;
  60. /**
  61. * Create a new command instance.
  62. *
  63. * @return void
  64. */
  65. public function __construct(
  66. protected AIModelService $modelService,
  67. protected SentenceService $sentenceService,
  68. protected OpenAIService $openAIService,
  69. protected NissayaTranslateService $nissayaTranslateService,
  70. protected PaliTranslateService $paliTranslateService
  71. ) {
  72. parent::__construct();
  73. }
  74. /**
  75. * Execute the console command.
  76. *
  77. * @return int
  78. */
  79. public function handle()
  80. {
  81. /**
  82. * model
  83. */
  84. if (! $this->option('model')) {
  85. $this->error('model is request');
  86. return 1;
  87. }
  88. $this->model = $this->modelService->getModelById($this->option('model'));
  89. $this->info("model:{$this->model['model']}");
  90. $this->modelToken = AuthService::getUserToken($this->model['uid']);
  91. // channel
  92. $this->workChannel = ChannelApi::getById($this->argument('channel'));
  93. // 需要判断输入channel 与翻译类型是否一致 nissaya -> nissaya channel
  94. if ($this->workChannel['type'] !== $this->argument('type')) {
  95. $this->error('channel type not match request '.$this->argument('type').' input is '.$this->workChannel['type']);
  96. return 1;
  97. }
  98. if ($this->option('thinking')) {
  99. $this->thinking = $this->option('thinking') === 'true';
  100. $this->line('thinking is '.$this->option('thinking'));
  101. }
  102. // translation 工作流步骤校验
  103. $steps = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('steps')))));
  104. $invalid = array_diff($steps, PaliTranslateService::STEPS);
  105. if (! empty($invalid)) {
  106. $this->error('invalid steps: '.implode(',', $invalid).'. allowed: '.implode(',', PaliTranslateService::STEPS));
  107. return 1;
  108. }
  109. // nissaya 参考资料注入步骤校验(哪些步骤启用 nissaya)
  110. $nissayaSteps = array_values(array_filter(array_map('trim', explode(',', (string) $this->option('nissaya')))));
  111. $invalidNissaya = array_diff($nissayaSteps, PaliTranslateService::NISSAYA_STEPS);
  112. if (! empty($invalidNissaya)) {
  113. $this->error('invalid nissaya steps: '.implode(',', $invalidNissaya).'. allowed: '.implode(',', PaliTranslateService::NISSAYA_STEPS));
  114. return 1;
  115. }
  116. $type = $this->argument('type');
  117. $channelId = $this->workChannel['id'] ?? '';
  118. // 缓存键:按 type、channel 区分不同任务的断点
  119. $cacheKey = self::CACHE_KEY_PREFIX.':'.$type.':'.$channelId;
  120. if ($this->option('fresh')) {
  121. Cache::forget($cacheKey);
  122. $this->info('Cleared cached cursor.');
  123. }
  124. // 是否为完整遍历(未指定 book/para),仅此情形在结束后清空断点缓存
  125. $isFullRun = ! $this->option('book') && ! $this->option('para');
  126. // 从缓存恢复已完成的 (book, para) 集合,作为重入时的稳定游标
  127. $done = Cache::get($cacheKey, []);
  128. $books = [];
  129. if ($this->option('book')) {
  130. $books = [$this->option('book')];
  131. } else {
  132. // 未指定 book 时,若已有断点缓存,从上次处理到的 book 继续,无需从 1 开始
  133. $startBook = 1;
  134. if (! empty($done)) {
  135. $doneBooks = array_map(fn ($cursor) => (int) explode('|', $cursor)[0], array_keys($done));
  136. $startBook = max($doneBooks);
  137. $this->info("resume from book {$startBook}");
  138. }
  139. $books = range($startBook, 217);
  140. }
  141. foreach ($books as $key => $book) {
  142. $maxParagraph = PaliText::where('book', $book)->max('paragraph');
  143. $paragraphs = range(1, $maxParagraph);
  144. if ($this->option('para')) {
  145. $paragraphs = [$this->option('para')];
  146. }
  147. foreach ($paragraphs as $key => $paragraph) {
  148. // 稳定游标:缓存键已含 type、channel,此处仅以 book|para 标识处理单元
  149. $cursor = $book.'|'.$paragraph;
  150. if (isset($done[$cursor])) {
  151. $this->info("skip {$cursor}");
  152. continue;
  153. }
  154. $start = time();
  155. $data = [];
  156. switch ($this->argument('type')) {
  157. case 'translation':
  158. $data = $this->paliTranslateService
  159. ->setModel($this->model)
  160. ->setChannel($this->workChannel)
  161. ->setThinking($this->thinking ?? null)
  162. ->setNissayaSteps($nissayaSteps)
  163. ->run($steps, (int) $book, (int) $paragraph);
  164. break;
  165. case 'nissaya':
  166. $data = $this->aiNissayaTranslate($book, $paragraph);
  167. break;
  168. case 'wbw':
  169. $data = $this->aiWBW($book, $paragraph);
  170. break;
  171. default:
  172. // code...
  173. break;
  174. }
  175. $this->save($data);
  176. $time = time() - $start;
  177. $this->info($this->argument('type')." {$book}-{$paragraph} ".count($data).' sentences time='.$time);
  178. // 该处理单元全部写库完成后再标记游标,确保中途中断不会误跳过
  179. $done[$cursor] = true;
  180. Cache::put($cacheKey, $done, now()->addHours(24));
  181. }
  182. }
  183. // 完整遍历正常结束,清空断点缓存
  184. if ($isFullRun) {
  185. Cache::forget($cacheKey);
  186. }
  187. return 0;
  188. }
  189. private function aiWBW($book, $para)
  190. {
  191. $sysPrompt = <<<'md'
  192. 你是一个佛教翻译专家,精通巴利文和缅文,精通巴利文逐词解析
  193. ## 翻译要求:
  194. - 请将用户提供的巴利句子单词表中的每个巴利文单词翻译为中文
  195. - 这些单词是一个完整的句子,请根据单词的上下文翻译
  196. - original 里面的数据是巴利文单词
  197. - 输入格式为 json 数组
  198. - 输出jsonl格式
  199. 在原来的数据中添加下列输出字段
  200. 1. meaning:单词的中文意思,如果有两个可能的意思,两个意思之间用/符号分隔
  201. 5. confidence:你认为你给出的这个单词的信息的信心指数(准确程度) 数值1-100 如果觉得非常有把握100, 如果觉得把握不大,适当降低信心指数
  202. 6. note:如果你认为信心指数很低,这个是疑难单词,请在note字段写明原因,如果不是疑难单词,请不要填写note
  203. **范例**:
  204. {"id":1,"original":"bhikkhusanghassa","meaning":"比库僧团[的]","confidence":100}
  205. 直接输出jsonl, 无需其他内容
  206. md;
  207. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  208. $sentences = Sentence::where('channel_uid', $channelId)
  209. ->where('book_id', $book)
  210. ->where('paragraph', $para)
  211. ->get();
  212. $result = [];
  213. foreach ($sentences as $key => $sentence) {
  214. $wbw = json_decode($sentence->content);
  215. $tpl = [];
  216. foreach ($wbw as $key => $word) {
  217. if (
  218. ! empty($word->real->value) &&
  219. $word->type->value !== '.ctl.'
  220. ) {
  221. $tpl[] = [
  222. 'id' => $word->sn[0],
  223. 'original' => $word->real->value,
  224. ];
  225. }
  226. }
  227. $tplText = json_encode($tpl, JSON_UNESCAPED_UNICODE);
  228. Log::debug($tplText);
  229. $startAt = time();
  230. $llm = $this->openAIService->setApiUrl($this->model['url'])
  231. ->setModel($this->model['model'])
  232. ->setApiKey($this->model['key'])
  233. ->setSystemPrompt($sysPrompt)
  234. ->setTemperature(0.7)
  235. ->setStream(false);
  236. if (isset($this->thinking)) {
  237. $llm = $llm->setThinking($this->thinking);
  238. }
  239. $response = $llm->send("```json\n{$tplText}\n```");
  240. $complete = time() - $startAt;
  241. $content = $response['choices'][0]['message']['content'] ?? '[]';
  242. Log::debug("ai response in {$complete}s content=".$content);
  243. $json = LlmResponseParser::jsonl($content);
  244. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  245. $result[] = [
  246. 'id' => $id,
  247. 'content' => json_encode($json, JSON_UNESCAPED_UNICODE),
  248. ];
  249. }
  250. return $result;
  251. }
  252. private function aiNissayaTranslate($book, $para)
  253. {
  254. $sentences = Sentence::nissaya()
  255. ->language('my') // 过滤缅文
  256. ->where('book_id', $book)
  257. ->where('paragraph', $para)
  258. ->orderBy('word_start')
  259. ->get();
  260. $result = [];
  261. foreach ($sentences as $key => $sentence) {
  262. if (! empty($sentence->content)) {
  263. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  264. $aiNissaya = $this->nissayaTranslateService
  265. ->setModel($this->model)
  266. ->translate($sentence->content, false);
  267. Log::debug('ai response ', ['content' => $aiNissaya['data']]);
  268. $result[] = [
  269. 'id' => $id,
  270. 'content' => json_encode($aiNissaya['data'] ?? [], JSON_UNESCAPED_UNICODE),
  271. 'content_type' => 'json',
  272. ];
  273. }
  274. }
  275. return $result;
  276. }
  277. private function save($data)
  278. {
  279. // 写入句子库
  280. $sentData = [];
  281. $sentData = array_map(function ($n) {
  282. $sId = explode('-', $n['id']);
  283. return [
  284. 'book_id' => $sId[0],
  285. 'paragraph' => $sId[1],
  286. 'word_start' => $sId[2],
  287. 'word_end' => $sId[3],
  288. 'channel_uid' => $this->workChannel['id'],
  289. 'content' => $n['content'],
  290. 'content_type' => $n['content_type'] ?? 'markdown',
  291. 'lang' => $this->workChannel['lang'],
  292. 'status' => $this->workChannel['status'],
  293. 'editor_uid' => $this->model['uid'],
  294. ];
  295. }, $data);
  296. foreach ($sentData as $key => $value) {
  297. $this->sentenceService->save($value);
  298. }
  299. }
  300. }