IndexTipitaka.php 17 KB

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