2
0

IndexPaliText.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. class IndexPaliText extends Command
  11. {
  12. /**
  13. * The name and signature of the console command.
  14. * php artisan opensearch:index-pali 93 --para=6
  15. * @var string
  16. */
  17. protected $signature = 'opensearch:index-pali {book : The book ID to index data for}
  18. {--test}
  19. {--para= : index paragraph No. omit to all}
  20. {--summary=on}
  21. {--resume}
  22. {--granularity= : The granularity to index (paragraph, sutta, sentence; omit to index all)}';
  23. /**
  24. * The console command description.
  25. *
  26. * @var string
  27. */
  28. protected $description = 'Index Pali data into OpenSearch for a specified book and optional granularity (all granularities if not specified)';
  29. protected $searchPaliDataService;
  30. protected $openSearchService;
  31. protected $summaryService;
  32. protected $tagService;
  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. SearchPaliDataService $searchPaliDataService,
  42. OpenSearchService $openSearchService,
  43. SummaryService $summaryService,
  44. TagService $tagService
  45. ) {
  46. parent::__construct();
  47. $this->searchPaliDataService = $searchPaliDataService;
  48. $this->openSearchService = $openSearchService;
  49. $this->summaryService = $summaryService;
  50. $this->tagService = $tagService;
  51. }
  52. /**
  53. * Execute the console command.
  54. *
  55. * @return int
  56. */
  57. public function handle()
  58. {
  59. $book = (int)$this->argument('book');
  60. $granularity = $this->option('granularity');
  61. $paragraph = $this->option('para');
  62. $this->summary = $this->option('summary') === 'on';
  63. if ($this->option('test')) {
  64. $this->isTest = true;
  65. $this->info('test mode');
  66. }
  67. try {
  68. // Test OpenSearch connection
  69. [$connected, $message] = $this->openSearchService->testConnection();
  70. if (!$connected) {
  71. $this->error($message);
  72. Log::error($message);
  73. return 1;
  74. }
  75. $overallStatus = 0; // Track overall command status (0 for success, 1 for any failure)
  76. $maxBookId = PaliText::max('book');
  77. if ($book === 0) {
  78. $booksId = range(1, $maxBookId);
  79. } else if ($this->option('resume')) {
  80. $booksId = range($book, $maxBookId);
  81. } else {
  82. $booksId = [$book];
  83. }
  84. foreach ($booksId as $key => $bookId) {
  85. $this->indexPaliParagraphs($bookId, $paragraph);
  86. }
  87. return $overallStatus;
  88. } catch (\Exception $e) {
  89. $this->error("Failed to index Pali data: " . $e->getMessage());
  90. Log::error("Failed to index Pali data for book: $book, granularity: " . ($granularity ?: 'all'), ['error' => $e]);
  91. return 1;
  92. }
  93. }
  94. /**
  95. *
  96. */
  97. protected function indexPaliParagraph($paraInfo, $paraContent, $related_id, array $category)
  98. {
  99. $paraId = $paraInfo['book'] . '_' . $paraInfo['paragraph'];
  100. $resource_id = $paraInfo['uid'];
  101. $path = json_decode($paraInfo['path']);
  102. if (is_array($path) && count($path) > 0) {
  103. $title = end($path)->title;
  104. } else {
  105. $title = '';
  106. }
  107. $document = [
  108. 'id' => "pali_para_{$paraId}",
  109. 'resource_id' => $resource_id, // Use uid from getPaliData for resource_id
  110. 'resource_type' => 'original_text',
  111. 'title' => [
  112. 'pali' => $title,
  113. ],
  114. 'summary' => [
  115. 'text' => $this->summary ? $this->summaryService->summarize($paraContent['markdown']) : ''
  116. ],
  117. 'content' => [
  118. 'pali' => $paraContent['markdown'],
  119. 'suggest' => $paraContent['words'],
  120. ],
  121. 'bold_single' => implode(' ', $paraContent['bold1']),
  122. 'bold_multi' => implode(' ', array_merge($paraContent['bold2'], $paraContent['bold3'])),
  123. 'related_id' => $related_id,
  124. 'category' => $category, // Assuming Pali paragraphs are sutta; adjust as needed
  125. 'language' => 'pali',
  126. 'updated_at' => now()->toIso8601String(),
  127. 'granularity' => 'paragraph',
  128. 'path' => $this->getPathTitle($path),
  129. ];
  130. if ($paraInfo['level'] < 8) {
  131. $document['title']['suggest'] = $paraContent['words'];
  132. }
  133. if ($this->isTest) {
  134. $this->info($document['title']['pali']);
  135. $this->info($document['summary']['text']);
  136. } else {
  137. $this->openSearchService->create($document['id'], $document);
  138. }
  139. return;
  140. }
  141. /**
  142. *
  143. */
  144. protected function indexPaliSession($paraInfo, $contents, $currChapter, $related_id)
  145. {
  146. $markdown = [];
  147. $text = [];
  148. $bold_single = [];
  149. $bold_multi = [];
  150. foreach ($contents as $key => $content) {
  151. $markdown[] = $content['markdown'];
  152. $text[] = $content['text'];
  153. $bold_single = array_merge($bold_single, $content['bold1']);
  154. $bold_multi = array_merge($bold_multi, $content['bold2'], $content['bold3']);
  155. }
  156. $document = [
  157. 'id' => "pali_session_{$related_id}",
  158. 'resource_id' => $paraInfo['uid'], // Use uid from getPaliData for resource_id
  159. 'resource_type' => 'original_text',
  160. 'title' => [
  161. 'pali' => "{$currChapter} paragraph {$paraInfo['paragraph']}"
  162. ],
  163. 'summary' => [
  164. 'text' => $this->summary ? $this->summaryService->summarize($content['markdown']) : ''
  165. ],
  166. 'content' => [
  167. 'pali' => implode("\n\n", $markdown),
  168. ],
  169. 'bold_single' => implode(" ", $bold_single),
  170. 'bold_multi' => implode(" ", $bold_multi),
  171. 'related_id' => $related_id,
  172. 'category' => 'pali', // Assuming Pali paragraphs are sutta; adjust as needed
  173. 'language' => 'pali',
  174. 'updated_at' => now()->toIso8601String(),
  175. 'granularity' => 'session',
  176. 'path' => $this->getPathTitle(json_decode($paraInfo['path'])),
  177. ];
  178. if ($this->isTest) {
  179. $this->info($document['title']['pali']);
  180. $this->info($document['summary']['text']);
  181. } else {
  182. $this->openSearchService->create($document['id'], $document);
  183. }
  184. return;
  185. }
  186. private function getPathTitle(array $input)
  187. {
  188. $output = [];
  189. foreach ($input as $key => $node) {
  190. $output[] = $node->title;
  191. }
  192. return implode('/', $output);
  193. }
  194. /**
  195. * Index Pali paragraphs for a given book.
  196. *
  197. * @param int $book
  198. * @return int
  199. */
  200. protected function indexPaliParagraphs($book, $paragraph = null)
  201. {
  202. $this->info("Starting to index paragraphs for book: $book");
  203. $total = 0;
  204. if ($paragraph) {
  205. $paragraphs = PaliText::where('book', $book)
  206. ->where('paragraph', $paragraph)
  207. ->orderBy('paragraph')->cursor();
  208. } else {
  209. $paragraphs = PaliText::where('book', $book)
  210. ->orderBy('paragraph')->cursor();
  211. }
  212. $bookUid = PaliText::where('book', $book)->where('level', 1)->first()->uid;
  213. $category = $this->tagService->getTagsName($bookUid);
  214. $headings = [];
  215. $currChapterTitle = '';
  216. $commentaryId = '';
  217. $currSession = [];
  218. foreach ($paragraphs as $key => $para) {
  219. $total++;
  220. if ($para->level < 8) {
  221. $currChapterTitle = $para->toc;
  222. }
  223. if ($para->class === 'nikaya') {
  224. $nikaya = $para->text;
  225. }
  226. $paraContent = $this->searchPaliDataService
  227. ->getParaContent($para['book'], $para['paragraph']);
  228. if (!empty($commentaryId)) {
  229. $currSession[] = $paraContent;
  230. }
  231. if (isset($paraContent['commentary'])) {
  232. if (!empty($commentaryId)) {
  233. //保存 session
  234. $this->indexPaliSession($para->toArray(), $currSession, $currChapterTitle, $commentaryId);
  235. $currSession = [];
  236. }
  237. $commentaryId = $paraContent['commentary'];
  238. }
  239. $this->indexPaliParagraph($para->toArray(), $paraContent, $commentaryId, $category);
  240. $this->info("{$para['book']}-[{$para['paragraph']}]-[{$commentaryId}]");
  241. usleep(10000);
  242. }
  243. $this->info("Successfully indexed $total paragraphs for book: $book");
  244. Log::info("Indexed $total paragraphs for book: $book");
  245. return 0;
  246. }
  247. /**
  248. * Index Pali suttas for a given book (placeholder for future implementation).
  249. *
  250. * @param int $book
  251. * @return int
  252. */
  253. protected function indexPaliSutta($book)
  254. {
  255. $this->warn("Sutta indexing is not yet implemented for book: $book");
  256. Log::warning("Sutta indexing not implemented for book: $book");
  257. return 1;
  258. }
  259. /**
  260. * Index Pali sentences for a given book (placeholder for future implementation).
  261. *
  262. * @param int $book
  263. * @return int
  264. */
  265. protected function indexPaliSentences($book)
  266. {
  267. $this->warn("Sentence indexing is not yet implemented for book: $book");
  268. Log::warning("Sentence indexing not implemented for book: $book");
  269. return 1;
  270. }
  271. }