UpgradeAITranslation.php 12 KB

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