UpgradeAITranslation.php 15 KB

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