IndexTipitaka.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Http\Api\ChannelApi;
  4. use App\Models\PaliText;
  5. use App\Models\ProgressChapter;
  6. use App\Models\Sentence;
  7. use App\Services\OpenSearchService;
  8. use App\Services\PaliContentService;
  9. use App\Services\SearchPaliDataService;
  10. use App\Services\SummaryService;
  11. use App\Services\TagService;
  12. use Illuminate\Console\Command;
  13. use Illuminate\Support\Facades\Log;
  14. class IndexTipitaka extends Command
  15. {
  16. /**
  17. * The name and signature of the console command.
  18. * php artisan opensearch:index-tipitaka 93 --para=6 --granularity=paragraph
  19. *
  20. * @var string
  21. */
  22. protected $signature = 'opensearch:index-tipitaka
  23. {book : The book ID to index data for}
  24. {--para= : index paragraph No. omit to all}
  25. {--channel= : index channel id omit to all}
  26. {--test}
  27. {--summary=on}
  28. {--resume}
  29. {--granularity=all : The granularity to index (paragraph, sutta, sentence; omit to index all)}';
  30. /**
  31. * The console command description.
  32. *
  33. * @var string
  34. */
  35. protected $description = 'Index Pali data into OpenSearch for a specified book and optional granularity (all granularities if not specified)';
  36. private $isTest = false;
  37. private $summary = false;
  38. /**
  39. * Create a new command instance.
  40. *
  41. * @return void
  42. */
  43. public function __construct(
  44. protected SearchPaliDataService $searchPaliDataService,
  45. protected OpenSearchService $openSearchService,
  46. protected SummaryService $summaryService,
  47. protected TagService $tagService
  48. ) {
  49. parent::__construct();
  50. }
  51. /**
  52. * Execute the console command.
  53. *
  54. * @return int
  55. */
  56. public function handle()
  57. {
  58. $this->line('index tipitaka start');
  59. $book = (int) $this->argument('book');
  60. $paragraph = $this->option('para');
  61. $channel = $this->option('channel');
  62. if ($channel) {
  63. $this->line('channel='.$channel);
  64. }
  65. $granularity = $this->option('granularity');
  66. $this->summary = $this->option('summary') === 'on';
  67. if ($this->option('test')) {
  68. $this->isTest = true;
  69. $this->info('test mode');
  70. }
  71. try {
  72. // Test OpenSearch connection
  73. [$connected, $message] = $this->openSearchService->testConnection();
  74. if (! $connected) {
  75. $this->error($message);
  76. Log::error($message);
  77. return 1;
  78. }
  79. $overallStatus = 0; // Track overall command status (0 for success, 1 for any failure)
  80. $maxBookId = PaliText::max('book');
  81. if ($book === 0) {
  82. $booksId = range(1, $maxBookId);
  83. } elseif ($this->option('resume')) {
  84. $booksId = range($book, $maxBookId);
  85. } else {
  86. $booksId = [$book];
  87. }
  88. foreach ($booksId as $key => $bookId) {
  89. if (
  90. $this->option('granularity') === 'chapter' ||
  91. $this->option('granularity') === 'all'
  92. ) {
  93. $this->indexChapter($bookId, $channel);
  94. }
  95. if (
  96. $this->option('granularity') === 'paragraph' ||
  97. $this->option('granularity') === 'all'
  98. ) {
  99. $this->indexTipitakaParagraph($bookId, $paragraph);
  100. }
  101. }
  102. return $overallStatus;
  103. } catch (\Exception $e) {
  104. $this->error('Failed to index Pali data: '.$e->getMessage());
  105. Log::error("Failed to index Pali data for book: $book, granularity: ".($granularity ?: 'all'), ['error' => $e]);
  106. return 1;
  107. }
  108. }
  109. /**
  110. * Index Pali paragraphs for a given book.
  111. *
  112. * @param int $book
  113. * @return int
  114. */
  115. protected function indexTipitakaParagraph($book, $paragraph = null)
  116. {
  117. $this->info("Starting to index paragraphs for book: $book");
  118. $total = 0;
  119. if ($paragraph) {
  120. $paragraphs = PaliText::where('book', $book)
  121. ->where('paragraph', $paragraph)
  122. ->orderBy('paragraph')->cursor();
  123. } else {
  124. $paragraphs = PaliText::where('book', $book)
  125. ->orderBy('paragraph')->cursor();
  126. }
  127. $bookUid = PaliText::where('book', $book)->where('level', 1)->first()->uid;
  128. $category = $this->tagService->getTagsName($bookUid);
  129. $headings = [];
  130. $currChapterTitle = '';
  131. $commentaryId = '';
  132. $currSession = [];
  133. foreach ($paragraphs as $key => $para) {
  134. $total++;
  135. if ($para->level < 8) {
  136. $currChapterTitle = $para->toc;
  137. }
  138. if ($para->class === 'nikaya') {
  139. $nikaya = $para->text;
  140. }
  141. $paraContent = $this->searchPaliDataService
  142. ->getParaContent($para['book'], $para['paragraph']);
  143. if (! empty($commentaryId)) {
  144. $currSession[] = $paraContent;
  145. }
  146. if (isset($paraContent['commentary'])) {
  147. if (! empty($commentaryId)) {
  148. // 保存 session
  149. $this->indexPaliSession($para->toArray(), $currSession, $currChapterTitle, $commentaryId);
  150. $currSession = [];
  151. }
  152. $commentaryId = $paraContent['commentary'];
  153. }
  154. $this->indexParagraph($para->toArray(), $paraContent, $commentaryId, $category);
  155. $this->info("{$para['book']}-[{$para['paragraph']}]-[{$commentaryId}]");
  156. }
  157. $this->info("Successfully indexed $total paragraphs for book: $book");
  158. Log::info("Indexed $total paragraphs for book: $book");
  159. return 0;
  160. }
  161. protected function indexParagraph($paraInfo, $paraContent, $related_id, array $category)
  162. {
  163. $paraId = $paraInfo['book'].'-'.$paraInfo['paragraph'];
  164. $resource_id = $paraInfo['uid'];
  165. $path = json_decode($paraInfo['path']);
  166. if (is_array($path) && count($path) > 0) {
  167. $title = end($path)->title;
  168. } else {
  169. $title = '';
  170. }
  171. $document = [
  172. 'id' => "tipitaka_paragraph_pi_{$paraId}",
  173. 'resource_id' => $resource_id, // Use uid from getPaliData for resource_id
  174. 'resource_type' => 'tipitaka',
  175. 'title' => [
  176. 'text' => ['pali' => $title],
  177. ],
  178. 'summary' => [
  179. 'text' => $this->summary ? $this->summaryService->summarize($paraContent['markdown']) : '',
  180. ],
  181. 'content' => [
  182. 'text' => ['pali' => $paraContent['text']],
  183. 'suggest' => ['pali' => $paraContent['words']],
  184. ],
  185. 'bold_single' => implode(' ', $paraContent['bold1']),
  186. 'bold_multi' => implode(' ', array_merge($paraContent['bold2'], $paraContent['bold3'])),
  187. 'related_id' => $paraId,
  188. 'category' => $category, // Assuming Pali paragraphs are sutta; adjust as needed
  189. 'language' => 'pi',
  190. 'updated_at' => now()->toIso8601String(),
  191. 'granularity' => 'paragraph',
  192. 'path' => $this->getPathTitle($path),
  193. ];
  194. if ($paraInfo['level'] < 8) {
  195. $document['title']['suggest']['pali'] = $paraContent['words'];
  196. }
  197. if ($this->isTest) {
  198. $this->info($document['title']['text']['pali']);
  199. $this->info($document['summary']['text']);
  200. } else {
  201. $this->openSearchService->create($document['id'], $document);
  202. }
  203. }
  204. protected function indexPaliSession($paraInfo, $contents, $currChapter, $related_id)
  205. {
  206. $markdown = [];
  207. $text = [];
  208. $bold_single = [];
  209. $bold_multi = [];
  210. foreach ($contents as $key => $content) {
  211. $markdown[] = $content['markdown'];
  212. $text[] = $content['text'];
  213. $bold_single = array_merge($bold_single, $content['bold1']);
  214. $bold_multi = array_merge($bold_multi, $content['bold2'], $content['bold3']);
  215. }
  216. $document = [
  217. 'id' => "pali_session_{$related_id}",
  218. 'resource_id' => $paraInfo['uid'], // Use uid from getPaliData for resource_id
  219. 'resource_type' => 'original_text',
  220. 'title' => [
  221. ['text' => ['pali' => "{$currChapter} paragraph {$paraInfo['paragraph']}"]],
  222. ],
  223. 'summary' => [
  224. 'text' => $this->summary ? $this->summaryService->summarize($content['markdown']) : '',
  225. ],
  226. 'content' => [
  227. ['text' => ['pali' => implode("\n\n", $markdown)]],
  228. ],
  229. 'bold_single' => implode(' ', $bold_single),
  230. 'bold_multi' => implode(' ', $bold_multi),
  231. 'related_id' => $related_id,
  232. 'category' => 'pali', // Assuming Pali paragraphs are sutta; adjust as needed
  233. 'language' => 'pi',
  234. 'updated_at' => now()->toIso8601String(),
  235. 'granularity' => 'session',
  236. 'path' => $this->getPathTitle(json_decode($paraInfo['path'])),
  237. ];
  238. if ($this->isTest) {
  239. $this->info($document['title']['pali']);
  240. $this->info($document['summary']['text']);
  241. } else {
  242. $this->openSearchService->create($document['id'], $document);
  243. }
  244. }
  245. /**
  246. * Index Pali suttas for a given book (placeholder for future implementation).
  247. *
  248. * @param int $book
  249. * @param ?string $channel
  250. * @return int
  251. */
  252. protected function indexChapter($book, $channelId = null)
  253. {
  254. $this->info("Starting to index paragraphs for book: $book");
  255. $total = 0;
  256. $chapters = PaliText::where('book', $book)
  257. ->where('level', '<', 8)
  258. ->orderBy('paragraph')->get();
  259. foreach ($chapters as $key => $chapter) {
  260. if ($chapter->level === 1) {
  261. $category = $this->tagService->getTagsName($chapter->uid);
  262. }
  263. /**
  264. * 章节的起始位置算法
  265. * 从章节的标题,到下一个章节的标题之间
  266. */
  267. $start = $chapter->paragraph;
  268. if ($key === count($chapters) - 1) {
  269. $end = PaliText::where('book', $book)
  270. ->orderBy('paragraph', 'desc')->first()
  271. ->value('paragraph');
  272. } else {
  273. $end = $chapters[$key + 1]->paragraph - 1;
  274. }
  275. // 获取这个段落之间的全部channel
  276. $table = Sentence::where('book_id', $book)
  277. ->whereBetween('paragraph', [$start, $end]);
  278. if ($channelId) {
  279. $table = $table->where('channel_uid', $channelId);
  280. }
  281. $channels = $table->select('channel_uid')
  282. ->groupBy('channel_uid')->get();
  283. $this->info("index chapter start={$start} end={$end}");
  284. foreach ($channels as $channel) {
  285. $display = [];
  286. $content = [];
  287. $channelInfo = ChannelApi::getById($channel->channel_uid);
  288. if (! $channelInfo) {
  289. Log::error('invalid channel', ['id' => $channel->channel_uid]);
  290. continue;
  291. }
  292. $this->info('channel ='.$channelInfo['name']);
  293. if ($channelInfo['type'] === 'wbw') {
  294. $this->info('wbw channel skip');
  295. continue;
  296. }
  297. $paragraphsData = app(PaliContentService::class)->paragraphs(
  298. $book,
  299. $start,
  300. $end,
  301. [$channel->channel_uid],
  302. ['mode' => 'read', 'format' => 'html', 'original' => false]
  303. );
  304. // 生成html数据
  305. $title = '';
  306. foreach ($paragraphsData as $paragraph) {
  307. $translation = [];
  308. $original = [];
  309. foreach ($paragraph['children'] as $sent) {
  310. $sid = "{$sent['book']}-{$sent['para']}-{$sent['wordStart']}-{$sent['wordEnd']}";
  311. if (isset($sent['translation'])) {
  312. foreach ($sent['translation'] as $tran) {
  313. if ($tran['channel']['id'] === $channel->channel_uid) {
  314. $html = $tran['html'] ?? $tran['content'];
  315. $translation[] = "<div class='sentence' data-sid='{$sid}'>{$html}</div>";
  316. if ($tran['para'] === $start && ! empty($html)) {
  317. $title = $html;
  318. }
  319. }
  320. }
  321. }
  322. if (
  323. isset($sent['origin']) ||
  324. is_array($sent['origin']) ||
  325. count($sent['origin']) > 0
  326. ) {
  327. foreach ($sent['origin'] as $origin) {
  328. if ($origin['channel']['id'] === $channel->channel_uid) {
  329. $html = $origin['html'] ?? $origin['content'];
  330. $original[] = "<div class='sentence origin' data-sid='{$sid}'>{$html}</div>";
  331. if (empty($title) && $origin['para'] === $start && ! empty($html)) {
  332. $title = $html;
  333. }
  334. }
  335. }
  336. }
  337. }
  338. $level = $paragraph['para'] === $start ? $chapter->level : 0;
  339. $strOriginal = implode('', $original);
  340. $strTranslation = implode('', $translation);
  341. if ($channelInfo['type'] === 'original') {
  342. $htmlContent = $strOriginal;
  343. } else {
  344. $htmlContent = $strTranslation;
  345. }
  346. $area = $channelInfo['type'] === 'original' ? 'original' : 'translation';
  347. if ($level > 0) {
  348. $display[] = "<div class='{$area}' data-para='{$paragraph['para']}'><h{$level}>{$htmlContent}</h{$level}></div>";
  349. } else {
  350. $display[] = "<div class='{$area}' data-para='{$paragraph['para']}'><div class='para-block'>{$htmlContent}</div></div>";
  351. }
  352. }
  353. $this->chapterSave([
  354. 'book' => $book,
  355. 'para' => $start,
  356. 'level' => $chapter->level,
  357. 'channel' => $channel->channel_uid,
  358. 'content' => implode('', $display),
  359. 'title' => strip_tags($title),
  360. 'cat' => $category ?? null,
  361. ]);
  362. }
  363. }
  364. return 0;
  365. }
  366. protected function chapterSave(array $param)
  367. {
  368. $progress = ProgressChapter::where('book', $param['book'])
  369. ->where('para', $param['para'])
  370. ->where('channel_id', $param['channel'])
  371. ->first();
  372. $channel = ChannelApi::getById($param['channel']);
  373. $document = [
  374. 'id' => "tipitaka_chapter_{$param['book']}-{$param['para']}_{$param['channel']}",
  375. 'resource_id' => $progress ? $progress->uid : "{$param['book']}-{$param['para']}_{$param['channel']}",
  376. 'resource_type' => 'tipitaka',
  377. 'title' => [],
  378. 'summary' => [
  379. 'text' => '',
  380. ],
  381. 'content' => [],
  382. 'related_id' => "{$param['book']}-{$param['para']}",
  383. 'category' => $param['cat'],
  384. 'language' => $channel['lang'],
  385. 'updated_at' => now()->toIso8601String(),
  386. 'granularity' => $param['level'] === 1 ? 'book' : 'chapter',
  387. ];
  388. // TODO: 补充语言判断,将内容放入对应的 text.pali 或 text.zh 字段
  389. $plainText = strip_tags($param['content']);
  390. $title = strip_tags($param['title']);
  391. if (str_contains($channel['lang'], 'zh')) {
  392. $document['content']['text']['zh'] = $plainText;
  393. $document['title']['text']['zh'] = $title;
  394. } else {
  395. $document['content']['text']['pali'] = $plainText;
  396. $document['title']['text']['pali'] = $title;
  397. }
  398. $document['content']['display'] = $param['content']; // 展示
  399. if ($this->isTest) {
  400. $this->info($param['content']);
  401. } else {
  402. $this->openSearchService->create($document['id'], $document);
  403. $this->info("create index {$document['id']} size=".strlen($param['content']));
  404. }
  405. }
  406. /**
  407. * Index Pali sentences for a given book (placeholder for future implementation).
  408. *
  409. * @param int $book
  410. * @return int
  411. */
  412. protected function indexPaliSentences($book)
  413. {
  414. $this->warn("Sentence indexing is not yet implemented for book: $book");
  415. Log::warning("Sentence indexing not implemented for book: $book");
  416. return 1;
  417. }
  418. private function getPathTitle(array $input)
  419. {
  420. $output = [];
  421. foreach ($input as $key => $node) {
  422. $output[] = $node->title;
  423. }
  424. return implode('/', $output);
  425. }
  426. }