UpgradeAITranslation.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. namespace App\Console\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Http;
  6. use App\Services\OpenAIService;
  7. use App\Services\AIModelService;
  8. use App\Services\SentenceService;
  9. use App\Services\SearchPaliDataService;
  10. use App\Http\Controllers\AuthController;
  11. use App\Models\PaliText;
  12. use App\Models\PaliSentence;
  13. use App\Models\Sentence;
  14. use App\Helpers\LlmResponseParser;
  15. use App\Http\Api\ChannelApi;
  16. use App\Tools\Tools;
  17. class UpgradeAITranslation extends Command
  18. {
  19. /**
  20. * The name and signature of the console command.
  21. * php artisan upgrade:ai.translation translation --book=141 --para=535
  22. * @var string
  23. */
  24. protected $signature = 'upgrade:ai.translation {type} {--book=} {--para=} {--resume} {--model=} ';
  25. /**
  26. * The console command description.
  27. *
  28. * @var string
  29. */
  30. protected $description = 'Command description';
  31. protected $sentenceService;
  32. protected $modelService;
  33. protected $openAIService;
  34. protected $model;
  35. protected $modelToken;
  36. protected $workChannel;
  37. protected $accessToken;
  38. /**
  39. * Create a new command instance.
  40. *
  41. * @return void
  42. */
  43. public function __construct(
  44. AIModelService $model,
  45. SentenceService $sent,
  46. OpenAIService $openAI
  47. ) {
  48. $this->modelService = $model;
  49. $this->sentenceService = $sent;
  50. $this->openAIService = $openAI;
  51. parent::__construct();
  52. }
  53. /**
  54. * Execute the console command.
  55. *
  56. * @return int
  57. */
  58. public function handle()
  59. {
  60. if ($this->option('model')) {
  61. $this->model = $this->modelService->getModelById($this->option('model'));
  62. $this->info("model:{$this->model['model']}");
  63. $this->modelToken = AuthController::getUserToken($this->model['uid']);
  64. }
  65. $this->workChannel = ChannelApi::getById($this->ask('请输入结果channel'));
  66. $books = [];
  67. if ($this->option('book')) {
  68. $books = [$this->option('book')];
  69. } else {
  70. $books = range(1, 217);
  71. }
  72. foreach ($books as $key => $book) {
  73. $maxParagraph = PaliText::where('book', $book)->max('paragraph');
  74. $paragraphs = range(1, $maxParagraph);
  75. if ($this->option('para')) {
  76. $paragraphs = [$this->option('para')];
  77. }
  78. foreach ($paragraphs as $key => $paragraph) {
  79. $this->info($this->argument('type') . " {$book}-{$paragraph}");
  80. $data = [];
  81. switch ($this->argument('type')) {
  82. case 'translation':
  83. $data = $this->aiPaliTranslate($book, $paragraph);
  84. break;
  85. case 'nissaya':
  86. $data = $this->aiNissayaTranslate($book, $paragraph);
  87. case 'wbw':
  88. $data = $this->aiWBW($book, $paragraph);
  89. default:
  90. # code...
  91. break;
  92. }
  93. $this->save($data);
  94. }
  95. }
  96. return 0;
  97. }
  98. private function getPaliContent($book, $para)
  99. {
  100. $sentenceService = app(SearchPaliDataService::class);
  101. $sentences = PaliSentence::where('book', $book)
  102. ->where('paragraph', $para)
  103. ->orderBy('word_begin')
  104. ->get();
  105. if (!$sentences) {
  106. return null;
  107. }
  108. $json = [];
  109. foreach ($sentences as $key => $sentence) {
  110. $content = $sentenceService->getSentenceText($book, $para, $sentence->word_begin, $sentence->word_end);
  111. $id = "{$book}-{$para}-{$sentence->word_begin}-{$sentence->word_end}";
  112. $json[] = ['id' => $id, 'content' => $content['markdown']];
  113. }
  114. return $json;
  115. }
  116. private function aiPaliTranslate($book, $para)
  117. {
  118. $prompt = <<<md
  119. 你是一个巴利语翻译助手。
  120. pali 是巴利原文的一个段落,json格式, 每条记录是一个句子。包括id 和 content 两个字段
  121. 请翻译这个段落为简体中文。
  122. 翻译要求
  123. 1. 语言风格为现代汉语书面语,不要使用古汉语或者半文半白。
  124. 2. 译文严谨,完全贴合巴利原文,不要加入自己的理解
  125. 3. 巴利原文中的黑体字在译文中也使用黑体。其他标点符号跟随巴利原文,但应该替换为相应的汉字全角符号
  126. 输出格式jsonl
  127. 输出id 和 content 两个字段,
  128. id 使用巴利原文句子的id ,
  129. content 为中文译文
  130. 直接输出jsonl数据,无需解释
  131. **输出范例**
  132. {"id":"1-2-3-4","content":"译文"}
  133. {"id":"2-3-4-5","content":"译文"}
  134. md;
  135. $pali = $this->getPaliContent($book, $para);
  136. $originalText = "```json\n" . json_encode($pali, JSON_UNESCAPED_UNICODE) . "\n```";
  137. Log::debug($originalText);
  138. if (!$this->model) {
  139. Log::error('model is invalid');
  140. return [];
  141. }
  142. $startAt = time();
  143. $response = $this->openAIService->setApiUrl($this->model['url'])
  144. ->setModel($this->model['model'])
  145. ->setApiKey($this->model['key'])
  146. ->setSystemPrompt($prompt)
  147. ->setTemperature(0.0)
  148. ->setStream(false)
  149. ->send("# pali\n\n{$originalText}\n\n");
  150. $complete = time() - $startAt;
  151. $translationText = $response['choices'][0]['message']['content'] ?? '[]';
  152. Log::debug("complete in {$complete}s", $translationText);
  153. $json = [];
  154. if (is_string($translationText)) {
  155. $json = LlmResponseParser::jsonl($translationText);
  156. }
  157. return $json;
  158. }
  159. private function aiWBW($book, $para)
  160. {
  161. $sysPrompt = <<<md
  162. 你是一个佛教翻译专家,精通巴利文和缅文,精通巴利文逐词解析
  163. ## 翻译要求:
  164. - 请将用户提供的巴利句子单词表中的每个巴利文单词翻译为中文
  165. - 这些单词是一个完整的句子,请根据单词的上下文翻译
  166. - original 里面的数据是巴利文单词
  167. - 输入格式为 json 数组
  168. - 输出jsonl格式
  169. 在原来的数据中添加下列输出字段
  170. 1. meaning:单词的中文意思,如果有两个可能的意思,两个意思之间用/符号分隔
  171. 5. confidence:你认为你给出的这个单词的信息的信心指数(准确程度) 数值1-100 如果觉得非常有把握100, 如果觉得把握不大,适当降低信心指数
  172. 6. note:如果你认为信心指数很低,这个是疑难单词,请在note字段写明原因,如果不是疑难单词,请不要填写note
  173. **范例**:
  174. {"id":1,"original":"bhikkhusanghassa","meaning":"比库僧团[的]","confidence":100}
  175. 直接输出jsonl, 无需其他内容
  176. md;
  177. $channelId = ChannelApi::getSysChannel('_System_Wbw_VRI_');
  178. $sentences = Sentence::where('channel_uid', $channelId)
  179. ->where('book_id', $book)
  180. ->where('paragraph', $para)
  181. ->get();
  182. $result = [];
  183. foreach ($sentences as $key => $sentence) {
  184. $wbw = json_decode($sentence->content);
  185. $tpl = [];
  186. foreach ($wbw as $key => $word) {
  187. if (
  188. !empty($word->real->value) &&
  189. $word->type->value !== '.ctl.'
  190. ) {
  191. $tpl[] = [
  192. 'id' => $word->sn[0],
  193. 'original' => $word->real->value,
  194. ];
  195. }
  196. }
  197. $tplText = json_encode($tpl, JSON_UNESCAPED_UNICODE);
  198. Log::debug($tplText);
  199. $startAt = time();
  200. $response = $this->openAIService->setApiUrl($this->model['url'])
  201. ->setModel($this->model['model'])
  202. ->setApiKey($this->model['key'])
  203. ->setSystemPrompt($sysPrompt)
  204. ->setTemperature(0.7)
  205. ->setStream(false)
  206. ->send("```json\n{$tplText}\n```");
  207. $complete = time() - $startAt;
  208. $content = $response['choices'][0]['message']['content'] ?? '[]';
  209. Log::debug("ai response in {$complete}s content=" . $content);
  210. $json = LlmResponseParser::jsonl($content);
  211. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  212. $result[] = [
  213. 'id' => $id,
  214. 'content' => json_encode($json, JSON_UNESCAPED_UNICODE),
  215. ];
  216. }
  217. return $result;
  218. }
  219. private function aiNissayaTranslate($book, $para)
  220. {
  221. $sysPrompt = <<<md
  222. 你是一个佛教翻译专家,精通巴利文和缅文
  223. ## 翻译要求:
  224. - 请将nissaya单词表中的巴利文和缅文分别翻译为中文
  225. - 输入格式为 巴利文:缅文
  226. - 一行是一条记录,翻译的时候,请不要拆分一行中的巴利文单词或缅文单词,一行中出现多个单词的,一起翻译
  227. - 输出csv格式内容,分隔符为"$",
  228. - 字段如下:巴利文\$巴利文的中文译文\$缅文\$缅文的中文译文 #两个译文的语义相似度(%)
  229. **范例**:
  230. pana\$然而\$ဝါဒန္တရကား\$教义之说 #60%
  231. 直接输出csv, 无需其他内容
  232. 用```包裹的行为注释内容,也需要翻译和解释。放在最后面。如果没有```,无需处理
  233. md;
  234. $sentences = Sentence::nissaya()
  235. ->language('my') // 过滤缅文
  236. ->where('book_id', $book)
  237. ->where('paragraph', $para)
  238. ->orderBy('strlen')
  239. ->get();
  240. $result = [];
  241. foreach ($sentences as $key => $sentence) {
  242. $nissaya = [];
  243. $rows = explode("\n", $sentence->content);
  244. foreach ($rows as $key => $row) {
  245. if (strpos('=', $row) >= 0) {
  246. $factors = explode("=", $row);
  247. $nissaya[] = Tools::MyToRm($factors[0]) . ':' . end($factors);
  248. } else {
  249. $nissaya[] = $row;
  250. }
  251. }
  252. $nissayaText = json_encode(implode("\n", $nissaya), JSON_UNESCAPED_UNICODE);
  253. Log::debug($nissayaText);
  254. $startAt = time();
  255. $response = $this->openAIService->setApiUrl($this->model['url'])
  256. ->setModel($this->model['model'])
  257. ->setApiKey($this->model['key'])
  258. ->setSystemPrompt($sysPrompt)
  259. ->setTemperature(0.7)
  260. ->setStream(false)
  261. ->send("# nissaya\n\n{$nissayaText}\n\n");
  262. $complete = time() - $startAt;
  263. $content = $response['choices'][0]['message']['content'] ?? '';
  264. Log::debug("ai response in {$complete}s content=" . $content);
  265. $id = "{$sentence->book_id}-{$sentence->paragraph}-{$sentence->word_start}-{$sentence->word_end}";
  266. $result[] = [
  267. 'id' => $id,
  268. 'content' => $content,
  269. ];
  270. }
  271. return $result;
  272. }
  273. private function save($data)
  274. {
  275. //写入句子库
  276. $sentData = [];
  277. $sentData = array_map(function ($n) {
  278. $sId = explode('-', $n['id']);
  279. return [
  280. 'book_id' => $sId[0],
  281. 'paragraph' => $sId[1],
  282. 'word_start' => $sId[2],
  283. 'word_end' => $sId[3],
  284. 'channel_uid' => $this->workChannel['id'],
  285. 'content' => $n['content'],
  286. 'content_type' => $n['content_type'] ?? 'markdown',
  287. 'lang' => $this->workChannel['lang'],
  288. 'status' => $this->workChannel['status'],
  289. 'editor_uid' => $this->model['uid'],
  290. ];
  291. }, $data);
  292. foreach ($sentData as $key => $value) {
  293. $this->sentenceService->save($value);
  294. }
  295. }
  296. }