IndexTipitaka.php 17 KB

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