IndexTipitaka.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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\Cache;
  14. use Illuminate\Support\Facades\Log;
  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. $paraList = Sentence::where('book_id', $book)
  299. ->whereBetween('paragraph', [$start, $end])
  300. ->where('channel_uid', $channel->channel_uid)
  301. ->orderBy('paragraph')
  302. ->distinct()->pluck('paragraph');
  303. // 生成html数据
  304. $title = '';
  305. foreach ($paraList as $para) {
  306. $para = (int) $para;
  307. $paragraph = app(PaliContentService::class)->readParagraph(
  308. $book,
  309. $para,
  310. $channel->channel_uid,
  311. 'html'
  312. );
  313. if (empty($paragraph['display'])) {
  314. continue;
  315. }
  316. if ($para === $start && empty($title)) {
  317. $title = $paragraph['sentences'][0]['html'];
  318. }
  319. $display[] = $paragraph['display'];
  320. }
  321. $this->chapterSave([
  322. 'book' => $book,
  323. 'para' => $start,
  324. 'level' => $chapter->level,
  325. 'channel' => $channel->channel_uid,
  326. 'content' => implode('', $display),
  327. 'title' => strip_tags($title),
  328. 'cat' => $category ?? null,
  329. ]);
  330. }
  331. }
  332. return 0;
  333. }
  334. protected function chapterSave(array $param)
  335. {
  336. $progress = ProgressChapter::where('book', $param['book'])
  337. ->where('para', $param['para'])
  338. ->where('channel_id', $param['channel'])
  339. ->first();
  340. $channel = ChannelApi::getById($param['channel']);
  341. $docId = "tipitaka_chapter_{$param['book']}-{$param['para']}_{$param['channel']}";
  342. $document = [
  343. 'id' => $docId,
  344. 'resource_id' => $progress ? $progress->uid : "{$param['book']}-{$param['para']}_{$param['channel']}",
  345. 'resource_type' => 'tipitaka',
  346. 'title' => [],
  347. 'summary' => [
  348. 'text' => '',
  349. ],
  350. 'content' => [],
  351. 'related_id' => "{$param['book']}-{$param['para']}",
  352. 'category' => $param['cat'],
  353. 'language' => $channel['lang'],
  354. 'updated_at' => now()->toIso8601String(),
  355. 'granularity' => $param['level'] === 1 ? 'book' : 'chapter',
  356. ];
  357. // TODO: 补充语言判断,将内容放入对应的 text.pali 或 text.zh 字段
  358. $plainText = strip_tags($param['content']);
  359. $title = strip_tags($param['title']);
  360. if (str_contains($channel['lang'], 'zh')) {
  361. $document['content']['text']['zh'] = $plainText;
  362. $document['title']['text']['zh'] = $title;
  363. } else {
  364. $document['content']['text']['pali'] = $plainText;
  365. $document['title']['text']['pali'] = $title;
  366. }
  367. $document['content']['display'] = $param['content']; // 展示
  368. Cache::put($docId, $param['content']);
  369. if ($this->isTest) {
  370. $this->info($param['content']);
  371. } else {
  372. $this->openSearchService->create($document['id'], $document);
  373. $this->info("create index {$document['id']} size=".strlen($param['content']));
  374. }
  375. }
  376. /**
  377. * Index Pali sentences for a given book (placeholder for future implementation).
  378. *
  379. * @param int $book
  380. * @return int
  381. */
  382. protected function indexPaliSentences($book)
  383. {
  384. $this->warn("Sentence indexing is not yet implemented for book: $book");
  385. Log::warning("Sentence indexing not implemented for book: $book");
  386. return 1;
  387. }
  388. private function getPathTitle(array $input)
  389. {
  390. $output = [];
  391. foreach ($input as $key => $node) {
  392. $output[] = $node->title;
  393. }
  394. return implode('/', $output);
  395. }
  396. }