2
0

UpgradeAITranslation.php 13 KB

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