book-text-util 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -59,6 +59,11 @@ const { items, segments } = await compareWhole({ cells, md, file: '001', label:
59
59
  - `compareChapter`:按卷分段(册↔卷对应);`runCompare`:连取数一起做(传 `transport`,不给 `isVariant` 时按浏览器环境取 `/compare/glyph-variants.json`,Node 请自己传)。
60
60
  - **异体字组**:给了 `isVariant` 时,`diffChars` 按「异体=同字」对齐,逐字互为异体的等长一段单独成一处(`hunk.variant`,类别 glyph),不再和旁边真正的用字不同粘成一条 word。判定只认表里的直接配对,不做传递(葢≈蓋、蓋≈盖 不推出 葢≈盖,避免 干/乾/幹 之类并成一组)。
61
61
  - 异体字判定用 open-guji-cv 的 `edges.tsv` 抽出的表(`{ pairs: "葢蓋\n畧略…" }`)。
62
+ - **异体字表怎么生成**(0.1.4 起在本包):`book-text-util variants --edges <open-guji-cv/config/hanzi/core/edges.tsv> [--mode collate|trusted|open] --out glyph-variants.json`,或在代码里 `buildVariantTable(edgesTsv, { mode, toSimplified })`。
63
+ - `trusted`/`open`:与网站原 `scripts/build-glyph-variants.mjs` 一样:variant/variant_partial/simp/z 边,来源限可信(open=Unihan、本项目、yi-bai;trusted 再加 yitizi、twedu、dypytz、hydzd、cjkvi-simplified),有 distinct 或 borrow(通假)边的不算。
64
+ - `collate`(默认,2026-11-14 殿本第1–5册参校查漏用、用户认可):在 trusted 上再加三条——① Unihan 语义/Z 异体或教育部异体字字典认定的,压过通假边(辨/辯、奕/弈、筭/算),distinct 仍否决;② 两字有一个是扩展区字(扩展 A 或 BMP 以外)时,任何来源的 variant 边都算(𠉀/候、𭧂/暴);常用字之间只靠宽松来源的不算(令/命、壁/璧、宇/字 仍是「用字不同」);③ 转简后同形的字对另放 `simp` 栏(範/范、乾/幹、閒/閑),`buildVariantTest(table, { simp: false })` 可以不并——对照本是简繁转换来的(维基文库)就该并。
65
+ - 分类另有两条对照本整理痕迹算 `struct`:底本条目起首的「一」被换成序号(一→十七,前一字是 卷/第/年 等的不算)、对照本写「無法顯示」占位。
66
+ - 第1–5册 911 处非异体差异上,collate 与人工核过的分类 910 处一致。
62
67
  - 其余:`diffChars`、`classify`、`wikiChars`/`chapterChars`、`parseCmp`/`formatCmp`(`?cmp=` 链接)。
63
68
  - 界面相关(标记装饰 `decorate`、偏好存储 `prefs`、React 钩子)留在网站,不在本包。
64
69
 
package/dist/cli.js CHANGED
@@ -167,9 +167,9 @@ function cmpKey(a, b) {
167
167
  for (let i = 1; i < 5; i++) if (a[i] !== b[i]) return a[i] ? 1 : -1;
168
168
  return 0;
169
169
  }
170
- function resolveOffsets(pos, items, key) {
170
+ function resolveOffsets(pos, items, key2) {
171
171
  return items.map((it, i) => {
172
- const a = key(it);
172
+ const a = key2(it);
173
173
  const off = a === void 0 ? void 0 : pos.get(a);
174
174
  if (off === void 0) throw new GujiFormatError(`\u7B2C ${i} \u6761\u7684\u683C\u4F4D ${String(a)} \u4E0D\u5728 char \u91CC`);
175
175
  return off;
@@ -312,21 +312,21 @@ function availableFormats(ch) {
312
312
  function safeFile(v) {
313
313
  return typeof v === "string" && /^[\w.-]+$/.test(v) ? v : null;
314
314
  }
315
- async function getJson(source, id, key, file) {
315
+ async function getJson(source, id, key2, file) {
316
316
  try {
317
- return await source.getTextFile(id, key, file) ?? null;
317
+ return await source.getTextFile(id, key2, file) ?? null;
318
318
  } catch {
319
319
  return null;
320
320
  }
321
321
  }
322
- async function getPreferred(source, id, key, slim, original) {
322
+ async function getPreferred(source, id, key2, slim, original) {
323
323
  const s = safeFile(slim);
324
324
  if (s) {
325
- const v = await getJson(source, id, key, s);
325
+ const v = await getJson(source, id, key2, s);
326
326
  if (v != null) return v;
327
327
  }
328
328
  const o = safeFile(original);
329
- return o ? getJson(source, id, key, o) : null;
329
+ return o ? getJson(source, id, key2, o) : null;
330
330
  }
331
331
  function glyphConverter(glyph2, converters) {
332
332
  if (glyph2 === "original") return (s) => s;
@@ -335,14 +335,14 @@ function glyphConverter(glyph2, converters) {
335
335
  }
336
336
  async function buildExport(req, source, converters) {
337
337
  const ch = req.chapter;
338
- const { id, versionKey: key } = req;
338
+ const { id, versionKey: key2 } = req;
339
339
  const needPunct = req.format !== "lines";
340
340
  const [char, punct, entity, fig] = await Promise.all([
341
- getPreferred(source, id, key, ch.reader_char_file, ch.char_file),
342
- needPunct ? getPreferred(source, id, key, ch.reader_punct_file, ch.punct_file) : null,
341
+ getPreferred(source, id, key2, ch.reader_char_file, ch.char_file),
342
+ needPunct ? getPreferred(source, id, key2, ch.reader_punct_file, ch.punct_file) : null,
343
343
  // 专名层取原文件:瘦身副本有 entity_id 时去掉了 href,而下载要原样写仓里的 book-index:// 链接
344
- needPunct && safeFile(ch.entity_file) ? getJson(source, id, key, ch.entity_file) : null,
345
- safeFile(ch.fig_file) ? getJson(source, id, key, ch.fig_file) : null
344
+ needPunct && safeFile(ch.entity_file) ? getJson(source, id, key2, ch.entity_file) : null,
345
+ safeFile(ch.fig_file) ? getJson(source, id, key2, ch.fig_file) : null
346
346
  ]);
347
347
  if (!char) throw new Error("\u672C\u518A\u6587\u5B57\u53D6\u4E0D\u5230");
348
348
  if (needPunct && !punct) throw new Error("\u672C\u518A\u6A19\u9EDE\u53D6\u4E0D\u5230");
@@ -441,8 +441,8 @@ import { readFile, writeFile, mkdir } from "fs/promises";
441
441
  import { join } from "path";
442
442
  function dirSource(root, layout = "flat") {
443
443
  return {
444
- async getTextFile(id, key, file) {
445
- const p = layout === "flat" ? join(root, file) : join(root, id, key, file);
444
+ async getTextFile(id, key2, file) {
445
+ const p = layout === "flat" ? join(root, file) : join(root, id, key2, file);
446
446
  try {
447
447
  return JSON.parse(await readFile(p, "utf-8"));
448
448
  } catch {
@@ -459,9 +459,15 @@ async function writeExport(dir, r) {
459
459
  }
460
460
 
461
461
  // src/compare/classify.ts
462
+ var NUMERAL = /^[一二三四五六七八九十百]+$/;
463
+ var PLACEHOLDER = /無法顯示|无法显示/;
464
+ var NUM_CTX = /* @__PURE__ */ new Set([..."\u5377\u7B2C\u5E74\u6708\u65E5\u6B72\u5C81\u4E4B\u5341\u767E\u5343\u842C\u4E07\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D"]);
462
465
  function classify(h, base, wiki, opts) {
463
466
  if (h.i1 === h.i2) return "add";
464
467
  if (h.j1 === h.j2) return opts.structEnd !== void 0 && h.i2 <= opts.structEnd ? "struct" : "omit";
468
+ const b = base.slice(h.i1, h.i2).join("");
469
+ const r = wiki.slice(h.j1, h.j2).join("");
470
+ if (b === "\u4E00" && r !== b && NUMERAL.test(r) && !NUM_CTX.has(base[h.i1 - 1] ?? "") || PLACEHOLDER.test(r)) return "struct";
465
471
  const len = h.i2 - h.i1;
466
472
  if (len === h.j2 - h.j1 && opts.isVariant) {
467
473
  let all = true;
@@ -607,24 +613,54 @@ function diffRaw(a, b, maxD, same) {
607
613
  }
608
614
 
609
615
  // src/compare/volumes.ts
616
+ var DIGIT = { "\u3007": 0, \u96F6: 0, \u4E00: 1, \u4E8C: 2, \u4E09: 3, \u56DB: 4, \u4E94: 5, \u516D: 6, \u4E03: 7, \u516B: 8, \u4E5D: 9 };
617
+ function cnNumber(s) {
618
+ if (!s) return null;
619
+ if (/^\d+$/.test(s)) return Number(s);
620
+ if (![...s].every((ch) => ch in DIGIT || ch === "\u5341" || ch === "\u767E")) return null;
621
+ if (![...s].some((ch) => ch === "\u5341" || ch === "\u767E")) {
622
+ let n = 0;
623
+ for (const ch of s) n = n * 10 + DIGIT[ch];
624
+ return n;
625
+ }
626
+ let total = 0;
627
+ let cur = 0;
628
+ for (const ch of s) {
629
+ if (ch === "\u767E") {
630
+ total += (cur || 1) * 100;
631
+ cur = 0;
632
+ } else if (ch === "\u5341") {
633
+ total += (cur || 1) * 10;
634
+ cur = 0;
635
+ } else cur = DIGIT[ch];
636
+ }
637
+ return total + cur;
638
+ }
639
+ function volumeNo(label) {
640
+ const m = /^卷([\d〇零一二三四五六七八九十百]+)/.exec(label.trim());
641
+ return m ? cnNumber(m[1]) : null;
642
+ }
610
643
  function wikiFileOf(no, chapters) {
611
644
  const want = `\u5377${String(no).padStart(3, "0")}`;
612
- return chapters.find((c) => c.title.trim() === want)?.file ?? null;
645
+ const exact = chapters.find((c) => c.title.trim() === want);
646
+ if (exact) return exact.file;
647
+ return chapters.find((c) => volumeNo(c.title) === no)?.file ?? null;
613
648
  }
614
649
 
615
650
  // src/compare/wikitext.ts
616
651
  var STATUS_LINE = /^(有标点|无标点|已修正|好$|簡繁|简繁)/;
617
652
  var VOLUME_LINE = /^#+\s*卷[\d〇零一二三四五六七八九十百]+\s*$/;
618
653
  var STRIP = /[\p{P}\p{Z}\s]/gu;
654
+ var ZI = /:zi\[[^\]\n]*\]/g;
655
+ var NOTE_MARK = /[<>|]/g;
619
656
  function wikiChars(md) {
620
657
  const lines = md.split("\n").map((s) => s.trim()).filter((s) => s && !VOLUME_LINE.test(s) && !STATUS_LINE.test(s)).map((s) => s.replace(/^#+\s*/, ""));
621
- return Array.from(lines.join("").replace(STRIP, ""));
658
+ return Array.from(lines.join("").replace(ZI, "\u25A1").replace(NOTE_MARK, "").replace(STRIP, ""));
622
659
  }
623
- var NOTE_MARK = /[<>|]/g;
624
660
  function chapterChars(md) {
625
661
  const lines = md.split("\n").map((s) => s.trim()).filter(Boolean);
626
662
  if (lines.length && /^#{1,2}\s/.test(lines[0])) lines.shift();
627
- return Array.from(lines.map((s) => s.replace(/^#+\s*/, "")).join("").replace(NOTE_MARK, "").replace(STRIP, ""));
663
+ return Array.from(lines.map((s) => s.replace(/^#+\s*/, "")).join("").replace(ZI, "\u25A1").replace(NOTE_MARK, "").replace(STRIP, ""));
628
664
  }
629
665
 
630
666
  // src/compare/compare.ts
@@ -667,16 +703,34 @@ function trimWikiToBase(base, wiki, start, end) {
667
703
  }
668
704
  return j0 < j1 ? [j0, j1] : [0, wiki.length];
669
705
  }
670
- async function compareSeg(input, seg, out, idStart, whole) {
706
+ async function compareSeg(input, seg, out, idStart, whole, range) {
671
707
  const res = { no: seg.no, label: seg.label, from: seg.from, to: seg.to, status: "ok", wikiFile: null };
672
- const file = whole ? whole.file : seg.no === null ? null : wikiFileOf(seg.no, input.wikiChapters);
673
- if (!file) return { ...res, status: "no-wiki" };
674
- res.wikiFile = file;
675
- const md = whole ? whole.md : await input.getWikiMd(file);
676
- if (md === null) return { ...res, status: "fetch-failed" };
708
+ let wiki;
709
+ if (whole) {
710
+ res.wikiFile = whole.file;
711
+ wiki = chapterChars(whole.md);
712
+ } else if (range) {
713
+ const files = [];
714
+ for (let n = range[0]; n <= range[1]; n++) {
715
+ const f = wikiFileOf(n, input.wikiChapters);
716
+ if (!f) return { ...res, wikiFile: files[0] ?? null, wikiFiles: files, status: "no-wiki" };
717
+ files.push(f);
718
+ }
719
+ res.wikiFile = files[0];
720
+ res.wikiFiles = files;
721
+ const mds = await Promise.all(files.map((f) => input.getWikiMd(f)));
722
+ if (mds.some((m) => m === null)) return { ...res, status: "fetch-failed" };
723
+ wiki = mds.flatMap((m) => wikiChars(m));
724
+ } else {
725
+ const file = seg.no === null ? null : wikiFileOf(seg.no, input.wikiChapters);
726
+ if (!file) return { ...res, status: "no-wiki" };
727
+ res.wikiFile = file;
728
+ const md = await input.getWikiMd(file);
729
+ if (md === null) return { ...res, status: "fetch-failed" };
730
+ wiki = wikiChars(md);
731
+ }
677
732
  const base = input.cells.slice(seg.from, seg.to).map((c) => c.c);
678
- let wiki = whole ? chapterChars(md) : wikiChars(md);
679
- if (!whole) {
733
+ if (!whole && !range) {
680
734
  const [j0, j1] = trimWikiToBase(base, wiki, seg.startsPartial, seg.endsPartial);
681
735
  wiki = wiki.slice(j0, j1);
682
736
  }
@@ -722,17 +776,103 @@ async function compareWhole(input) {
722
776
  }
723
777
 
724
778
  // src/compare/variants.ts
725
- function buildVariantTest(table) {
779
+ function buildVariantTest(table, opts = {}) {
726
780
  const set = /* @__PURE__ */ new Set();
727
- for (const line of table.pairs.split("\n")) {
728
- const cp = Array.from(line);
729
- if (cp.length !== 2) continue;
730
- set.add(cp[0] + cp[1]);
731
- set.add(cp[1] + cp[0]);
732
- }
781
+ const add = (text) => {
782
+ for (const line of text.split("\n")) {
783
+ const cp = Array.from(line);
784
+ if (cp.length !== 2) continue;
785
+ set.add(cp[0] + cp[1]);
786
+ set.add(cp[1] + cp[0]);
787
+ }
788
+ };
789
+ add(table.pairs);
790
+ if (table.simp && opts.simp !== false) add(table.simp);
733
791
  return (a, b) => set.has(a + b);
734
792
  }
735
793
 
794
+ // src/compare/variant-build.ts
795
+ var VARIANT_REL = /* @__PURE__ */ new Set(["variant", "variant_partial", "simp", "z"]);
796
+ var isOpen = (src) => src.startsWith("unihan") || src.startsWith("local:keben") || src.startsWith("yibai");
797
+ var TRUSTED_EXTRA = /* @__PURE__ */ new Set(["yitizi", "twedu", "dypytz", "hydzd", "cjkvi-simplified"]);
798
+ var isTrusted = (src) => isOpen(src) || TRUSTED_EXTRA.has(src);
799
+ var isStrong = (rel, src) => rel === "z" || src === "unihan:kSemanticVariant" || src === "unihan:kZVariant" || src === "twedu";
800
+ function isRareHan(ch) {
801
+ const cp = ch.codePointAt(0) ?? 0;
802
+ return cp > 65535 || cp >= 13312 && cp <= 19903;
803
+ }
804
+ var key = (a, b) => a < b ? a + b : b + a;
805
+ function buildVariantTable(edgesTsv, opts = {}) {
806
+ const mode = opts.mode ?? "collate";
807
+ const pickSrc = mode === "open" ? isOpen : isTrusted;
808
+ const yes = /* @__PURE__ */ new Set();
809
+ const strong = /* @__PURE__ */ new Set();
810
+ const loose = /* @__PURE__ */ new Set();
811
+ const no = /* @__PURE__ */ new Set();
812
+ const borrow = /* @__PURE__ */ new Set();
813
+ const used = /* @__PURE__ */ new Set();
814
+ const chars = /* @__PURE__ */ new Set();
815
+ for (const line of edgesTsv.split("\n")) {
816
+ if (!line) continue;
817
+ const [a, b, rel, , src = ""] = line.split(" ");
818
+ if (!a || !b || a === b || [...a].length !== 1 || [...b].length !== 1) continue;
819
+ const k = key(a, b);
820
+ chars.add(a);
821
+ chars.add(b);
822
+ if (rel === "distinct") no.add(k);
823
+ else if (rel === "borrow") borrow.add(k);
824
+ else if (VARIANT_REL.has(rel)) {
825
+ if (pickSrc(src)) {
826
+ yes.add(k);
827
+ used.add(src);
828
+ }
829
+ if (isStrong(rel, src)) strong.add(k);
830
+ if (rel !== "simp") loose.add(k);
831
+ }
832
+ }
833
+ const out = /* @__PURE__ */ new Set();
834
+ for (const k of yes) if (!no.has(k) && !borrow.has(k)) out.add(k);
835
+ let simp;
836
+ if (mode === "collate") {
837
+ for (const k of strong) if (!no.has(k)) out.add(k);
838
+ for (const k of loose) {
839
+ if (no.has(k)) continue;
840
+ const [a, b] = [...k];
841
+ if (isRareHan(a) || isRareHan(b)) out.add(k);
842
+ }
843
+ if (opts.toSimplified) {
844
+ const groups = /* @__PURE__ */ new Map();
845
+ for (let cp = 19968; cp <= 40959; cp++) chars.add(String.fromCodePoint(cp));
846
+ for (const c of chars) {
847
+ const s = opts.toSimplified(c);
848
+ if ([...s].length !== 1) continue;
849
+ const g = groups.get(s) ?? [];
850
+ g.push(c);
851
+ groups.set(s, g);
852
+ }
853
+ const sp = /* @__PURE__ */ new Set();
854
+ for (const [s, g] of groups) {
855
+ const all = g.includes(s) ? g : [...g, s];
856
+ if (all.length < 2 || all.length > 12) continue;
857
+ for (let i = 0; i < all.length; i++)
858
+ for (let j = i + 1; j < all.length; j++) {
859
+ const k = key(all[i], all[j]);
860
+ if (!no.has(k) && !out.has(k)) sp.add(k);
861
+ }
862
+ }
863
+ simp = [...sp].sort();
864
+ }
865
+ }
866
+ const table = {
867
+ version: opts.version ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
868
+ mode,
869
+ sources: [...used].sort(),
870
+ pairs: [...out].sort().join("\n")
871
+ };
872
+ if (simp) table.simp = simp.join("\n");
873
+ return table;
874
+ }
875
+
736
876
  // src/compare/report.ts
737
877
  var CAT_TITLE = {
738
878
  word: "\u7528\u5B57\u4E0D\u540C",
@@ -812,10 +952,14 @@ var HELP = `\u7528\u6CD5\uFF1A
812
952
  [--glyph original|traditional|simplified] [--title \u4E66\u540D] [--id \u6761\u76EEid] [--out \u76EE\u5F55]
813
953
  book-text-util compare --base <\u5E95\u672C.txt> --ref <\u5BF9\u7167\u672C.md> [--variants <glyph-variants.json>] [--json]
814
954
 
955
+ book-text-util variants --edges <open-guji-cv/config/hanzi/core/edges.tsv> [--mode collate|trusted|open] [--no-simp]
956
+ [--out glyph-variants.json]
957
+
815
958
  book-text-util report --base-root <\u7248\u672C\u76EE\u5F55> --ref-root <\u5BF9\u7167\u7248\u672C\u76EE\u5F55> --chapters 001-005 [--variants <glyph-variants.json>]
816
959
  [--title \u6807\u9898] [--base-label \u540D] [--ref-label \u540D] [--list word,add,omit,glyph] [--out \u62A5\u544A.md]
817
960
 
818
961
  export\uFF1A\u8BFB\u7248\u672C\u76EE\u5F55\u91CC\u7684 index.json \u4E0E <\u518C>.char.json \u7B49\uFF0C\u751F\u6210 guji-markdown\uFF1B--glyph \u975E original \u9700\u8981\u5B89\u88C5 opencc-js \u4E0E book-index-ui\u3002
962
+ variants\uFF1A\u751F\u6210\u5BF9\u6821\u7528\u7684\u5F02\u4F53\u5B57\u8868\uFF08\u5224\u6CD5\u89C1 src/compare/variant-build.ts\uFF1Bcollate \u7684\u7E41\u7B80\u540C\u5F62\u4E00\u680F\u8981 opencc-js\uFF09\u3002
819
963
  compare\uFF1A\u628A\u4E24\u4EFD\u6587\u672C\u53BB\u6807\u70B9\u540E\u505A\u5B57\u7EA7\u6BD4\u5BF9\uFF0C\u5217\u51FA\u6BCF\u5904\u5DEE\u5F02\u53CA\u5206\u7C7B\u3002`;
820
964
  function die(msg) {
821
965
  process.stderr.write(msg + "\n");
@@ -935,8 +1079,35 @@ async function cmdReport(argv) {
935
1079
  `);
936
1080
  } else process.stdout.write(md + "\n");
937
1081
  }
1082
+ async function cmdVariants(argv) {
1083
+ const { values: v } = parseArgs({
1084
+ args: argv,
1085
+ options: { edges: { type: "string" }, mode: { type: "string", default: "collate" }, "no-simp": { type: "boolean", default: false }, out: { type: "string", default: "glyph-variants.json" } }
1086
+ });
1087
+ if (!v.edges) die("\u9700\u8981 --edges\n\n" + HELP);
1088
+ const mode = v.mode;
1089
+ if (!["open", "trusted", "collate"].includes(mode)) die(`--mode \u53EA\u8BA4 collate|trusted|open\uFF0C\u6536\u5230 ${mode}`);
1090
+ let toSimplified;
1091
+ if (mode === "collate" && !v["no-simp"]) {
1092
+ try {
1093
+ const { Converter } = await import(
1094
+ /* @vite-ignore */
1095
+ "opencc-js/t2cn"
1096
+ );
1097
+ toSimplified = Converter({ from: "t", to: "cn" });
1098
+ } catch (e) {
1099
+ die(`\u7E41\u7B80\u540C\u5F62\u4E00\u680F\u9700\u8981 opencc-js\uFF08${e.message}\uFF09\uFF1B\u4E0D\u8981\u8FD9\u4E00\u680F\u5C31\u52A0 --no-simp`);
1100
+ }
1101
+ }
1102
+ const table = buildVariantTable(await readFile2(v.edges, "utf-8"), { mode, toSimplified });
1103
+ await writeFile2(v.out, JSON.stringify(table));
1104
+ const n = (s) => s ? s.split("\n").length : 0;
1105
+ process.stdout.write(`${n(table.pairs)} \u5BF9\u5F02\u4F53\u3001${n(table.simp)} \u5BF9\u7E41\u7B80\u540C\u5F62 \u2192 ${v.out}\uFF08mode ${mode}\uFF0C\u6765\u6E90 ${table.sources.join("\u3001")}\uFF09
1106
+ `);
1107
+ }
938
1108
  var [cmd, ...rest] = process.argv.slice(2);
939
1109
  if (cmd === "export") await cmdExport(rest);
940
1110
  else if (cmd === "compare") await cmdCompare(rest);
1111
+ else if (cmd === "variants") await cmdVariants(rest);
941
1112
  else if (cmd === "report") await cmdReport(rest);
942
1113
  else process.stdout.write(HELP + "\n");