UpgradeAITranslation.php 15 KB

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