ExportMobileHeading.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\BookTitle;
  4. use App\Models\PaliText;
  5. use App\Models\RelatedParagraph;
  6. use Illuminate\Console\Command;
  7. /**
  8. * 导出移动端离线目录库(SQLite)。
  9. *
  10. * 替代 wikipali-mobile 仓库里的 src/data/tipitaka_heading.json(5.5MB,
  11. * 全量载入内存)。导出 pali_texts 全部段落(不只是章节行,下载功能需要
  12. * 非章节段落的字符数)。输出两张表:
  13. *
  14. * - pali_text:全量段落,除原有目录字段外额外带上
  15. * - length:段落字符数(源表列名 `lenght` 为拼写错误,导出时纠正)
  16. * - cs_para + book_name:来自 related_paragraphs,用于由段落定位对应的
  17. * 义注 / 复注章节起始位置
  18. * - works:作品清单,来自 book_titles(一行 = 一部作品,起点段 (book, paragraph),
  19. * 多为 level=1,少数是 level=2,如书 209 Vajirabuddhi-ṭīkā 拆成的各篇)。
  20. * tags 只挂在作品上:作品起点段的 pali_texts.uid 经 tag_maps / tags 取到的
  21. * 标签名,逗号分隔。移动端靠它判断注释层次。
  22. */
  23. class ExportMobileHeading extends Command
  24. {
  25. protected $signature = 'export:mobile.heading
  26. {--out= : 输出文件路径,默认 storage/app/public/export/mobile/tipitaka-heading-<date>.db3}
  27. {--copy-to= : 导出后额外复制一份到该路径(例如移动端仓库的 assets/db/tipitaka.db3)}';
  28. protected $description = '导出移动端离线目录 SQLite(段落 + 作品表 works,含 tags 与义注复注关联段落)';
  29. public function handle(): int
  30. {
  31. $out = $this->option('out');
  32. if (! $out) {
  33. $dir = storage_path('app/public/export/mobile');
  34. if (! is_dir($dir)) {
  35. mkdir($dir, 0775, true);
  36. }
  37. $out = $dir.'/tipitaka-heading-'.date('Y-m-d').'.db3';
  38. }
  39. if (file_exists($out)) {
  40. unlink($out);
  41. }
  42. $dbh = new \PDO('sqlite:'.$out, '', '', [\PDO::ATTR_PERSISTENT => true]);
  43. $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  44. $this->createSchema($dbh);
  45. $texts = $this->exportPaliTexts($dbh);
  46. $works = $this->exportWorks($dbh);
  47. $this->writeMeta($dbh, [
  48. 'generated_at' => date('c'),
  49. 'source' => config('app.url', ''),
  50. 'pali_text_rows' => (string) $texts,
  51. 'works_rows' => (string) $works,
  52. ]);
  53. // 建索引放在插入之后,避免边插边维护索引
  54. $this->createIndexes($dbh);
  55. $dbh->exec('VACUUM');
  56. $dbh = null;
  57. $this->newLine();
  58. $this->info(sprintf(
  59. '导出完成:%s(%s,pali_text %d 行,works %d 行)',
  60. $out,
  61. $this->humanSize(filesize($out)),
  62. $texts,
  63. $works
  64. ));
  65. $copyTo = $this->option('copy-to');
  66. if ($copyTo) {
  67. $dir = dirname($copyTo);
  68. if (! is_dir($dir)) {
  69. mkdir($dir, 0775, true);
  70. }
  71. copy($out, $copyTo);
  72. $this->info('已复制到:'.$copyTo);
  73. }
  74. return 0;
  75. }
  76. private function createSchema(\PDO $dbh): void
  77. {
  78. // 全量段落(不只是章节标题行):下载功能需要非章节段落的字符数。
  79. // 关联注释书(cs_para / book_name)已合并进本表 —— 每个段落至多对应
  80. // 一部注释书,无对应时为 NULL。
  81. $dbh->exec('CREATE TABLE pali_text (
  82. book INTEGER NOT NULL,
  83. paragraph INTEGER NOT NULL,
  84. level INTEGER NOT NULL,
  85. toc TEXT,
  86. length INTEGER,
  87. chapter_len INTEGER,
  88. chapter_strlen INTEGER,
  89. parent INTEGER,
  90. cs_para INTEGER,
  91. book_name TEXT,
  92. PRIMARY KEY (book, paragraph)
  93. )');
  94. // 作品:book_titles 一行一部。作品的段落范围 = [paragraph, 同 book 下一部
  95. // 作品的 paragraph - 1],客户端按此推算,不另存。
  96. $dbh->exec('CREATE TABLE works (
  97. sn INTEGER PRIMARY KEY,
  98. book INTEGER NOT NULL,
  99. paragraph INTEGER NOT NULL,
  100. level INTEGER,
  101. title TEXT,
  102. toc TEXT,
  103. tags TEXT
  104. )');
  105. $dbh->exec('CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)');
  106. }
  107. private function createIndexes(\PDO $dbh): void
  108. {
  109. $dbh->exec('CREATE INDEX idx_pali_text_book_level ON pali_text (book, level)');
  110. $dbh->exec('CREATE INDEX idx_pali_text_parent ON pali_text (book, parent)');
  111. $dbh->exec('CREATE INDEX idx_pali_text_related ON pali_text (book_name, cs_para)');
  112. $dbh->exec('CREATE UNIQUE INDEX idx_works_book_para ON works (book, paragraph)');
  113. }
  114. private function exportPaliTexts(\PDO $dbh): int
  115. {
  116. $total = PaliText::count();
  117. $this->line("导出 pali_text(全量段落):{$total} 行");
  118. $bar = $this->output->createProgressBar($total);
  119. $bar->setRedrawFrequency(5000);
  120. $related = $this->loadRelated();
  121. $stmt = $dbh->prepare('INSERT INTO pali_text
  122. (book, paragraph, level, toc, length, chapter_len, chapter_strlen,
  123. parent, cs_para, book_name)
  124. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
  125. $dbh->beginTransaction();
  126. $n = 0;
  127. foreach (
  128. PaliText::select(['book', 'paragraph', 'level', 'toc',
  129. 'lenght', 'chapter_len', 'chapter_strlen', 'parent'])
  130. ->orderBy('book')
  131. ->orderBy('paragraph')
  132. ->cursor() as $row
  133. ) {
  134. $rel = $related[$row->book.'-'.$row->paragraph] ?? null;
  135. $stmt->execute([
  136. $row->book,
  137. $row->paragraph,
  138. $row->level,
  139. $row->toc !== '' ? $row->toc : null,
  140. // 源表列名 `lenght` 是拼写错误,导出时纠正为 `length`
  141. $row->lenght,
  142. $row->chapter_len,
  143. $row->chapter_strlen,
  144. $row->parent,
  145. $rel[0] ?? null,
  146. $rel[1] ?? null,
  147. ]);
  148. $n++;
  149. $bar->advance();
  150. }
  151. $dbh->commit();
  152. $bar->finish();
  153. $this->newLine();
  154. return $n;
  155. }
  156. /**
  157. * 关联注释书:由段落 (book, para) 找到对应义注 / 复注的起始位置。
  158. *
  159. * related_paragraphs 中同一段落会有多行,映射到一段连续的 cs_para 区间,
  160. * 但 book_name 唯一,因此这里取 min(cs_para) 作为起始位置合并成一行。
  161. * book_name 为空或 cs_para 为 0 表示该段落没有对应段落,直接跳过(结果列留 NULL)。
  162. * 0 不能照抄:mobile 只把 NULL 当「无对应」,0 会被当成坐标去配同名所有 0 号段落
  163. * (related_paragraphs 重建后,复注自己的序言、标题段等都是 0)。
  164. *
  165. * @return array<string, array{0:int,1:string}> "book-para" => [cs_para, book_name]
  166. */
  167. private function loadRelated(): array
  168. {
  169. $this->line('载入 related_paragraphs …');
  170. $out = [];
  171. RelatedParagraph::query()
  172. ->selectRaw('book, para, book_name, min(cs_para) as cs_para')
  173. ->whereNotNull('book_name')
  174. ->where('book_name', '<>', '')
  175. ->where('cs_para', '>', 0)
  176. ->groupBy('book', 'para', 'book_name')
  177. ->orderBy('book')
  178. ->orderBy('para')
  179. ->chunk(50000, function ($rows) use (&$out) {
  180. foreach ($rows as $r) {
  181. $out[$r->book.'-'.$r->para] = [(int) $r->cs_para, $r->book_name];
  182. }
  183. });
  184. $this->line(' 有注释书的段落:'.count($out));
  185. return $out;
  186. }
  187. /**
  188. * 作品表:book_titles 一行一部,tags 取作品起点段(pali_texts 同 book/paragraph
  189. * 那一行)的 tag_maps → tags。按 sn 排序;同 (book, paragraph) 重复的只留第一条。
  190. */
  191. private function exportWorks(\PDO $dbh): int
  192. {
  193. $this->line('导出 works(book_titles)…');
  194. $titles = BookTitle::orderBy('sn')->get(['sn', 'book', 'paragraph', 'title']);
  195. $stmt = $dbh->prepare('INSERT INTO works (sn, book, paragraph, level, title, toc, tags)
  196. VALUES (?, ?, ?, ?, ?, ?, ?)');
  197. $dbh->beginTransaction();
  198. $seen = [];
  199. $n = 0;
  200. foreach ($titles as $bt) {
  201. $key = $bt->book.'-'.$bt->paragraph;
  202. if (isset($seen[$key])) {
  203. $this->warn(" book_titles 重复:{$key}(sn={$bt->sn}),跳过");
  204. continue;
  205. }
  206. $seen[$key] = true;
  207. $text = PaliText::where('book', $bt->book)
  208. ->where('paragraph', $bt->paragraph)
  209. ->with(['tagMaps' => fn ($q) => $q->where('table_name', 'pali_texts'), 'tagMaps.tags'])
  210. ->first(['uid', 'level', 'toc']);
  211. if (! $text) {
  212. $this->warn(" pali_texts 找不到作品起点段:{$key}(sn={$bt->sn})");
  213. }
  214. $tags = $text
  215. ? $text->tagMaps->map(fn ($m) => $m->tags?->name)->filter()->unique()->sort()->values()->all()
  216. : [];
  217. $stmt->execute([
  218. $bt->sn,
  219. $bt->book,
  220. $bt->paragraph,
  221. $text?->level,
  222. $bt->title,
  223. $text && $text->toc !== '' ? $text->toc : null,
  224. $tags ? implode(',', $tags) : null,
  225. ]);
  226. $n++;
  227. }
  228. $dbh->commit();
  229. $this->line(" 作品:{$n}");
  230. return $n;
  231. }
  232. private function writeMeta(\PDO $dbh, array $meta): void
  233. {
  234. $stmt = $dbh->prepare('INSERT INTO meta (key, value) VALUES (?, ?)');
  235. foreach ($meta as $k => $v) {
  236. $stmt->execute([$k, $v]);
  237. }
  238. }
  239. private function humanSize(int $bytes): string
  240. {
  241. $units = ['B', 'KB', 'MB', 'GB'];
  242. $i = 0;
  243. while ($bytes >= 1024 && $i < count($units) - 1) {
  244. $bytes /= 1024;
  245. $i++;
  246. }
  247. return round($bytes, 1).' '.$units[$i];
  248. }
  249. }