@wwkit/harness 1.0.46 → 1.0.47

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.
Files changed (117) hide show
  1. package/package.json +1 -1
  2. package/skills/pea/SKILL.md +14 -4
  3. package/skills/pea/references/tpl-prd/epic.md +7 -2
  4. package/skills/peago/SKILL.md +10 -2
  5. package/skills/peago/references/cleancode/languages/py-ut.md +88 -0
  6. package/skills/peago/references/cleancode/languages/py.md +222 -0
  7. package/skills/{blame-cleancode/references → peago/references/cleancode}/report_template.md +45 -12
  8. package/skills/peago/references/cleancode/rules-ut.md +133 -0
  9. package/skills/peago/references/cleancode/rules.md +477 -0
  10. package/skills/peago/references/cleancode/spec.md +204 -0
  11. package/skills/peago/references/lint/spec.md +160 -0
  12. package/skills/peago/references/test/languages/js.md +74 -0
  13. package/skills/peago/references/test/languages/py.md +68 -0
  14. package/skills/peago/references/test/spec.md +201 -0
  15. package/skills/peago/references/translate/scripts/check-paragraphs.js +71 -0
  16. package/skills/peago/references/translate/scripts/check-structure.js +118 -0
  17. package/skills/peago/references/translate/scripts/chunk-bilingual.js +123 -0
  18. package/skills/peago/references/translate/scripts/chunk-text.js +150 -0
  19. package/skills/peago/references/translate/scripts/clean-text.js +121 -0
  20. package/skills/peago/references/translate/scripts/count-terms.js +54 -0
  21. package/skills/peago/references/translate/scripts/extract-vision.js +267 -0
  22. package/skills/peago/references/translate/scripts/md-to-docx.js +381 -0
  23. package/skills/peago/references/translate/scripts/merge-format.js +110 -0
  24. package/skills/peago/references/translate/scripts/merge-pages.js +202 -0
  25. package/skills/peago/references/translate/scripts/merge-result.js +113 -0
  26. package/skills/peago/references/translate/scripts/verify-chunk.js +200 -0
  27. package/skills/peago/references/translate/spec.md +14 -6
  28. package/skills/better-class/SKILL.md +0 -48
  29. package/skills/better-class/references/planning_spec.md +0 -91
  30. package/skills/better-class/references/report-template.md +0 -65
  31. package/skills/better-class/references/sprint_for_eo.md +0 -83
  32. package/skills/better-class/references/sprint_for_report.md +0 -22
  33. package/skills/better-class/references/subagent-prompt.md +0 -47
  34. package/skills/better-class/references/workflow.md +0 -75
  35. package/skills/better-class/scripts/check-syntax.js +0 -112
  36. package/skills/better-class/scripts/check_input_vars.js +0 -52
  37. package/skills/better-class/scripts/init.js +0 -88
  38. package/skills/better-class/scripts/resolve_run_vars.js +0 -96
  39. package/skills/better-class/scripts/run-tests.js +0 -108
  40. package/skills/better-cleancode/SKILL.md +0 -157
  41. package/skills/better-ut/SKILL.md +0 -236
  42. package/skills/blame-class/SKILL.md +0 -78
  43. package/skills/blame-class/references/report_template.md +0 -98
  44. package/skills/blame-class/references/rules.md +0 -40
  45. package/skills/blame-cleancode/SKILL.md +0 -105
  46. package/skills/blame-cleancode/plan.md +0 -1408
  47. package/skills/blame-cleancode/references/rules.md +0 -630
  48. package/skills/blame-ut/SKILL.md +0 -113
  49. package/skills/blame-ut/references/report_template.md +0 -102
  50. package/skills/blame-ut/references/rules.md +0 -197
  51. package/skills/convert-files/SKILL.md +0 -37
  52. package/skills/convert-files/package.json +0 -11
  53. package/skills/convert-files/references/sprint_for_conversion.md +0 -17
  54. package/skills/convert-files/scripts/check_input_vars.js +0 -54
  55. package/skills/convert-files/scripts/convert.js +0 -331
  56. package/skills/convert-files/scripts/init.js +0 -75
  57. package/skills/convert-files/scripts/resolve_run_vars.js +0 -124
  58. package/skills/create-ppt/SKILL.md +0 -47
  59. package/skills/create-ppt/package.json +0 -9
  60. package/skills/create-ppt/references/ppt-styles.md +0 -287
  61. package/skills/create-ppt/references/sprint_for_ppt_generation.md +0 -81
  62. package/skills/create-ppt/references/sprint_for_source_discovery.md +0 -18
  63. package/skills/create-ppt/scripts/check_input_vars.js +0 -57
  64. package/skills/create-ppt/scripts/find-source-files.js +0 -98
  65. package/skills/create-ppt/scripts/init.js +0 -96
  66. package/skills/create-ppt/scripts/md-to-pptx.js +0 -579
  67. package/skills/create-ppt/scripts/resolve_run_vars.js +0 -91
  68. package/skills/jstest/SKILL.md +0 -561
  69. package/skills/jstest/references/case-create.md +0 -327
  70. package/skills/jstest/references/case-fix.md +0 -273
  71. package/skills/jstest/references/config.md +0 -148
  72. package/skills/jstest/references/coverage-analyze.md +0 -247
  73. package/skills/jstest/references/env-ensure.md +0 -210
  74. package/skills/jstest/references/execute.md +0 -168
  75. package/skills/jstest/references/sample.md +0 -166
  76. package/skills/jstest/references/scoring-rules.md +0 -75
  77. package/skills/jstest/references/suitability-check.md +0 -232
  78. package/skills/jstest/references/test-standards.md +0 -288
  79. package/skills/lint/SKILL.md +0 -440
  80. package/skills/lint/references/ai-fix.md +0 -138
  81. package/skills/lint/references/config-setup.md +0 -103
  82. package/skills/lint/references/config.md +0 -65
  83. package/skills/lint/references/env-ensure.md +0 -89
  84. package/skills/lint/references/language-detect.md +0 -76
  85. package/skills/lint/references/rules-analyze.md +0 -126
  86. package/skills/lint/references/suitability-check.md +0 -82
  87. package/skills/lint/references/tool-fix.md +0 -91
  88. package/skills/peago/references/extract/baseline.md +0 -17
  89. package/skills/peago/references/extract/spec.md +0 -117
  90. package/skills/pytest/SKILL.md +0 -556
  91. package/skills/pytest/references/case-create.md +0 -325
  92. package/skills/pytest/references/case-fix.md +0 -272
  93. package/skills/pytest/references/config.md +0 -145
  94. package/skills/pytest/references/coverage-analyze.md +0 -224
  95. package/skills/pytest/references/env-ensure.md +0 -196
  96. package/skills/pytest/references/execute.md +0 -153
  97. package/skills/pytest/references/sample.md +0 -160
  98. package/skills/pytest/references/scoring-rules.md +0 -57
  99. package/skills/pytest/references/suitability-check.md +0 -221
  100. package/skills/pytest/references/test-standards.md +0 -244
  101. /package/skills/{lint/references → peago/references/lint}/languages/js.md +0 -0
  102. /package/skills/{lint/references → peago/references/lint}/languages/py.md +0 -0
  103. /package/skills/{lint/references → peago/references/lint/scripts}/detect-language.js +0 -0
  104. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/Calculator.js +0 -0
  105. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/ConfigManager.js +0 -0
  106. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/FileProcessor.js +0 -0
  107. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/OrderService.js +0 -0
  108. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/TokenGenerator.js +0 -0
  109. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/UserService.js +0 -0
  110. /package/skills/{jstest/references/src/jstest-sample → peago/references/test/sample-src/js}/index.js +0 -0
  111. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/Calculator.py +0 -0
  112. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/ConfigManager.py +0 -0
  113. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/FileProcessor.py +0 -0
  114. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/OrderService.py +0 -0
  115. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/TokenGenerator.py +0 -0
  116. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/UserService.py +0 -0
  117. /package/skills/{pytest/references/src/pytest-sample → peago/references/test/sample-src/py}/__init__.py +0 -0
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-structure.js — 聚合产物结构扫描(ESM,纯 JS,无依赖)
4
+ *
5
+ * 在 docx 生成前对聚合后的双语 `-tsl.md` 做机械结构扫描,拦截上游
6
+ * (清洗/翻译/聚合)过程检查探测不到的结构缺陷:
7
+ *
8
+ * 1. 交错形态:四段连续窗口 [原文断段][译文断段][原文续段][译文续段]
9
+ * —— 原文段不以句末标点结尾 + 原文续段以续接形态(小写/断词)开头。
10
+ * 含链式(同段连续跨多个边界):窗口命中后沿链计数。
11
+ * 2. 孤儿段:连续两个原文段之间无译文段(含块尾未配对原文段)。
12
+ * 3. 过程标记残留:`[CONT]` 计数。
13
+ *
14
+ * 全部为机械规则(字符形态判定),零 LLM 调用,与产物规模线性。
15
+ *
16
+ * 输入:argv[2] = 双语 Markdown 文件路径
17
+ * 输出:stdout 一行汇总(PASS/FAIL + 各项计数);--json 输出明细 JSON
18
+ * 退出码:0 = PASS(全部为 0 或 ≤ 阈值);1 = FAIL
19
+ */
20
+
21
+ import { readFileSync } from 'fs';
22
+
23
+ const isFrPara = s => /[a-zA-Zéèàçùôîâêîôû]{3,}/.test(s) && !/[\u4e00-\u9fff]/.test(s);
24
+ const isZhPara = s => /[\u4e00-\u9fff]/.test(s);
25
+ const endsComplete = s => /[.!?。!?:;;」』)\]»"…]\s*$/.test(s.trimEnd());
26
+ const startsContinuation = s => /^[a-zéèàçùôîâêîôû(«"']/.test(s.trimStart());
27
+ const isFootnotePara = s => /^\d{1,3}[\s,.]/.test(s.trimStart());
28
+ // 表格行:单行、≤8 词、无句末标点(表格行间空行是正常排版,不计交错)
29
+ const isTableLine = s => s.split(/\n/).length === 1 && s.split(/\s+/).length <= 8 && !/[.,;:!?]$/.test(s.trimEnd());
30
+
31
+ /**
32
+ * 扫描双语产物的结构缺陷。
33
+ * @param {string} content — 双语 Markdown 全文
34
+ * @returns {{ interleave: object[], orphans: object[], contCount: number, paras: number }}
35
+ */
36
+ export function checkStructure(content) {
37
+ // 判定前剥离 markdown 行前缀(>、#、*、列表符),使 fmt 版与纯文本判定一致
38
+ const stripMd = s => s.replace(/^[>#\-*\s]+/gm, '');
39
+ const paras = content.split(/\n\n+/).map(p => p.trim()).filter(Boolean);
40
+ const interleave = [];
41
+ const orphans = [];
42
+ let contCount = (content.match(/\[CONT\]/g) || []).length;
43
+
44
+ let i = 0;
45
+ while (i < paras.length) {
46
+ const a = paras[i], b = paras[i + 1], c = paras[i + 2], d = paras[i + 3];
47
+
48
+ // —— 交错形态(四段窗口)——
49
+ if (b !== undefined && c !== undefined && d !== undefined &&
50
+ isFrPara(stripMd(a)) && isZhPara(stripMd(b)) && isFrPara(stripMd(c)) && isZhPara(stripMd(d)) &&
51
+ !endsComplete(a) && startsContinuation(c) &&
52
+ !isFootnotePara(stripMd(a)) && !(isTableLine(stripMd(a)) && isTableLine(stripMd(c))) &&
53
+ a.split(/\s+/).length > 6) {
54
+ interleave.push({
55
+ index: i,
56
+ tail: a.slice(-40),
57
+ head: c.slice(0, 40),
58
+ chain: 1,
59
+ });
60
+ // 跳过整个窗口(链式在产物上表现为多个相邻窗口,逐窗口计数)
61
+ i += 4;
62
+ continue;
63
+ }
64
+
65
+ // —— 孤儿段:连续两个原文段无译文间隔 ——
66
+ // 豁免 1:文献引用连排(学术翻译惯例——脚注/参考文献条目原文可不译)。
67
+ // 豁免 2:区域对照布局(原文区整块在前、译文区整块在后)——连续原文段
68
+ // ≥3 且其后紧跟连续中文段(译文区)时,属合法排版变体,跳过。
69
+ const isBiblio = s => /\(\d{4}\)|\d+:\d+|\bvol\.?\b|\bpp\.?\b|Press|University|Éditions|\bidem\b|Ibid/i.test(s);
70
+ if (b !== undefined && isFrPara(stripMd(a)) && isFrPara(stripMd(b)) &&
71
+ stripMd(a).split(/\s+/).length > 6 && stripMd(b).split(/\s+/).length > 6 &&
72
+ !isFootnotePara(stripMd(a)) && !isFootnotePara(stripMd(b)) &&
73
+ !isBiblio(stripMd(a)) && !isBiblio(stripMd(b))) {
74
+ // 区域对照判定:向前向后数连续原文段
75
+ let run = 0;
76
+ while (i + run < paras.length && isFrPara(stripMd(paras[i + run]))) run++;
77
+ const followedByZh = i + run < paras.length && isZhPara(stripMd(paras[i + run]));
78
+ const isZoneLayout = (run >= 3 && followedByZh) || run >= 6;
79
+ if (!isZoneLayout) {
80
+ orphans.push({ index: i, tail: a.slice(-40), next: b.slice(0, 40) });
81
+ }
82
+ i += Math.max(run, 2);
83
+ continue;
84
+ }
85
+
86
+ i += 1;
87
+ }
88
+
89
+ return { interleave, orphans, contCount, paras: paras.length };
90
+ }
91
+
92
+ // --- CLI ---
93
+
94
+ const isMain = !process.env.JEST_WORKER_ID && import.meta.url === `file://${process.argv[1]}`;
95
+
96
+ if (isMain) {
97
+ const file = process.argv[2];
98
+ const asJson = process.argv.includes('--json');
99
+ if (!file) {
100
+ console.error('usage: node check-structure.js <bilingual.md> [--json]');
101
+ process.exit(1);
102
+ }
103
+ const r = checkStructure(readFileSync(file, 'utf-8'));
104
+ const pass = r.interleave.length === 0 && r.orphans.length === 0 && r.contCount === 0;
105
+ if (asJson) {
106
+ console.log(JSON.stringify({ pass, ...r }, null, 2));
107
+ } else {
108
+ console.log(
109
+ `${pass ? 'PASS' : 'FAIL'}: paragraphs ${r.paras}, interleave ${r.interleave.length}, ` +
110
+ `orphans ${r.orphans.length}, cont ${r.contCount}`
111
+ );
112
+ if (!pass) {
113
+ for (const x of r.interleave.slice(0, 5)) console.log(` interleave@${x.index}: …${x.tail} ▶ ${x.head}…`);
114
+ for (const x of r.orphans.slice(0, 5)) console.log(` orphan@${x.index}: …${x.tail} | ${x.next}…`);
115
+ }
116
+ }
117
+ process.exit(pass ? 0 : 1);
118
+ }
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * chunk-bilingual.js — 双语文档分块 + 格式重建进度初始化(ESM,纯 JS,无依赖)
4
+ *
5
+ * 用法:node chunk-bilingual.js <work_dir> <chunk_words> [<input_file>]
6
+ * <input_file> 缺省 = <work_dir>/bilingual.md(translate Item 6)
7
+ * 显式传入 = 从指定文件分块(translate-format Item 2)
8
+ *
9
+ * 功能:
10
+ * 1. 创建 <work_dir>/fmt/ 目录
11
+ * 2. 按段落边界将输入文档分块,写入 fmt/p001.md...
12
+ * 3. 创建 fmt/progress.md(身份行 + chunk 状态表)
13
+ * 4. stdout 打印总块数
14
+ *
15
+ * 短路:fmt/progress.md 已存在 → 跳过分块和初始化,仅打印已有块数
16
+ */
17
+
18
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'fs';
19
+ import { join, basename } from 'path';
20
+
21
+ /**
22
+ * 将文本按段落边界分块。
23
+ * @param {string} content — 文本内容
24
+ * @param {number} chunkWords — 每块最大词数
25
+ * @returns {string[]} 分块数组
26
+ */
27
+ export function chunkBilingual(content, chunkWords) {
28
+ if (!content || !content.trim()) return [];
29
+
30
+ const paragraphs = content.split(/\n\n+/);
31
+
32
+ const chunks = [];
33
+ let currentChunk = [];
34
+ let currentWords = 0;
35
+
36
+ for (const para of paragraphs) {
37
+ const trimmed = para.trim();
38
+ if (!trimmed) continue;
39
+
40
+ const words = trimmed.split(/\s+/).filter(Boolean).length;
41
+
42
+ if (currentWords + words > chunkWords && currentChunk.length > 0) {
43
+ chunks.push(currentChunk.join('\n\n'));
44
+ currentChunk = [trimmed];
45
+ currentWords = words;
46
+ } else {
47
+ currentChunk.push(trimmed);
48
+ currentWords += words;
49
+ }
50
+ }
51
+
52
+ if (currentChunk.length > 0) {
53
+ chunks.push(currentChunk.join('\n\n'));
54
+ }
55
+
56
+ return chunks;
57
+ }
58
+
59
+ // --- CLI ---
60
+
61
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
62
+
63
+ if (isMain) {
64
+ const args = process.argv.slice(2);
65
+
66
+ if (args.length < 2) {
67
+ console.error('Usage: node chunk-bilingual.js <work_dir> <chunk_words> [<input_file>]');
68
+ process.exit(2);
69
+ }
70
+
71
+ const [workDir, chunkWordsStr, inputFile] = args;
72
+ const chunkWords = parseInt(chunkWordsStr, 10);
73
+ const fmtDir = join(workDir, 'fmt');
74
+ const progressPath = join(fmtDir, 'progress.md');
75
+
76
+ if (isNaN(chunkWords) || chunkWords < 100) {
77
+ console.error('ERROR: chunk_words must be a number >= 100');
78
+ process.exit(2);
79
+ }
80
+
81
+ // 短路:progress.md 已存在 → 仅打印已有块数
82
+ if (existsSync(progressPath)) {
83
+ const existing = readdirSync(fmtDir).filter(f => f.match(/^p\d+\.md$/)).length;
84
+ console.log(`chunks: ${existing} (skipped, progress.md exists)`);
85
+ process.exit(0);
86
+ }
87
+
88
+ // 输入源:显式 input_file 优先,缺省 <work_dir>/bilingual.md
89
+ const inputPath = inputFile || join(workDir, 'bilingual.md');
90
+ if (!existsSync(inputPath)) {
91
+ console.error(`ERROR: input file not found: ${inputPath}`);
92
+ process.exit(2);
93
+ }
94
+
95
+ const content = readFileSync(inputPath, 'utf-8');
96
+ const chunks = chunkBilingual(content, chunkWords);
97
+
98
+ if (chunks.length === 0) {
99
+ console.error(`ERROR: input is empty or contains no paragraphs: ${inputPath}`);
100
+ process.exit(2);
101
+ }
102
+
103
+ // 1. 创建 fmt/ 目录
104
+ mkdirSync(fmtDir, { recursive: true });
105
+
106
+ // 2. 写分块文件
107
+ chunks.forEach((chunk, i) => {
108
+ const num = String(i + 1).padStart(3, '0');
109
+ writeFileSync(join(fmtDir, `p${num}.md`), chunk + '\n', 'utf-8');
110
+ });
111
+
112
+ // 3. 创建 progress.md
113
+ const inputDirBasename = basename(join(workDir, '..', '..'));
114
+ const fileBasename = basename(workDir);
115
+ const lines = [`# tsl format progress — book: ${inputDirBasename}, file: ${fileBasename}`, '', '| Chunk | 状态 | 重试 |', '|-------|------|------|'];
116
+ for (let i = 0; i < chunks.length; i++) {
117
+ const num = String(i + 1).padStart(3, '0');
118
+ lines.push(`| p${num} | pending | 0 |`);
119
+ }
120
+ writeFileSync(progressPath, lines.join('\n') + '\n', 'utf-8');
121
+
122
+ console.log(`chunks: ${chunks.length}`);
123
+ }
@@ -0,0 +1,150 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * chunk-text.js — 文本分块脚本(ESM,段落感知)
4
+ *
5
+ * 输入:argv[2] = 工作目录(含 source.txt),argv[3] = 每块最大词数(默认 4000)
6
+ * 输出:p001.txt, p002.txt, ... 写入工作目录,stdout 打印总块数
7
+ *
8
+ * 分块策略:
9
+ * - PDF 文本(含 \f):按 \f 切分页面,按 chunk_words 分组
10
+ * - 纯文本(无 \f):按段落边界切分,尽量不切断段落;单段落超长时按词数硬切
11
+ * - 每块末尾检测段落是否完整(以句末标点结尾),不完整时追加 [CONT] 标记
12
+ */
13
+
14
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'fs';
15
+ import { join } from 'path';
16
+
17
+ const args = process.argv.slice(2);
18
+
19
+ if (args.length < 1) {
20
+ console.error('usage: chunk-text.js <work_dir> [chunk_words=4000]');
21
+ process.exit(2);
22
+ }
23
+
24
+ const workDir = args[0];
25
+ const chunkWords = Math.max(100, parseInt(args[1] || '4000', 10));
26
+ const sourcePath = join(workDir, 'source.txt');
27
+
28
+ if (!existsSync(sourcePath)) {
29
+ console.error(`ERROR: source file not found: ${sourcePath}`);
30
+ process.exit(2);
31
+ }
32
+
33
+ const outputDir = workDir;
34
+ mkdirSync(outputDir, { recursive: true });
35
+
36
+ const content = readFileSync(sourcePath, 'utf-8');
37
+
38
+ // Count words (CJK-aware: CJK chars count as ~1 word per 1.5 chars; others by whitespace)
39
+ function countWords(text) {
40
+ const trimmed = text.trim();
41
+ if (!trimmed) return 0;
42
+ const cjkMatches = trimmed.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g);
43
+ const cjkCount = cjkMatches ? cjkMatches.length : 0;
44
+ const restCount = trimmed.split(/\s+/).filter(w => w.length > 0).length;
45
+ return Math.ceil(cjkCount / 1.5) + restCount;
46
+ }
47
+
48
+ // Check if text ends with a complete sentence (sentence-ending punctuation)
49
+ function isParagraphComplete(text) {
50
+ const trimmed = text.trimEnd();
51
+ if (trimmed.length === 0) return true;
52
+ // Common sentence-ending punctuation in multiple languages
53
+ return /[.!?。!?:;;]\s*$/.test(trimmed) ||
54
+ /["'」』))\]]\s*$/.test(trimmed) ||
55
+ trimmed.endsWith('[CONT]'); // already marked
56
+ }
57
+
58
+ // Append [CONT] marker if last paragraph is incomplete
59
+ function markIncomplete(chunk) {
60
+ const trimmed = chunk.trimEnd();
61
+ if (trimmed.length === 0) return chunk;
62
+ if (isParagraphComplete(trimmed)) return chunk;
63
+ // Find last non-empty line
64
+ return chunk.replace(/\s*$/, '\n[CONT]\n');
65
+ }
66
+
67
+ // Split into chunks
68
+ let chunks = [];
69
+
70
+ if (content.includes('\f')) {
71
+ // PDF text with form feed page breaks
72
+ const pages = content.split('\f');
73
+ let currentChunk = '';
74
+
75
+ for (let i = 0; i < pages.length; i++) {
76
+ const page = pages[i];
77
+ if (page.trim().length === 0) continue;
78
+
79
+ const pageWords = countWords(page);
80
+ const wouldExceedWords = countWords(currentChunk) + pageWords > chunkWords;
81
+
82
+ if (wouldExceedWords && currentChunk.length > 0) {
83
+ // Mark incomplete before flushing
84
+ chunks.push(markIncomplete(currentChunk));
85
+ currentChunk = page;
86
+ } else {
87
+ currentChunk += (currentChunk ? '\n' : '') + page;
88
+ }
89
+ }
90
+
91
+ // Flush remaining (last chunk — don't mark [CONT], it's the end of document)
92
+ if (currentChunk.trim().length > 0) {
93
+ chunks.push(currentChunk);
94
+ }
95
+ } else {
96
+ // Plain text without page breaks — split by paragraph boundaries
97
+ const paragraphs = content.split(/\n\s*\n/); // Split on double newline (paragraph boundary)
98
+
99
+ let currentChunk = '';
100
+
101
+ for (const para of paragraphs) {
102
+ if (para.trim().length === 0) continue;
103
+
104
+ const paraWords = countWords(para);
105
+ const chunkWordsNow = countWords(currentChunk);
106
+
107
+ // If adding this paragraph exceeds limit and we have content, flush
108
+ if (chunkWordsNow + paraWords > chunkWords && currentChunk.length > 0) {
109
+ chunks.push(markIncomplete(currentChunk));
110
+ currentChunk = para;
111
+ } else {
112
+ currentChunk += (currentChunk ? '\n\n' : '') + para;
113
+ }
114
+
115
+ // If single paragraph exceeds chunk_words, hard-split it by words
116
+ while (countWords(currentChunk) > chunkWords) {
117
+ const words = currentChunk.trim().split(/\s+/);
118
+ const firstPart = words.slice(0, chunkWords).join(' ');
119
+ const restPart = words.slice(chunkWords).join(' ');
120
+ chunks.push(markIncomplete(firstPart));
121
+ currentChunk = restPart;
122
+ }
123
+ }
124
+
125
+ // Flush remaining (last chunk — no [CONT])
126
+ if (currentChunk.trim().length > 0) {
127
+ chunks.push(currentChunk);
128
+ }
129
+ }
130
+
131
+ // Filter empty chunks
132
+ chunks = chunks.filter(c => c.trim().length > 0);
133
+
134
+ if (chunks.length === 0) {
135
+ console.error('ERROR: no content to chunk');
136
+ process.exit(3);
137
+ }
138
+
139
+ // Write chunks
140
+ let contCount = 0;
141
+ for (let i = 0; i < chunks.length; i++) {
142
+ const chunkNum = String(i + 1).padStart(3, '0');
143
+ const chunkPath = join(outputDir, `p${chunkNum}.txt`);
144
+ writeFileSync(chunkPath, chunks[i], 'utf-8');
145
+ if (chunks[i].includes('[CONT]')) contCount++;
146
+ }
147
+
148
+ // Print summary
149
+ const totalWords = chunks.reduce((sum, c) => sum + countWords(c), 0);
150
+ console.log(`chunked: ${chunks.length} chunks, ~${totalWords} words, ${contCount} [CONT] markers → ${outputDir}/p001.txt..p${String(chunks.length).padStart(3, '0')}.txt`);
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * clean-text.js — PDF 提取文本清洗脚本(ESM,纯 JS,无系统依赖)
4
+ *
5
+ * 清洗 pdf-parse 提取的 source.txt 中的确定性噪声:
6
+ * 1. Tab 字符 → 空格
7
+ * 2. 独立 ^ 字符(OCR 噪声)→ 删除(保留 \f 页标记)
8
+ * 3. 行中 \f(页中断合并文本)→ 拆分为独立行
9
+ * 4. 连续空格 → 单空格
10
+ * 5. 行尾空格 → 删除
11
+ *
12
+ * 输入:argv[2] = source.txt 路径
13
+ * 输出:原地清洗,stdout 打印统计
14
+ *
15
+ * 用法:
16
+ * node clean-text.js "<source.txt>"
17
+ */
18
+
19
+ import { readFileSync, writeFileSync, existsSync } from 'fs';
20
+
21
+ /**
22
+ * 清洗文本内容,返回清洗后的内容和统计信息。
23
+ * @param {string} content — 原始文本
24
+ * @returns {{ content: string, stats: { tabs: number, carets: number, formFeeds: number } }}
25
+ */
26
+ export function cleanText(content) {
27
+ let tabCount = 0;
28
+ let caretCount = 0;
29
+ let formFeedSplitCount = 0;
30
+
31
+ // 1. 行中 \f 拆分:将 "text\fmore" 拆为 "text\n\f\nmore"
32
+ // \f 独占一行,保留为页标记(chunk-text.js 依赖 \f 分页)
33
+ const lines = content.split('\n');
34
+ const processedLines = [];
35
+
36
+ for (const line of lines) {
37
+ // 独占行的 \f 是页标记,不拆分
38
+ if (line === '\f') {
39
+ processedLines.push(line);
40
+ continue;
41
+ }
42
+ if (line.includes('\f')) {
43
+ const parts = line.split('\f');
44
+ for (let i = 0; i < parts.length; i++) {
45
+ if (i > 0) {
46
+ processedLines.push('\f');
47
+ formFeedSplitCount++;
48
+ }
49
+ if (parts[i].length > 0) {
50
+ processedLines.push(parts[i]);
51
+ }
52
+ }
53
+ } else {
54
+ processedLines.push(line);
55
+ }
56
+ }
57
+
58
+ // 2. 逐行清洗:tab→空格、删除^、折叠空格、去行尾空格
59
+ const cleanedLines = processedLines.map((line) => {
60
+ // 跳过 \f 独占行,不清洗
61
+ if (line === '\f') return line;
62
+
63
+ let cleaned = line;
64
+
65
+ // Tab → 空格
66
+ const tabs = (cleaned.match(/\t/g) || []).length;
67
+ if (tabs > 0) {
68
+ cleaned = cleaned.replace(/\t/g, ' ');
69
+ tabCount += tabs;
70
+ }
71
+
72
+ // 删除 ^ 字符(OCR 噪声,不删除 \f)
73
+ const carets = (cleaned.match(/\^/g) || []).length;
74
+ if (carets > 0) {
75
+ cleaned = cleaned.replace(/\^/g, '');
76
+ caretCount += carets;
77
+ }
78
+
79
+ // 折叠连续空格 → 单空格
80
+ cleaned = cleaned.replace(/ {2,}/g, ' ');
81
+
82
+ // 去行尾空格
83
+ cleaned = cleaned.replace(/\s+$/, '');
84
+
85
+ return cleaned;
86
+ });
87
+
88
+ return {
89
+ content: cleanedLines.join('\n'),
90
+ stats: { tabs: tabCount, carets: caretCount, formFeeds: formFeedSplitCount },
91
+ };
92
+ }
93
+
94
+ // --- CLI ---
95
+
96
+ const isMain = import.meta.url === `file://${process.argv[1]}`;
97
+
98
+ if (isMain) {
99
+ const args = process.argv.slice(2);
100
+
101
+ if (args.length < 1) {
102
+ console.error('usage: clean-text.js <source.txt>');
103
+ process.exit(2);
104
+ }
105
+
106
+ const filePath = args[0];
107
+
108
+ if (!existsSync(filePath)) {
109
+ console.error(`ERROR: source file not found: ${filePath}`);
110
+ process.exit(2);
111
+ }
112
+
113
+ const raw = readFileSync(filePath, 'utf-8');
114
+ const { content, stats } = cleanText(raw);
115
+ writeFileSync(filePath, content, 'utf-8');
116
+
117
+ console.log(`clean-text: ${filePath}`);
118
+ console.log(` tabs replaced: ${stats.tabs}`);
119
+ console.log(` carets removed: ${stats.carets}`);
120
+ console.log(` form feeds split: ${stats.formFeeds}`);
121
+ }
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * count-terms.js — 词频统计脚本(ESM)
4
+ *
5
+ * 输入:argv[2] = 工作目录(.tsl/,含各子目录的 source.txt),argv[3] = 术语列表(逗号分隔)
6
+ * 输出:stdout 每行 "次数\t术语",按次数降序
7
+ *
8
+ * 统计方式:大小写不敏感子串计数,扫描 .tsl/ 下所有子目录的 source.txt 全文。
9
+ */
10
+
11
+ import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
12
+ import { join } from 'path';
13
+
14
+ const args = process.argv.slice(2);
15
+ const workDir = args[0];
16
+ const termsCsv = args[1];
17
+
18
+ if (!workDir || !termsCsv) {
19
+ console.error('Usage: node count-terms.js <work_dir> <terms_csv>');
20
+ process.exit(2);
21
+ }
22
+
23
+ const terms = termsCsv.split(',').map(t => t.trim()).filter(t => t.length > 0);
24
+
25
+ // 扫描所有子目录的 source.txt,合并全文
26
+ const subdirs = readdirSync(workDir)
27
+ .filter(name => {
28
+ const p = join(workDir, name);
29
+ return statSync(p).isDirectory() && existsSync(join(p, 'source.txt'));
30
+ })
31
+ .sort();
32
+
33
+ let fullText = '';
34
+ for (const name of subdirs) {
35
+ fullText += readFileSync(join(workDir, name, 'source.txt'), 'utf-8') + '\n';
36
+ }
37
+
38
+ const lower = fullText.toLowerCase();
39
+ const result = [];
40
+ for (const term of terms) {
41
+ const tl = term.toLowerCase();
42
+ let count = 0;
43
+ let idx = lower.indexOf(tl);
44
+ while (idx !== -1) {
45
+ count++;
46
+ idx = lower.indexOf(tl, idx + tl.length);
47
+ }
48
+ result.push({ term, count });
49
+ }
50
+
51
+ result.sort((a, b) => b.count - a.count);
52
+ for (const r of result) {
53
+ console.log(`${r.count}\t${r.term}`);
54
+ }