ExportMobileHeading.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Models\PaliText;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. /**
  7. * 导出移动端离线目录库(SQLite)。
  8. *
  9. * 替代 wikipali-mobile 仓库里的 src/data/tipitaka_heading.json(5.5MB,
  10. * 全量载入内存)。导出 pali_texts 全部段落(不只是章节行,下载功能需要
  11. * 非章节段落的字符数),除原有目录字段外额外带上:
  12. * - length:段落字符数(源表列名 `lenght` 为拼写错误,导出时纠正)
  13. *
  14. * - tags:pali_texts.uid 经 tag_maps / tags 取到的标签名,逗号分隔
  15. * - related_paragraphs:cs_para + book_name,用于由根本章节定位
  16. * 对应的义注 / 复注章节起始位置
  17. */
  18. class ExportMobileHeading extends Command
  19. {
  20. protected $signature = 'export:mobile.heading
  21. {--out= : 输出文件路径,默认 storage/app/public/export/mobile/tipitaka-heading-<date>.db3}
  22. {--copy-to= : 导出后额外复制一份到该路径(例如移动端仓库的 assets/db/tipitaka.db3)}';
  23. protected $description = '导出移动端离线目录 SQLite(含 tags 与义注复注关联段落)';
  24. public function handle(): int
  25. {
  26. $out = $this->option('out');
  27. if (! $out) {
  28. $dir = storage_path('app/public/export/mobile');
  29. if (! is_dir($dir)) {
  30. mkdir($dir, 0775, true);
  31. }
  32. $out = $dir.'/tipitaka-heading-'.date('Y-m-d').'.db3';
  33. }
  34. if (file_exists($out)) {
  35. unlink($out);
  36. }
  37. $dbh = new \PDO('sqlite:'.$out, '', '', [\PDO::ATTR_PERSISTENT => true]);
  38. $dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  39. $this->createSchema($dbh);
  40. $texts = $this->exportPaliTexts($dbh);
  41. $related = $this->exportRelated($dbh);
  42. $this->writeMeta($dbh, [
  43. 'generated_at' => date('c'),
  44. 'source' => config('app.url', ''),
  45. 'pali_text_rows' => (string) $texts,
  46. 'related_rows' => (string) $related,
  47. ]);
  48. // 建索引放在插入之后,避免边插边维护索引
  49. $this->createIndexes($dbh);
  50. $dbh->exec('VACUUM');
  51. $dbh = null;
  52. $this->newLine();
  53. $this->info(sprintf(
  54. '导出完成:%s(%s,pali_text %d 行,related %d 行)',
  55. $out,
  56. $this->humanSize(filesize($out)),
  57. $texts,
  58. $related
  59. ));
  60. $copyTo = $this->option('copy-to');
  61. if ($copyTo) {
  62. $dir = dirname($copyTo);
  63. if (! is_dir($dir)) {
  64. mkdir($dir, 0775, true);
  65. }
  66. copy($out, $copyTo);
  67. $this->info('已复制到:'.$copyTo);
  68. }
  69. return 0;
  70. }
  71. private function createSchema(\PDO $dbh): void
  72. {
  73. // 全量段落(不只是章节标题行):下载功能需要非章节段落的字符数
  74. $dbh->exec('CREATE TABLE pali_text (
  75. book INTEGER NOT NULL,
  76. paragraph INTEGER NOT NULL,
  77. level INTEGER NOT NULL,
  78. toc TEXT,
  79. length INTEGER,
  80. chapter_len INTEGER,
  81. chapter_strlen INTEGER,
  82. parent INTEGER,
  83. uid TEXT,
  84. tags TEXT,
  85. PRIMARY KEY (book, paragraph)
  86. )');
  87. // 一个根本章节可关联多部义注 / 复注,故独立成表
  88. $dbh->exec('CREATE TABLE related_paragraph (
  89. book INTEGER NOT NULL,
  90. para INTEGER NOT NULL,
  91. book_id INTEGER,
  92. cs_para INTEGER,
  93. book_name TEXT
  94. )');
  95. $dbh->exec('CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)');
  96. }
  97. private function createIndexes(\PDO $dbh): void
  98. {
  99. $dbh->exec('CREATE INDEX idx_pali_text_book_level ON pali_text (book, level)');
  100. $dbh->exec('CREATE INDEX idx_pali_text_parent ON pali_text (book, parent)');
  101. $dbh->exec('CREATE INDEX idx_related_src ON related_paragraph (book, para)');
  102. $dbh->exec('CREATE INDEX idx_related_dst ON related_paragraph (book_name, cs_para)');
  103. }
  104. private function exportPaliTexts(\PDO $dbh): int
  105. {
  106. $total = PaliText::count();
  107. $this->line("导出 pali_text(全量段落):{$total} 行");
  108. $bar = $this->output->createProgressBar($total);
  109. $bar->setRedrawFrequency(5000);
  110. // uid -> 标签名列表。tag_maps.table_name 对 pali_texts 使用复数表名。
  111. $tagsByUid = $this->loadTags();
  112. $stmt = $dbh->prepare('INSERT INTO pali_text
  113. (book, paragraph, level, toc, length, chapter_len, chapter_strlen, parent, uid, tags)
  114. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
  115. $dbh->beginTransaction();
  116. $n = 0;
  117. foreach (
  118. PaliText::select(['uid', 'book', 'paragraph', 'level', 'toc',
  119. 'lenght', 'chapter_len', 'chapter_strlen', 'parent'])
  120. ->orderBy('book')
  121. ->orderBy('paragraph')
  122. ->cursor() as $row
  123. ) {
  124. $stmt->execute([
  125. $row->book,
  126. $row->paragraph,
  127. $row->level,
  128. $row->toc !== '' ? $row->toc : null,
  129. // 源表列名 `lenght` 是拼写错误,导出时纠正为 `length`
  130. $row->lenght,
  131. $row->chapter_len,
  132. $row->chapter_strlen,
  133. $row->parent,
  134. $row->uid,
  135. isset($tagsByUid[$row->uid]) ? implode(',', $tagsByUid[$row->uid]) : null,
  136. ]);
  137. $n++;
  138. $bar->advance();
  139. }
  140. $dbh->commit();
  141. $bar->finish();
  142. $this->newLine();
  143. return $n;
  144. }
  145. /** @return array<string, string[]> uid => tag names */
  146. private function loadTags(): array
  147. {
  148. $this->line('载入 tag_maps / tags …');
  149. $out = [];
  150. DB::table('tag_maps')
  151. ->join('tags', 'tags.id', '=', 'tag_maps.tag_id')
  152. ->where('tag_maps.table_name', 'pali_texts')
  153. ->select(['tag_maps.anchor_id', 'tags.name'])
  154. ->orderBy('tag_maps.anchor_id')
  155. ->chunk(20000, function ($rows) use (&$out) {
  156. foreach ($rows as $r) {
  157. $out[$r->anchor_id][] = $r->name;
  158. }
  159. });
  160. $this->line(' 标签锚点:'.count($out));
  161. return $out;
  162. }
  163. /**
  164. * 关联段落:由根本章节 (book, para) 找到对应义注 / 复注的 (book_name, cs_para)。
  165. *
  166. * `book_name` 为空表示该段落没有对应的注释书,导出为 NULL。
  167. */
  168. private function exportRelated(\PDO $dbh): int
  169. {
  170. $query = DB::table('related_paragraphs')
  171. ->select(['book', 'para', 'book_id', 'cs_para', 'book_name']);
  172. $total = $query->count();
  173. $this->line("导出 related_paragraph:{$total} 行");
  174. $bar = $this->output->createProgressBar($total);
  175. $bar->setRedrawFrequency(5000);
  176. $stmt = $dbh->prepare('INSERT INTO related_paragraph
  177. (book, para, book_id, cs_para, book_name) VALUES (?, ?, ?, ?, ?)');
  178. $dbh->beginTransaction();
  179. $n = 0;
  180. foreach ($query->orderBy('book')->orderBy('para')->cursor() as $row) {
  181. $stmt->execute([
  182. $row->book,
  183. $row->para,
  184. $row->book_id,
  185. $row->cs_para,
  186. $row->book_name !== '' ? $row->book_name : null,
  187. ]);
  188. $n++;
  189. $bar->advance();
  190. }
  191. $dbh->commit();
  192. $bar->finish();
  193. $this->newLine();
  194. return $n;
  195. }
  196. private function writeMeta(\PDO $dbh, array $meta): void
  197. {
  198. $stmt = $dbh->prepare('INSERT INTO meta (key, value) VALUES (?, ?)');
  199. foreach ($meta as $k => $v) {
  200. $stmt->execute([$k, $v]);
  201. }
  202. }
  203. private function humanSize(int $bytes): string
  204. {
  205. $units = ['B', 'KB', 'MB', 'GB'];
  206. $i = 0;
  207. while ($bytes >= 1024 && $i < count($units) - 1) {
  208. $bytes /= 1024;
  209. $i++;
  210. }
  211. return round($bytes, 1).' '.$units[$i];
  212. }
  213. }