UpgradeAITranslation.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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\PaliSentence;
  7. use App\Models\PaliText;
  8. use App\Models\Sentence;
  9. use App\Services\AIAssistant\NissayaTranslateService;
  10. use App\Services\AIModelService;
  11. use App\Services\AuthService;
  12. use App\Services\OpenAIService;
  13. use App\Services\SearchPaliDataService;
  14. use App\Services\SentenceService;
  15. use App\Tools\Tools;
  16. use Illuminate\Console\Command;
  17. use Illuminate\Support\Facades\Cache;
  18. use Illuminate\Support\Facades\Log;
  19. class UpgradeAITranslation extends Command
  20. {
  21. /**
  22. * The name and signature of the console command.
  23. * php artisan upgrade:ai.translation translation --book=141 --para=535
  24. * php artisan upgrade:ai.translation nissaya --book=207 --para=1247
  25. *
  26. * @var string
  27. */
  28. protected $signature = 'upgrade:ai.translation
  29. {type}
  30. {channel}
  31. {--book=}
  32. {--para=}
  33. {--resume}
  34. {--model=}
  35. {--thinking : 开启和关闭deepseek thinking true | false}
  36. {--fresh : 清除缓存断点,从头开始}';
  37. // 缓存键前缀:以 type、channel 区分,记录已完成的 "book|para" 集合,中断后重跑自动跳过
  38. private const CACHE_KEY_PREFIX = 'upgrade:ai.translation:done';
  39. /**
  40. * The console command description.
  41. *
  42. * @var string
  43. */
  44. protected $description = 'Command description';
  45. protected AiModelResource $model;
  46. protected string $modelToken;
  47. protected array $workChannel;
  48. protected string $accessToken;
  49. protected bool $thinking;
  50. /**
  51. * Create a new command instance.
  52. *
  53. * @return void
  54. */
  55. public function __construct(
  56. protected AIModelService $modelService,
  57. protected SentenceService $sentenceService,
  58. protected OpenAIService $openAIService,
  59. protected NissayaTranslateService $nissayaTranslateService
  60. ) {
  61. parent::__construct();
  62. }
  63. /**
  64. * Execute the console command.
  65. *
  66. * @return int
  67. */
  68. public function handle()
  69. {
  70. if ($this->option('model')) {
  71. $this->model = $this->modelService->getModelById($this->option('model'));
  72. $this->info("model:{$this->model['model']}");
  73. $this->modelToken = AuthService::getUserToken($this->model['uid']);
  74. }
  75. $this->workChannel = ChannelApi::getById($this->argument('channel'));
  76. // 需要判断输入channel 与翻译类型是否一致 nissaya -> nissaya channel
  77. if ($this->workChannel['type'] !== $this->argument('type')) {
  78. $this->error('channel type not match request ' . $this->argument('type') . ' input is ' . $this->workChannel['type']);
  79. return 1;
  80. }
  81. if ($this->option('thinking')) {
  82. $this->thinking = $this->option('thinking') === 'true';
  83. $this->line('thinking is ' . $this->option('thinking'));
  84. }
  85. $type = $this->argument('type');
  86. $channelId = $this->workChannel['id'] ?? '';
  87. // 缓存键:按 type、channel 区分不同任务的断点
  88. $cacheKey = self::CACHE_KEY_PREFIX . ':' . $type . ':' . $channelId;
  89. if ($this->option('fresh')) {
  90. Cache::forget($cacheKey);
  91. $this->info('Cleared cached cursor.');
  92. }
  93. // 是否为完整遍历(未指定 book/para),仅此情形在结束后清空断点缓存
  94. $isFullRun = ! $this->option('book') && ! $this->option('para');
  95. // 从缓存恢复已完成的 (book, para) 集合,作为重入时的稳定游标
  96. $done = Cache::get($cacheKey, []);
  97. $books = [];
  98. if ($this->option('book')) {
  99. $books = [$this->option('book')];
  100. } else {
  101. // 未指定 book 时,若已有断点缓存,从上次处理到的 book 继续,无需从 1 开始
  102. $startBook = 1;
  103. if (! empty($done)) {
  104. $doneBooks = array_map(fn($cursor) => (int) explode('|', $cursor)[0], array_keys($done));
  105. $startBook = max($doneBooks);
  106. $this->info("resume from book {$startBook}");
  107. }
  108. $books = range($startBook, 217);
  109. }
  110. foreach ($books as $key => $book) {
  111. $maxParagraph = PaliText::where('book', $book)->max('paragraph');
  112. $paragraphs = range(1, $maxParagraph);
  113. if ($this->option('para')) {
  114. $paragraphs = [$this->option('para')];
  115. }
  116. foreach ($paragraphs as $key => $paragraph) {
  117. // 稳定游标:缓存键已含 type、channel,此处仅以 book|para 标识处理单元
  118. $cursor = $book . '|' . $paragraph;
  119. if (isset($done[$cursor])) {
  120. $this->info("skip {$cursor}");
  121. continue;
  122. }
  123. $data = [];
  124. switch ($this->argument('type')) {
  125. case 'translation':
  126. $data = $this->aiPaliTranslate($book, $paragraph);
  127. break;
  128. case 'nissaya':
  129. $data = $this->aiNissayaTranslate($book, $paragraph);
  130. break;
  131. case 'wbw':
  132. $data = $this->aiWBW($book, $paragraph);
  133. break;
  134. default:
  135. // code...
  136. break;
  137. }
  138. $this->save($data);
  139. $this->info($this->argument('type') . " {$book}-{$paragraph} " . count($data) . ' sentences');
  140. // 该处理单元全部写库完成后再标记游标,确保中途中断不会误跳过
  141. $done[$cursor] = true;
  142. Cache::put($cacheKey, $done, now()->addHours(24));
  143. }
  144. }
  145. // 完整遍历正常结束,清空断点缓存
  146. if ($isFullRun) {
  147. Cache::forget($cacheKey);
  148. }
  149. return 0;
  150. }
  151. private function getPaliContent($book, $para)
  152. {
  153. $sentenceService = app(SearchPaliDataService::class);
  154. $sentences = PaliSentence::where('book', $book)
  155. ->where('paragraph', $para)
  156. ->orderBy('word_begin')
  157. ->get();
  158. if (! $sentences) {
  159. return null;
  160. }
  161. $json = [];
  162. foreach ($sentences as $key => $sentence) {
  163. $content = $sentenceService->getSentenceContent($book, $para, $sentence->word_begin, $sentence->word_end);
  164. $id = "{$book}-{$para}-{$sentence->word_begin}-{$sentence->word_end}";
  165. $json[] = ['id' => $id, 'content' => $content['markdown']];
  166. }
  167. return $json;
  168. }
  169. private function aiPaliTranslate($book, $para)
  170. {
  171. $prompt = <<<'md'
  172. 你是一个巴利语翻译助手。
  173. pali 是巴利原文的一个段落,json格式, 每条记录是一个句子。包括id 和 content 两个字段
  174. 请翻译这个段落为简体中文。
  175. 翻译要求
  176. 1. 语言风格为现代汉语书面语,不要使用古汉语或者半文半白。
  177. 2. 译文严谨,完全贴合巴利原文,不要加入自己的理解
  178. 3. 巴利原文中的黑体字在译文中也使用黑体。其他标点符号跟随巴利原文,但应该替换为相应的汉字全角符号
  179. 输出格式jsonl
  180. 输出id 和 content 两个字段,
  181. id 使用巴利原文句子的id ,
  182. content 为中文译文
  183. 直接输出jsonl数据,无需解释
  184. **输出范例**
  185. {"id":"1-2-3-4","content":"译文"}
  186. {"id":"2-3-4-5","content":"译文"}
  187. md;
  188. $pali = $this->getPaliContent($book, $para);
  189. $originalText = "```json\n" . json_encode($pali, JSON_UNESCAPED_UNICODE) . "\n```";
  190. Log::debug($originalText);
  191. if (! $this->model) {
  192. Log::error('model is invalid');
  193. return [];
  194. }
  195. $startAt = time();
  196. $llm = $this->openAIService->setApiUrl($this->model['url'])
  197. ->setModel($this->model['model'])
  198. ->setApiKey($this->model['key'])
  199. ->setSystemPrompt($prompt)
  200. ->setTemperature(0.0)
  201. ->setStream(false);
  202. if (isset($this->thinking)) {
  203. $llm = $llm->setThinking($this->thinking);
  204. }
  205. $response = $llm->send("# pali\n\n{$originalText}\n\n");
  206. $complete = time() - $startAt;
  207. $translationText = $response['choices'][0]['message']['content'] ?? '[]';
  208. Log::debug("complete in {$complete}s", ['content' => $translationText]);
  209. $json = [];
  210. if (is_string($translationText)) {
  211. $json = LlmResponseParser::jsonl($translationText);
  212. }
  213. return $json;
  214. }
  215. private function aiWBW($book, $para)
  216. {
  217. $sysPrompt = <<<'md'
  218. 你是一个佛教翻译专家,精通巴利文和缅文,精通巴利文逐词解析
  219. ## 翻译要求:
  220. - 请将用户提供的巴利句子单词表中的每个巴利文单词翻译为中文
  221. - 这些单词是一个完整的句子,请根据单词的上下文翻译
  222. - original 里面的数据是巴利文单词
  223. - 输入格式为 json 数组
  224. - 输出jsonl格式
  225. 在原来的数据中添加下列输出字段
  226. 1. meaning:单词的中文意思,如果有两个可能的意思,两个意思之间用/符号分隔
  227. 5. confidence:你认为你给出的这个单词的信息的信心指数(准确程度) 数值1-100 如果觉得非常有把握100, 如果觉得把握不大,适当降低信心指数
  228. 6. note:如果你认为信心指数很低,这个是疑难单词,请在note字段写明原因,如果不是疑难单词,请不要填写note
  229. **范例**:
  230. {"id":1,"original":"bhikkhusanghassa","meaning":"比库僧团[的]","confidence":100}
  231. 直接输出jsonl, 无需其他内容
  232. md;
  233. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  234. $sentences = Sentence::where('channel_uid', $channelId)
  235. ->where('book_id', $book)
  236. ->where('paragraph', $para)
  237. ->get();
  238. $result = [];
  239. foreach ($sentences as $key => $sentence) {
  240. $wbw = json_decode($sentence->content);
  241. $tpl = [];
  242. foreach ($wbw as $key => $word) {
  243. if (
  244. ! empty($word->real->value) &&
  245. $word->type->value !== '.ctl.'
  246. ) {
  247. $tpl[] = [
  248. 'id' => $word->sn[0],
  249. 'original' => $word->real->value,
  250. ];
  251. }
  252. }
  253. $tplText = json_encode($tpl, JSON_UNESCAPED_UNICODE);
  254. Log::debug($tplText);
  255. $startAt = time();
  256. $llm = $this->openAIService->setApiUrl($this->model['url'])
  257. ->setModel($this->model['model'])
  258. ->setApiKey($this->model['key'])
  259. ->setSystemPrompt($sysPrompt)
  260. ->setTemperature(0.7)
  261. ->setStream(false);
  262. if (isset($this->thinking)) {
  263. $llm = $llm->setThinking($this->thinking);
  264. }
  265. $response = $llm->send("```json\n{$tplText}\n```");
  266. $complete = time() - $startAt;
  267. $content = $response['choices'][0]['message']['content'] ?? '[]';
  268. Log::debug("ai response in {$complete}s content=" . $content);
  269. $json = LlmResponseParser::jsonl($content);
  270. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  271. $result[] = [
  272. 'id' => $id,
  273. 'content' => json_encode($json, JSON_UNESCAPED_UNICODE),
  274. ];
  275. }
  276. return $result;
  277. }
  278. private function aiNissayaTranslate($book, $para)
  279. {
  280. $sysPrompt = <<<'md'
  281. 你是一个佛教翻译专家,精通巴利文和缅文
  282. ## 翻译要求:
  283. - 请将nissaya单词表中的巴利文和缅文分别翻译为中文
  284. - 输入格式为 巴利文:缅文
  285. - 一行是一条记录,翻译的时候,请不要拆分一行中的巴利文单词或缅文单词,一行中出现多个单词的,一起翻译
  286. - 输出csv格式内容,分隔符为"$",
  287. - 字段如下:巴利文$巴利文的中文译文$缅文$缅文的中文译文 #两个译文的语义相似度(%)
  288. **范例**:
  289. pana$然而$ဝါဒန္တရကား$教义之说 #60%
  290. 直接输出csv, 无需其他内容
  291. 用```包裹的行为注释内容,也需要翻译和解释。放在最后面。如果没有```,无需处理
  292. md;
  293. $sentences = Sentence::nissaya()
  294. ->language('my') // 过滤缅文
  295. ->where('book_id', $book)
  296. ->where('paragraph', $para)
  297. ->orderBy('strlen')
  298. ->get();
  299. $result = [];
  300. foreach ($sentences as $key => $sentence) {
  301. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  302. /*
  303. $nissaya = [];
  304. $rows = explode("\n", $sentence->content);
  305. foreach ($rows as $key => $row) {
  306. if (strpos('=', $row) >= 0) {
  307. $factors = explode("=", $row);
  308. $nissaya[] = Tools::MyToRm($factors[0]) . ':' . end($factors);
  309. } else {
  310. $nissaya[] = $row;
  311. }
  312. }
  313. $nissayaText = json_encode(implode("\n", $nissaya), JSON_UNESCAPED_UNICODE);
  314. Log::debug($nissayaText);
  315. $startAt = time();
  316. $response = $this->openAIService->setApiUrl($this->model['url'])
  317. ->setModel($this->model['model'])
  318. ->setApiKey($this->model['key'])
  319. ->setSystemPrompt($sysPrompt)
  320. ->setTemperature(0.7)
  321. ->setStream(false)
  322. ->send("# nissaya\n\n{$nissayaText}\n\n");
  323. $complete = time() - $startAt;
  324. $content = $response['choices'][0]['message']['content'] ?? '';
  325. Log::debug("ai response in {$complete}s content=" . $content);
  326. */
  327. $aiNissaya = $this->nissayaTranslateService
  328. ->setModel($this->model)
  329. ->translate($sentence->content, false);
  330. Log::debug('ai response ', ['content' => $aiNissaya['data']]);
  331. $result[] = [
  332. 'id' => $id,
  333. 'content' => json_encode($aiNissaya['data'] ?? [], JSON_UNESCAPED_UNICODE),
  334. 'content_type' => 'json',
  335. ];
  336. }
  337. return $result;
  338. }
  339. private function save($data)
  340. {
  341. // 写入句子库
  342. $sentData = [];
  343. $sentData = array_map(function ($n) {
  344. $sId = explode('-', $n['id']);
  345. return [
  346. 'book_id' => $sId[0],
  347. 'paragraph' => $sId[1],
  348. 'word_start' => $sId[2],
  349. 'word_end' => $sId[3],
  350. 'channel_uid' => $this->workChannel['id'],
  351. 'content' => $n['content'],
  352. 'content_type' => $n['content_type'] ?? 'markdown',
  353. 'lang' => $this->workChannel['lang'],
  354. 'status' => $this->workChannel['status'],
  355. 'editor_uid' => $this->model['uid'],
  356. ];
  357. }, $data);
  358. foreach ($sentData as $key => $value) {
  359. $this->sentenceService->save($value);
  360. }
  361. }
  362. }