2
0

RelatedParagraphSource.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. <?php
  2. namespace App\Services\RelatedParagraph;
  3. use App\Models\BookTitle;
  4. use App\Models\PaliText;
  5. use App\Models\Tag;
  6. use App\Models\TagMap;
  7. use App\Models\WbwTemplate;
  8. use RuntimeException;
  9. /**
  10. * 重建 related_paragraphs 的输入:数据库里的段落、锚点、书目,与
  11. * resources/data/related-paragraphs/ 下的 sn 书名表和每个 book 的补丁表。
  12. */
  13. class RelatedParagraphSource
  14. {
  15. /** 层级 tag 名 → 层级。一个 sn 若同时带几个,按此顺序取第一个。 */
  16. private const LAYER_TAGS = [
  17. 'mūla' => 'mula',
  18. 'aṭṭhakathā' => 'atthakatha',
  19. 'ṭīkā' => 'tika',
  20. 'mūlaṭīkā' => 'tika',
  21. 'anuṭīkā' => 'tika',
  22. 'abhinavaṭīkā' => 'tika',
  23. 'purāṇaṭīkā' => 'tika',
  24. 'añña' => 'anna',
  25. 'pāḷi' => 'mula',
  26. ];
  27. private ?array $snNames = null;
  28. public function __construct(private ?string $dataPath = null)
  29. {
  30. $this->dataPath ??= resource_path('data/related-paragraphs');
  31. }
  32. /**
  33. * @return list<int>
  34. */
  35. public function books(): array
  36. {
  37. return PaliText::query()->distinct()->orderBy('book')->pluck('book')->map(fn ($book) => (int) $book)->all();
  38. }
  39. /**
  40. * @return list<int>
  41. */
  42. public function paragraphs(int $book): array
  43. {
  44. return PaliText::query()->where('book', $book)->orderBy('paragraph')
  45. ->pluck('paragraph')->map(fn ($para) => (int) $para)->all();
  46. }
  47. /**
  48. * 该书的 .ctl. 锚点,页码标记已排除。
  49. *
  50. * @return array<int, list<string>>
  51. */
  52. public function markers(int $book): array
  53. {
  54. $markers = [];
  55. $rows = WbwTemplate::query()
  56. ->where('book', $book)
  57. ->where('type', '.ctl.')
  58. ->orderBy('paragraph')->orderBy('wid')
  59. ->get(['paragraph', 'word']);
  60. foreach ($rows as $row) {
  61. if (AnchorParser::parse($row->word)['kind'] !== AnchorParser::KIND_PAGE) {
  62. $markers[(int) $row->paragraph][] = $row->word;
  63. }
  64. }
  65. return $markers;
  66. }
  67. /**
  68. * @return array<int, int> 起始段落号 => sn
  69. */
  70. public function titles(int $book): array
  71. {
  72. return BookTitle::query()->where('book', $book)->orderBy('paragraph')
  73. ->pluck('sn', 'paragraph')->map(fn ($sn) => (int) $sn)->all();
  74. }
  75. /**
  76. * sn 书名表 book-names.csv(sn,book_name)。
  77. *
  78. * @return array<int, string>
  79. */
  80. public function snNames(): array
  81. {
  82. if ($this->snNames !== null) {
  83. return $this->snNames;
  84. }
  85. $this->snNames = [];
  86. foreach ($this->readCsv($this->dataPath.'/book-names.csv', ['sn', 'book_name']) as $line => $row) {
  87. if (! ctype_digit($row['sn']) || $row['book_name'] === '') {
  88. throw new RuntimeException("book-names.csv 第 {$line} 行格式不对");
  89. }
  90. $this->snNames[(int) $row['sn']] = $row['book_name'];
  91. }
  92. return $this->snNames;
  93. }
  94. /**
  95. * 补丁表 {book}.csv(para,book_name,begin,end)。没有文件就是没有补丁。
  96. *
  97. * @return array<int, array{book_name: string|null, begin: int, end: int}>
  98. */
  99. public function patch(int $book): array
  100. {
  101. $patch = [];
  102. $file = "{$this->dataPath}/{$book}.csv";
  103. foreach ($this->readCsv($file, ['para', 'book_name', 'begin', 'end']) as $line => $row) {
  104. foreach (['para', 'begin', 'end'] as $column) {
  105. if (! ctype_digit($row[$column])) {
  106. throw new RuntimeException("{$book}.csv 第 {$line} 行 {$column} 不是数字");
  107. }
  108. }
  109. if ((int) $row['end'] < (int) $row['begin']) {
  110. throw new RuntimeException("{$book}.csv 第 {$line} 行 end 小于 begin");
  111. }
  112. if (isset($patch[(int) $row['para']])) {
  113. throw new RuntimeException("{$book}.csv 第 {$line} 行段落 {$row['para']} 重复");
  114. }
  115. $patch[(int) $row['para']] = [
  116. 'book_name' => $row['book_name'] === '' ? null : $row['book_name'],
  117. 'begin' => (int) $row['begin'],
  118. 'end' => (int) $row['end'],
  119. ];
  120. }
  121. return $patch;
  122. }
  123. /**
  124. * 每个 sn 的层级(mula / atthakatha / tika / anna / unknown),取自其 level-1 段落的 tag。
  125. *
  126. * @return array<int, string>
  127. */
  128. public function layers(): array
  129. {
  130. $titles = BookTitle::query()->get(['book', 'paragraph', 'sn']);
  131. $uids = PaliText::query()->where('level', 1)->get(['book', 'paragraph', 'uid'])
  132. ->keyBy(fn ($text) => $text->book.'-'.$text->paragraph);
  133. $tagNames = Tag::query()->whereIn('name', array_keys(self::LAYER_TAGS))->pluck('name', 'id');
  134. $tagsByUid = [];
  135. foreach (TagMap::query()->whereIn('tag_id', $tagNames->keys())->get(['anchor_id', 'tag_id']) as $map) {
  136. $tagsByUid[$map->anchor_id][] = $tagNames[$map->tag_id];
  137. }
  138. $layers = [];
  139. foreach ($titles as $title) {
  140. $uid = $uids->get($title->book.'-'.$title->paragraph)?->uid;
  141. $names = $tagsByUid[$uid] ?? [];
  142. $layers[(int) $title->sn] = 'unknown';
  143. foreach (self::LAYER_TAGS as $tag => $layer) {
  144. if (in_array($tag, $names, true)) {
  145. $layers[(int) $title->sn] = $layer;
  146. break;
  147. }
  148. }
  149. }
  150. return $layers;
  151. }
  152. /**
  153. * @param list<string> $columns
  154. * @return array<int, array<string, string>> 行号 => 行
  155. */
  156. private function readCsv(string $file, array $columns): array
  157. {
  158. if (! is_file($file)) {
  159. return [];
  160. }
  161. $rows = [];
  162. $handle = fopen($file, 'r');
  163. $header = fgetcsv($handle, escape: '');
  164. if ($header !== $columns) {
  165. fclose($handle);
  166. throw new RuntimeException(basename($file).' 表头应为 '.implode(',', $columns));
  167. }
  168. $line = 1;
  169. while (($data = fgetcsv($handle, escape: '')) !== false) {
  170. $line++;
  171. if ($data === [null]) {
  172. continue;
  173. }
  174. if (count($data) !== count($columns)) {
  175. fclose($handle);
  176. throw new RuntimeException(basename($file)." 第 {$line} 行列数不对");
  177. }
  178. $rows[$line] = array_combine($columns, array_map('trim', $data));
  179. }
  180. fclose($handle);
  181. return $rows;
  182. }
  183. }