hnch-docs 0.2.1

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/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "hnch-docs",
3
+ "version": "0.2.1",
4
+ "description": "hnch \u6587\u4ef6\u89e3\u6790 \u2014\u2014 \u7b56\u7565\u6a21\u5f0f\uff0c\u652f\u6301 PDF/DOCX/DOC/XLSX/PPTX/MD/TXT/CSV/JSON/HTML/EPUB/\u56fe\u7247/Tesseract OCR/\u97f3\u9891/\u89c6\u9891",
5
+ "main": "src/index.js",
6
+ "exports": {
7
+ ".": "./src/index.js",
8
+ "./ocr": "./src/strategies/image.js"
9
+ },
10
+ "scripts": {
11
+ "test": "echo \"Error: no test specified\" && exit 1"
12
+ },
13
+ "keywords": [
14
+ "file",
15
+ "parser",
16
+ "pdf",
17
+ "docx",
18
+ "ocr",
19
+ "epub",
20
+ "html"
21
+ ],
22
+ "author": "",
23
+ "license": "ISC",
24
+ "dependencies": {
25
+ "chardet": "^2.1.0",
26
+ "cheerio": "^1.0.0",
27
+ "epub": "^2.1.1",
28
+ "fast-xml-parser": "^4.4.0",
29
+ "iconv-lite": "^0.6.3",
30
+ "jszip": "^3.10.1",
31
+ "mammoth": "^1.9.0",
32
+ "pdf-parse": "^1.1.1",
33
+ "tesseract.js": "^5.0.4",
34
+ "word-extractor": "^1.0.4",
35
+ "xlsx": "^0.18.5"
36
+ }
37
+ }
package/src/format.js ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 文本格式化工具
3
+ *
4
+ * 提取过程通用的 Markdown 输出辅助。
5
+ */
6
+
7
+ /**
8
+ * 单元格转义:处理 null/undefined、换行、管道符
9
+ */
10
+ function escapeCell(val) {
11
+ if (val == null) return '';
12
+ return String(val)
13
+ .replace(/\r?\n|\r/g, '<br>')
14
+ .replace(/\|/g, '\\|');
15
+ }
16
+
17
+ /**
18
+ * 二维数组 → Markdown 表格(含转义)
19
+ */
20
+ function toMarkdownTable(data) {
21
+ if (!data || data.length === 0) return '';
22
+ const norm = data.map(row => (Array.isArray(row) ? row : [row]).map(escapeCell));
23
+ const headers = norm[0];
24
+ const rows = norm.slice(1);
25
+ const headerRow = `| ${headers.join(' | ')} |`;
26
+ const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`;
27
+ const dataRows = rows.map(row => `| ${row.join(' | ')} |`).join('\n');
28
+ return rows.length > 0 ? `${headerRow}\n${separatorRow}\n${dataRows}` : `${headerRow}\n${separatorRow}`;
29
+ }
30
+
31
+ /**
32
+ * 解析单行 CSV(识别引号包裹、转义双引号)
33
+ */
34
+ function parseCsvLine(line, delim = ',') {
35
+ const out = [];
36
+ let cur = '';
37
+ let inQuote = false;
38
+ for (let i = 0; i < line.length; i++) {
39
+ const c = line[i];
40
+ if (inQuote) {
41
+ if (c === '"' && line[i + 1] === '"') { cur += '"'; i++; }
42
+ else if (c === '"') { inQuote = false; }
43
+ else { cur += c; }
44
+ } else {
45
+ if (c === '"') { inQuote = true; }
46
+ else if (c === delim) { out.push(cur); cur = ''; }
47
+ else { cur += c; }
48
+ }
49
+ }
50
+ out.push(cur);
51
+ return out.map(s => s.trim());
52
+ }
53
+
54
+ module.exports = { toMarkdownTable, escapeCell, parseCsvLine };
package/src/index.js ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * @hnch/ragdoc — RAG 文档解析核心
3
+ *
4
+ * 策略模式驱动,按文件类型自动选择解析器。
5
+ *
6
+ * 用法:
7
+ * const { extractText, extractMeta, extractStructured, listStrategies, registerStrategy } = require('@hnch/ragdoc');
8
+ * const text = await extractText('/path/to/file.pdf');
9
+ * const meta = await extractMeta('/path/to/file.pdf');
10
+ * const text = await extractText(buffer, { ext: '.pdf', withHeader: true, cjkSpacing: true });
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+ const registry = require('./strategies/registry');
16
+
17
+ // ── 工具 ────────────────────────────────────────────
18
+
19
+ function isBuffer(val) {
20
+ return Buffer.isBuffer(val);
21
+ }
22
+
23
+ function isFilePath(val) {
24
+ return typeof val === 'string' && !val.startsWith('<') && val.length < 4096;
25
+ }
26
+
27
+ /**
28
+ * 通过文件头部魔数检测真实类型
29
+ * 比扩展名更可靠
30
+ */
31
+ function detectRealExt(filePath) {
32
+ let fd;
33
+ try {
34
+ fd = fs.openSync(filePath, 'r');
35
+ const buf = Buffer.alloc(8);
36
+ fs.readSync(fd, buf, 0, 8, 0);
37
+
38
+ // ZIP-based formats (DOCX/XLSX/PPTX/EPUB all start with PK) — 需深入识别,这里仅识别非压缩格式
39
+ if (buf[0] === 0x50 && buf[1] === 0x4B) return null;
40
+ if (buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46) return '.pdf';
41
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47) return '.png';
42
+ if (buf[0] === 0xFF && buf[1] === 0xD8) return '.jpg';
43
+ } catch {
44
+ return null;
45
+ } finally {
46
+ if (fd !== undefined) { try { fs.closeSync(fd); } catch { } }
47
+ }
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * 确认文件扩展名(优先魔数,回退扩展名)
53
+ */
54
+ function resolveExt(filePath) {
55
+ const magic = detectRealExt(filePath);
56
+ if (magic) return magic;
57
+ return path.extname(filePath).toLowerCase();
58
+ }
59
+
60
+ // ── 核心提取 ────────────────────────────────────────
61
+
62
+ /**
63
+ * 提取文件文本内容
64
+ *
65
+ * @param {string|Buffer} input - 文件路径或 Buffer
66
+ * @param {Object} [opts]
67
+ * @param {string} [opts.strategy] - 强制策略名
68
+ * @param {string} [opts.ext] - 扩展名(Buffer 输入时必填)
69
+ * @param {string} [opts.format] - 'markdown' | 'text' (默认 'markdown')
70
+ * @param {boolean} [opts.fallback] - 策略失败时自动降级 (默认 true)
71
+ * @param {boolean} [opts.withHeader]- 输出顶部加 YAML frontmatter (默认 false)
72
+ * @param {boolean} [opts.cjkSpacing]- 中英文之间加空格 (默认 false)
73
+ * @param {boolean} [opts.embedImages]- DOCX 图片是否 base64 内嵌 (默认 false)
74
+ * @param {Function} [opts.onProgress] - 进度回调 (0-100)
75
+ * @returns {Promise<string>}
76
+ */
77
+ async function extractText(input, opts = {}) {
78
+ const {
79
+ strategy: forcedName,
80
+ ext: givenExt,
81
+ fallback = true,
82
+ format = 'markdown',
83
+ withHeader = false,
84
+ cjkSpacing = false,
85
+ embedImages = false,
86
+ } = opts;
87
+
88
+ let ext, filePath;
89
+
90
+ if (isFilePath(input)) {
91
+ filePath = input;
92
+ if (!fs.existsSync(filePath)) {
93
+ throw Object.assign(new Error(`文件不存在: ${filePath}`), { code: 'FILE_NOT_FOUND' });
94
+ }
95
+ const maxSize = parseInt(process.env.FILE_MAX_SIZE) || 100 * 1024 * 1024;
96
+ const stat = fs.statSync(filePath);
97
+ if (stat.size > maxSize) {
98
+ throw Object.assign(
99
+ new Error(`文件过大 (${formatSize(stat.size)},上限 ${formatSize(maxSize)})`),
100
+ { code: 'FILE_TOO_LARGE' },
101
+ );
102
+ }
103
+ ext = givenExt || resolveExt(filePath);
104
+ } else if (isBuffer(input)) {
105
+ if (!givenExt) throw new Error('Buffer 输入必须提供 opts.ext');
106
+ ext = givenExt.toLowerCase();
107
+ filePath = null;
108
+ } else {
109
+ throw new Error('input 必须是文件路径或 Buffer');
110
+ }
111
+
112
+ // 策略选择
113
+ const strategies = forcedName
114
+ ? [registry.get(forcedName)].filter(Boolean)
115
+ : registry.matchAll(ext);
116
+
117
+ if (strategies.length === 0) {
118
+ throw Object.assign(new Error(`不支持的文件类型: ${ext}`), { code: 'UNSUPPORTED_TYPE' });
119
+ }
120
+
121
+ // 按优先级尝试
122
+ const timeoutMs = parseInt(process.env.FILE_TIMEOUT_MS) || 60000;
123
+ let lastErr;
124
+ let usedStrategy = null;
125
+ let raw;
126
+ for (const strategy of strategies) {
127
+ try {
128
+ if (strategy.isAvailable && !strategy.isAvailable()) continue;
129
+ raw = await Promise.race([
130
+ strategy.extract(filePath || input, {
131
+ ext, format, embedImages, onProgress: opts.onProgress,
132
+ }),
133
+ new Promise((_, reject) =>
134
+ setTimeout(() => reject(new Error(`解析超时 (${timeoutMs}ms)`)), timeoutMs),
135
+ ),
136
+ ]);
137
+ usedStrategy = strategy;
138
+ break;
139
+ } catch (err) {
140
+ lastErr = err;
141
+ // 终态错误(扫描件 OCR 路径已用尽)不再降级到其他策略
142
+ const TERMINAL_CODES = ['SCANNED_PDF_NO_OCR_STRATEGY', 'SCANNED_PDF_NO_OCR_ENGINE'];
143
+ if (!fallback || TERMINAL_CODES.includes(err.code)) throw err;
144
+ }
145
+ }
146
+
147
+ if (!usedStrategy) {
148
+ throw Object.assign(
149
+ new Error(`文件解析失败 (${ext}): ${lastErr?.message || '所有策略均失败'}`),
150
+ { code: 'EXTRACT_FAILED', originalError: lastErr },
151
+ );
152
+ }
153
+
154
+ // 元数据(仅在需要 header 时拉取)
155
+ let meta = { ext };
156
+ if (withHeader && filePath && usedStrategy.extractMeta) {
157
+ try {
158
+ const extra = await usedStrategy.extractMeta(filePath);
159
+ Object.assign(meta, extra);
160
+ } catch { /* 元数据失败不阻断 */ }
161
+ }
162
+
163
+ return postProcess(raw, meta, { withHeader, cjkSpacing });
164
+ }
165
+
166
+ // ── 元数据 ──────────────────────────────────────────
167
+
168
+ /**
169
+ * 提取文件元数据
170
+ * @returns {Promise<{size, createdAt, modifiedAt, ext, mime, pages, author, title}>}
171
+ */
172
+ async function extractMeta(filePath) {
173
+ if (!fs.existsSync(filePath)) {
174
+ throw Object.assign(new Error(`文件不存在: ${filePath}`), { code: 'FILE_NOT_FOUND' });
175
+ }
176
+
177
+ const stat = fs.statSync(filePath);
178
+ const ext = resolveExt(filePath);
179
+
180
+ const meta = {
181
+ path: filePath,
182
+ size: stat.size,
183
+ sizeFormatted: formatSize(stat.size),
184
+ createdAt: stat.birthtime,
185
+ modifiedAt: stat.mtime,
186
+ ext,
187
+ mime: extToMime(ext),
188
+ pages: null,
189
+ author: null,
190
+ title: null,
191
+ };
192
+
193
+ const strategies = registry.matchAll(ext);
194
+ for (const s of strategies) {
195
+ if (s.extractMeta) {
196
+ try {
197
+ const extra = await s.extractMeta(filePath);
198
+ Object.assign(meta, extra);
199
+ } catch { /* 元数据失败不阻断 */ }
200
+ }
201
+ }
202
+
203
+ return meta;
204
+ }
205
+
206
+ // ── 结构化提取 ──────────────────────────────────────
207
+
208
+ /**
209
+ * 提取表格等结构化数据
210
+ * @returns {Promise<{tables: Array<{headers, rows}>, text: string}>}
211
+ */
212
+ async function extractStructured(filePath, opts = {}) {
213
+ const ext = resolveExt(filePath);
214
+ const strategies = registry.matchAll(ext);
215
+
216
+ for (const s of strategies) {
217
+ if (s.extractStructured) {
218
+ try {
219
+ return s.extractStructured(filePath, opts);
220
+ } catch { /* 降级 */ }
221
+ }
222
+ }
223
+
224
+ const text = await extractText(filePath, opts);
225
+ return { tables: [], text };
226
+ }
227
+
228
+ // ── 输出 ────────────────────────────────────────────
229
+
230
+ function formatSize(bytes) {
231
+ if (bytes < 1024) return `${bytes} B`;
232
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
233
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
234
+ }
235
+
236
+ function extToMime(ext) {
237
+ const map = {
238
+ '.pdf': 'application/pdf',
239
+ '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
240
+ '.doc': 'application/msword',
241
+ '.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
242
+ '.xls': 'application/vnd.ms-excel',
243
+ '.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
244
+ '.ppt': 'application/vnd.ms-powerpoint',
245
+ '.md': 'text/markdown',
246
+ '.txt': 'text/plain',
247
+ '.csv': 'text/csv',
248
+ '.json': 'application/json',
249
+ '.html': 'text/html',
250
+ '.htm': 'text/html',
251
+ '.epub': 'application/epub+zip',
252
+ '.png': 'image/png',
253
+ '.jpg': 'image/jpeg',
254
+ '.jpeg': 'image/jpeg',
255
+ '.webp': 'image/webp',
256
+ };
257
+ return map[ext] || 'application/octet-stream';
258
+ }
259
+
260
+
261
+ // ── 后处理 ────────────────────────────────────────
262
+
263
+ const CODE_FENCE_RE = /```[\s\S]*?```/g;
264
+
265
+ /**
266
+ * 中英文之间加空格(保护代码块/行内代码/URL)
267
+ */
268
+ function addCjkSpacing(text) {
269
+ // 把代码块/行内代码替换成占位符,处理完再还原
270
+ const placeholders = [];
271
+ const stash = (m) => { placeholders.push(m); return `${placeholders.length - 1}`; };
272
+ let work = text
273
+ .replace(CODE_FENCE_RE, stash)
274
+ .replace(/`[^`\n]+`/g, stash)
275
+ .replace(/https?:\/\/[^\s)]+/g, stash);
276
+
277
+ work = work
278
+ .replace(/([一-鿿])([a-zA-Z0-9])/g, '$1 $2')
279
+ .replace(/([a-zA-Z0-9])([一-鿿])/g, '$1 $2');
280
+
281
+ return work.replace(/(\d+)/g, (_, i) => placeholders[+i]);
282
+ }
283
+
284
+ function buildHeader(meta) {
285
+ const lines = [
286
+ meta.title ? `title: ${meta.title}` : null,
287
+ meta.author ? `author: ${meta.author}` : null,
288
+ meta.pages ? `pages: ${meta.pages}` : null,
289
+ meta.ext ? `ext: ${meta.ext}` : null,
290
+ ].filter(Boolean);
291
+ return lines.length > 0 ? `---\n${lines.join('\n')}\n---\n\n` : '';
292
+ }
293
+
294
+ function postProcess(text, meta, opts = {}) {
295
+ let out = String(text || '');
296
+
297
+ // 合并多余空行(3+ → 2)
298
+ out = out.replace(/\n{3,}/g, '\n\n');
299
+ // 去掉行尾空格
300
+ out = out.replace(/[ \t]+\n/g, '\n');
301
+
302
+ if (opts.cjkSpacing) out = addCjkSpacing(out);
303
+
304
+ out = out.trim();
305
+
306
+ if (opts.withHeader) {
307
+ const header = buildHeader(meta || {});
308
+ if (header) out = header + out;
309
+ }
310
+
311
+ return out;
312
+ }
313
+
314
+ module.exports = {
315
+ extractText, extractMeta, extractStructured, detectRealExt, extToMime,
316
+ listStrategies: () => registry.list().map(s => ({ name: s.name, label: s.label, exts: s.exts, priority: s.priority || 0 })),
317
+ registerStrategy: (s) => registry.register(s),
318
+ };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * 音频转文字策略 —— 占位
3
+ *
4
+ * 需要用户通过 registerStrategy 注入具体实现。
5
+ *
6
+ * 示例(调 server_models Whisper):
7
+ * const { init } = require('@hnch/core/ai');
8
+ * const ai = init({ gatewayUrl: process.env.GATEWAY_URL });
9
+ *
10
+ * registerStrategy({
11
+ * name: 'audio',
12
+ * exts: ['.wav','.mp3','.flac','.ogg','.aac','.m4a','.wma','.opus','.webm','.amr','.mov'],
13
+ * priority: 25,
14
+ * async extract(filePath) {
15
+ * const form = new FormData();
16
+ * form.append('files', fs.createReadStream(filePath), 'audio.wav');
17
+ * form.append('lang', 'auto');
18
+ * const res = await ai.call('POST', '/api/v1/inference', form);
19
+ * return res.result?.[0]?.text || '';
20
+ * }
21
+ * });
22
+ */
23
+
24
+ module.exports = {
25
+ name: 'audio',
26
+ label: '音频转文字(未配置)',
27
+ exts: ['.wav', '.mp3', '.flac', '.ogg', '.aac', '.m4a', '.wma', '.opus', '.webm', '.amr', '.mov'],
28
+ priority: 0,
29
+ isAvailable() { return false; },
30
+ extract() { throw new Error('音频转文字策略未配置'); },
31
+ };
@@ -0,0 +1,103 @@
1
+ /**
2
+ * 百度 OCR 策略
3
+ *
4
+ * 搬自 client_models/server/services/Files/ocr.js
5
+ * 环境变量: BAIDU_OCR_CLIENT_ID / BAIDU_OCR_CLIENT_SECRET / BAIDU_OCR_CACHE_PATH
6
+ */
7
+ const fsSync = require('fs');
8
+ const fs = require('fs').promises;
9
+ const path = require('path');
10
+ const os = require('os');
11
+
12
+ let cachedToken = null;
13
+ let tokenExpiry = 0;
14
+
15
+ function cachePath() {
16
+ // 优先环境变量;否则放到 OS tmpdir(Linux 容器/只读 CWD 也能写)
17
+ return process.env.BAIDU_OCR_CACHE_PATH || path.join(os.tmpdir(), 'baidu_accesstoken.json');
18
+ }
19
+
20
+ async function loadTokenFromDisk() {
21
+ try {
22
+ const data = await fs.readFile(cachePath(), 'utf8');
23
+ return JSON.parse(data);
24
+ } catch {
25
+ return { access_token: null, expires_in: 0 };
26
+ }
27
+ }
28
+
29
+ async function saveTokenToFile(tokenInfo) {
30
+ try {
31
+ const dir = path.dirname(cachePath());
32
+ if (!fsSync.existsSync(dir)) fsSync.mkdirSync(dir, { recursive: true });
33
+ await fs.writeFile(cachePath(), JSON.stringify(tokenInfo), 'utf8');
34
+ } catch { /* 缓存写失败不影响功能 */ }
35
+ }
36
+
37
+ async function refreshToken() {
38
+ const id = process.env.BAIDU_OCR_CLIENT_ID;
39
+ const secret = process.env.BAIDU_OCR_CLIENT_SECRET;
40
+ if (!id || !secret) throw new Error('百度 OCR 未配置: BAIDU_OCR_CLIENT_ID / BAIDU_OCR_CLIENT_SECRET');
41
+
42
+ const res = await fetch('https://aip.baidubce.com/oauth/2.0/token', {
43
+ method: 'POST',
44
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
45
+ body: `grant_type=client_credentials&client_id=${encodeURIComponent(id)}&client_secret=${encodeURIComponent(secret)}`,
46
+ });
47
+ const data = await res.json();
48
+ if (!data.access_token) throw new Error(`百度 OCR Token 获取失败: ${JSON.stringify(data)}`);
49
+
50
+ cachedToken = data.access_token;
51
+ tokenExpiry = Date.now() + (data.expires_in - 600) * 1000;
52
+
53
+ await saveTokenToFile({ access_token: data.access_token, expires_in: Date.now() / 1000 + 2592000 });
54
+ return data.access_token;
55
+ }
56
+
57
+ async function getToken() {
58
+ // 内存缓存
59
+ if (cachedToken && Date.now() < tokenExpiry) return cachedToken;
60
+
61
+ // 磁盘缓存
62
+ const disk = await loadTokenFromDisk();
63
+ if (disk.access_token && disk.expires_in > Date.now() / 1000) {
64
+ cachedToken = disk.access_token;
65
+ tokenExpiry = (disk.expires_in - 600) * 1000;
66
+ return cachedToken;
67
+ }
68
+
69
+ // 远程获取
70
+ return refreshToken();
71
+ }
72
+
73
+ function imageToBase64(filePath) {
74
+ return fsSync.readFileSync(filePath, { encoding: 'base64' });
75
+ }
76
+
77
+ module.exports = {
78
+ name: 'baidu-ocr',
79
+ label: 'OCR (百度)',
80
+ exts: ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff'],
81
+ priority: 30,
82
+ isAvailable() {
83
+ return !!(process.env.BAIDU_OCR_CLIENT_ID && process.env.BAIDU_OCR_CLIENT_SECRET);
84
+ },
85
+ async extract(filePath) {
86
+ const token = await getToken();
87
+ const image = imageToBase64(filePath);
88
+ if (!image) return '';
89
+
90
+ const res = await fetch(
91
+ `https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=${token}`,
92
+ {
93
+ method: 'POST',
94
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json' },
95
+ body: `image=${encodeURIComponent(image)}&detect_direction=false&vertexes_location=false&paragraph=false&probability=false`,
96
+ },
97
+ );
98
+ const body = await res.json();
99
+ if (!body.words_result) throw new Error(`百度 OCR 识别失败: ${JSON.stringify(body)}`);
100
+
101
+ return body.words_result.map(item => `- ${item.words}`).join('\n');
102
+ },
103
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * DOC 解析策略 (word-extractor)
3
+ */
4
+ const WordExtractor = require('word-extractor');
5
+
6
+ module.exports = {
7
+ name: 'word-doc',
8
+ label: 'DOC 解析 (word-extractor)',
9
+ exts: ['.doc'],
10
+ async extract(filePath) {
11
+ const extractor = new WordExtractor();
12
+ const doc = await extractor.extract(filePath);
13
+ return doc.getBody();
14
+ },
15
+ };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * DOCX 解析策略 (mammoth + styleMap)
3
+ *
4
+ * - styleMap 保留标题层级、引用、列表
5
+ * - 默认丢弃图片(节省 token);opts.embedImages=true 时 base64 内嵌
6
+ * - extractMeta 读 docProps/core.xml
7
+ */
8
+ const fs = require('fs');
9
+ const mammoth = require('mammoth');
10
+ const JSZip = require('jszip');
11
+
12
+ const STYLE_MAP = [
13
+ "p[style-name='Title'] => # ",
14
+ "p[style-name='Subtitle'] => ## ",
15
+ "p[style-name='Heading 1'] => # ",
16
+ "p[style-name='Heading 2'] => ## ",
17
+ "p[style-name='Heading 3'] => ### ",
18
+ "p[style-name='Heading 4'] => #### ",
19
+ "p[style-name='Heading 5'] => ##### ",
20
+ "p[style-name='Heading 6'] => ###### ",
21
+ "p[style-name='Quote'] => > ",
22
+ "p[style-name='Intense Quote'] => > ",
23
+ "p[style-name='List Paragraph'] => - ",
24
+ "p[style-name='TOC Heading'] => # ",
25
+ "r[style-name='Strong'] => **$text**",
26
+ "r[style-name='Emphasis'] => *$text*",
27
+ ];
28
+
29
+ function pickXmlField(xml, tag) {
30
+ const re = new RegExp(`<${tag}[^>]*>([\\s\\S]*?)<\\/${tag}>`);
31
+ const m = xml.match(re);
32
+ return m ? m[1].trim() : null;
33
+ }
34
+
35
+ module.exports = {
36
+ name: 'mammoth',
37
+ label: 'DOCX 解析 (mammoth)',
38
+ exts: ['.docx'],
39
+ async extract(filePath, opts = {}) {
40
+ const options = { styleMap: STYLE_MAP };
41
+ if (opts.embedImages) {
42
+ options.convertImage = mammoth.images.imgElement(img =>
43
+ img.read('base64').then(data => ({ src: `data:${img.contentType};base64,${data}` }))
44
+ );
45
+ } else {
46
+ // 丢弃图片:返回空 src,让 mammoth 跳过
47
+ options.convertImage = mammoth.images.imgElement(() => ({ src: '' }));
48
+ }
49
+ const result = await mammoth.convertToMarkdown({ path: filePath }, options);
50
+ return result.value;
51
+ },
52
+ async extractMeta(filePath) {
53
+ try {
54
+ const buffer = fs.readFileSync(filePath);
55
+ const zip = await JSZip.loadAsync(buffer);
56
+ const coreFile = zip.file('docProps/core.xml');
57
+ const appFile = zip.file('docProps/app.xml');
58
+ const meta = {};
59
+ if (coreFile) {
60
+ const xml = await coreFile.async('string');
61
+ meta.title = pickXmlField(xml, 'dc:title');
62
+ meta.author = pickXmlField(xml, 'dc:creator');
63
+ }
64
+ if (appFile) {
65
+ const xml = await appFile.async('string');
66
+ const pages = pickXmlField(xml, 'Pages');
67
+ if (pages) meta.pages = parseInt(pages, 10);
68
+ }
69
+ return meta;
70
+ } catch {
71
+ return {};
72
+ }
73
+ },
74
+ };
@@ -0,0 +1,42 @@
1
+ /**
2
+ * EPUB 电子书解析策略
3
+ */
4
+ const EPub = require('epub');
5
+ const cheerio = require('cheerio');
6
+
7
+ module.exports = {
8
+ name: 'epub',
9
+ label: 'EPUB 电子书解析',
10
+ exts: ['.epub'],
11
+ priority: 10,
12
+ extract(filePath) {
13
+ return new Promise((resolve, reject) => {
14
+ const epub = new EPub(filePath);
15
+ epub.on('end', () => {
16
+ const chapters = epub.flow
17
+ .filter(ch => ch.id && epub.getChapter(ch.id))
18
+ .map(ch => {
19
+ const $ = cheerio.load(epub.getChapter(ch.id));
20
+ return $.text().trim();
21
+ });
22
+ resolve(chapters.join('\n\n'));
23
+ });
24
+ epub.on('error', reject);
25
+ epub.parse();
26
+ });
27
+ },
28
+ extractMeta(filePath) {
29
+ return new Promise((resolve) => {
30
+ const epub = new EPub(filePath);
31
+ epub.on('end', () => {
32
+ resolve({
33
+ title: epub.metadata.title,
34
+ author: epub.metadata.creator,
35
+ pages: epub.flow.length,
36
+ });
37
+ });
38
+ epub.on('error', () => resolve({}));
39
+ epub.parse();
40
+ });
41
+ },
42
+ };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * HTML 解析策略 (cheerio)
3
+ */
4
+ const fs = require('fs');
5
+ const cheerio = require('cheerio');
6
+ const iconv = require('iconv-lite');
7
+ const chardet = require('chardet');
8
+
9
+ const ENCODING_MAP = {
10
+ 'UTF-8': 'utf8', 'ASCII': 'ascii', 'ISO-8859-1': 'latin1',
11
+ 'GB2312': 'gb2312', 'GBK': 'gbk', 'BIG5': 'big5',
12
+ 'SHIFT_JIS': 'shiftjis', 'EUC-KR': 'euckr',
13
+ 'UTF-16LE': 'utf16le', 'UTF-16BE': 'utf16be',
14
+ };
15
+
16
+ function readWithEncoding(filePath) {
17
+ const buffer = fs.readFileSync(filePath);
18
+ const detected = chardet.detect(buffer);
19
+ const encoding = ENCODING_MAP[detected] || 'utf8';
20
+ try { return iconv.decode(buffer, encoding); }
21
+ catch { return buffer.toString('utf8'); }
22
+ }
23
+
24
+ module.exports = {
25
+ name: 'html',
26
+ label: 'HTML 解析 (cheerio)',
27
+ exts: ['.html', '.htm'],
28
+ priority: 10,
29
+ extract(filePath) {
30
+ const html = readWithEncoding(filePath);
31
+ const $ = cheerio.load(html);
32
+ $('script, style, noscript').remove();
33
+ return $('body').text().replace(/\s{2,}/g, '\n').trim();
34
+ },
35
+ };
@@ -0,0 +1,25 @@
1
+ /**
2
+ * 图片策略 —— OCR 占位
3
+ *
4
+ * 默认不可用,需要用户注入具体 OCR 实现。
5
+ * 提供两种接入方式:
6
+ * 1. 替换 extract/isAvailable 实现
7
+ * 2. 通过 registerStrategy 注册高优先级同名策略覆盖
8
+ *
9
+ * 示例(百度 OCR):
10
+ * registerStrategy({ name: 'image', priority: 20, isAvailable: () => true,
11
+ * extract: async (p) => baiduOCR(p) });
12
+ */
13
+
14
+ module.exports = {
15
+ name: 'image',
16
+ label: '图片 OCR(未配置)',
17
+ exts: ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff'],
18
+ priority: 0,
19
+ isAvailable() {
20
+ return false; // 默认不可用,需要用户注册实现
21
+ },
22
+ extract() {
23
+ throw new Error('OCR 策略未配置。请通过 registerStrategy 注册图片解析实现。');
24
+ },
25
+ };
@@ -0,0 +1,57 @@
1
+ /**
2
+ * OCR 策略 (tesseract.js)
3
+ *
4
+ * - 纯 JS 引擎,零外部依赖,支持 100+ 语言
5
+ * - worker 按语言缓存,复用避免重复加载语言包(扫描 PDF 多页提速明显)
6
+ * - 进程退出时自动清理
7
+ *
8
+ * 环境变量:
9
+ * TESSERACT_LANG 默认语言(默认 'chi_sim+eng')
10
+ * TESSERACT_CACHE_PATH 语言包缓存目录(Linux 容器建议设到 os.tmpdir() 下可写目录)
11
+ */
12
+ const path = require('path');
13
+ const os = require('os');
14
+ const { createWorker } = require('tesseract.js');
15
+
16
+ const workers = new Map(); // lang -> Promise<Worker>
17
+
18
+ function defaultCachePath() {
19
+ return process.env.TESSERACT_CACHE_PATH || path.join(os.tmpdir(), 'tesseract-cache');
20
+ }
21
+
22
+ function getWorker(lang) {
23
+ if (!workers.has(lang)) {
24
+ const p = createWorker(lang, undefined, {
25
+ cachePath: defaultCachePath(),
26
+ });
27
+ workers.set(lang, p);
28
+ }
29
+ return workers.get(lang);
30
+ }
31
+
32
+ async function terminateAll() {
33
+ for (const [lang, p] of workers.entries()) {
34
+ try { const w = await p; await w.terminate(); } catch { }
35
+ workers.delete(lang);
36
+ }
37
+ }
38
+
39
+ // 进程退出时清理
40
+ process.once('beforeExit', terminateAll);
41
+ process.once('SIGINT', () => { terminateAll().finally(() => process.exit(130)); });
42
+ process.once('SIGTERM', () => { terminateAll().finally(() => process.exit(143)); });
43
+
44
+ module.exports = {
45
+ name: 'ocr-tesseract',
46
+ label: 'OCR (Tesseract)',
47
+ exts: ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.tiff'],
48
+ priority: 15,
49
+ async extract(filePath, opts = {}) {
50
+ const lang = opts.lang || process.env.TESSERACT_LANG || 'chi_sim+eng';
51
+ const worker = await getWorker(lang);
52
+ const { data: { text } } = await worker.recognize(filePath);
53
+ return text.trim();
54
+ },
55
+ /** 显式释放 worker(测试或长进程清理时调) */
56
+ terminateAll,
57
+ };
@@ -0,0 +1,141 @@
1
+ /**
2
+ * PDF 解析策略 (pdf-parse)
3
+ *
4
+ * 扫描件自动降级 OCR:
5
+ * 1. sharp(需 vips 带 PDF 支持,多数发行版不带)
6
+ * 2. pdftoppm 命令行(poppler-utils)—— Linux 主流
7
+ *
8
+ * 都不可用时抛 SCANNED_PDF_NO_OCR_ENGINE。
9
+ */
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const os = require('os');
13
+ const crypto = require('crypto');
14
+ const { execFile } = require('child_process');
15
+ const { promisify } = require('util');
16
+ const pdfParse = require('pdf-parse');
17
+
18
+ const execFileAsync = promisify(execFile);
19
+
20
+ function tmpPath(prefix, ext) {
21
+ const rand = crypto.randomBytes(6).toString('hex');
22
+ return path.join(os.tmpdir(), `${prefix}_${process.pid}_${rand}${ext}`);
23
+ }
24
+
25
+ /** 用 sharp 渲染 PDF 第 N 页为 PNG。需要 vips 支持 PDF。 */
26
+ async function renderWithSharp(pdfPath, pageNum) {
27
+ let sharp;
28
+ try { sharp = require('sharp'); } catch { return null; }
29
+ try {
30
+ const outPath = tmpPath('pdf_page', '.png');
31
+ await sharp(pdfPath, { page: pageNum - 1, density: 200 }).png().toFile(outPath);
32
+ return outPath;
33
+ } catch {
34
+ return null; // sharp 装了但 vips 没编 PDF 支持
35
+ }
36
+ }
37
+
38
+ /**
39
+ * 用 pdftoppm 渲染 PDF 第 N 页为 PNG。
40
+ *
41
+ * pdftoppm 输出文件名为 `${prefix}-NNN.png`,N 的位数由 -l 决定。
42
+ * 为了拿到稳定的文件名,每次只渲染一页且使用独立 tmp 目录,
43
+ * 渲染完直接 readdir 找出生成的唯一 png 文件。
44
+ */
45
+ async function renderWithPdftoppm(pdfPath, pageNum) {
46
+ const tmpDir = path.join(os.tmpdir(), `pdf_ocr_${process.pid}_${crypto.randomBytes(4).toString('hex')}`);
47
+ fs.mkdirSync(tmpDir, { recursive: true });
48
+ const prefix = path.join(tmpDir, 'page');
49
+ try {
50
+ await execFileAsync(
51
+ 'pdftoppm',
52
+ ['-png', '-r', '200', '-f', String(pageNum), '-l', String(pageNum), pdfPath, prefix],
53
+ { timeout: 30000 },
54
+ );
55
+ const files = fs.readdirSync(tmpDir).filter(f => f.endsWith('.png'));
56
+ if (files.length === 0) return null;
57
+ return path.join(tmpDir, files[0]);
58
+ } catch {
59
+ try { fs.rmSync(tmpDir, { recursive: true, force: true }); } catch { }
60
+ return null;
61
+ }
62
+ }
63
+
64
+ async function renderPageToImage(pdfPath, pageNum) {
65
+ return (await renderWithSharp(pdfPath, pageNum))
66
+ || (await renderWithPdftoppm(pdfPath, pageNum));
67
+ }
68
+
69
+ /** 清理由 renderPageToImage 生成的临时图片或其所在目录 */
70
+ function cleanupRendered(imgPath) {
71
+ if (!imgPath) return;
72
+ try {
73
+ const dir = path.dirname(imgPath);
74
+ // 我们自己 mkdir 的临时目录名以 pdf_ocr_ 开头,整个删;sharp 路径单独删文件
75
+ if (path.basename(dir).startsWith('pdf_ocr_')) {
76
+ fs.rmSync(dir, { recursive: true, force: true });
77
+ } else {
78
+ fs.unlinkSync(imgPath);
79
+ }
80
+ } catch { /* 清理失败不阻断 */ }
81
+ }
82
+
83
+ module.exports = {
84
+ name: 'pdf-parse',
85
+ label: 'PDF 解析 (pdf-parse)',
86
+ exts: ['.pdf'],
87
+ priority: 20,
88
+ async extract(filePath, opts = {}) {
89
+ const buffer = fs.readFileSync(filePath);
90
+ const data = await pdfParse(buffer);
91
+ const text = (data.text || '').trim();
92
+
93
+ if (text) return text;
94
+
95
+ // 扫描件 → 找图片 OCR 策略(懒加载避免循环依赖)
96
+ const registry = require('./registry');
97
+ const ocrStrategy = registry.match('.jpg');
98
+ if (!ocrStrategy) {
99
+ throw Object.assign(
100
+ new Error('PDF 为扫描件,且未注册图片 OCR 策略'),
101
+ { code: 'SCANNED_PDF_NO_OCR_STRATEGY' },
102
+ );
103
+ }
104
+
105
+ const totalPages = data.numpages;
106
+ const results = [];
107
+ const failed = [];
108
+ for (let page = 1; page <= totalPages; page++) {
109
+ if (opts.onProgress) opts.onProgress(Math.floor((page - 1) / totalPages * 100));
110
+ const imgPath = await renderPageToImage(filePath, page);
111
+ if (!imgPath) { failed.push(page); continue; }
112
+ try {
113
+ const pageText = await ocrStrategy.extract(imgPath, opts);
114
+ if (pageText && pageText.trim()) results.push(`## 第 ${page} 页\n${pageText.trim()}`);
115
+ } catch (e) {
116
+ failed.push(page);
117
+ } finally {
118
+ cleanupRendered(imgPath);
119
+ }
120
+ }
121
+ if (opts.onProgress) opts.onProgress(100);
122
+
123
+ if (results.length === 0) {
124
+ throw Object.assign(
125
+ new Error('PDF 扫描件 OCR 失败:未生成任何页面图片。请安装 sharp(带 PDF 的 vips) 或 poppler-utils(pdftoppm)。'),
126
+ { code: 'SCANNED_PDF_NO_OCR_ENGINE', totalPages, failedPages: failed },
127
+ );
128
+ }
129
+
130
+ return results.join('\n\n');
131
+ },
132
+ async extractMeta(filePath) {
133
+ const buffer = fs.readFileSync(filePath);
134
+ const data = await pdfParse(buffer);
135
+ return {
136
+ pages: data.numpages,
137
+ author: data.info?.Author || null,
138
+ title: data.info?.Title || null,
139
+ };
140
+ },
141
+ };
@@ -0,0 +1,174 @@
1
+ /**
2
+ * PPTX 解析策略(直接解 OOXML zip,不依赖 textract)
3
+ *
4
+ * - 按 slide 顺序输出:## 第 N 页[: 标题] + 正文 + > 备注
5
+ * - 中文友好(Intl.Segmenter 仅用于必要时切分超长块)
6
+ * - 支持 notes(备注页)
7
+ */
8
+ const fs = require('fs');
9
+ const JSZip = require('jszip');
10
+ const { XMLParser } = require('fast-xml-parser');
11
+
12
+ const parser = new XMLParser({
13
+ ignoreAttributes: false,
14
+ attributeNamePrefix: '@_',
15
+ textNodeName: '#text',
16
+ parseTagValue: false,
17
+ trimValues: true,
18
+ });
19
+
20
+ function toArray(v) {
21
+ if (v == null) return [];
22
+ return Array.isArray(v) ? v : [v];
23
+ }
24
+
25
+ /**
26
+ * 收集节点下所有 a:t 文本,按 a:p 段落分组
27
+ */
28
+ function collectParagraphs(node) {
29
+ if (!node || typeof node !== 'object') return [];
30
+ const paragraphs = [];
31
+ const txBody = node['p:txBody'] || node['a:txBody'] || node['txBody'];
32
+ if (!txBody) return [];
33
+ for (const p of toArray(txBody['a:p'])) {
34
+ const runs = toArray(p['a:r']);
35
+ const parts = runs.map(r => {
36
+ const t = r['a:t'];
37
+ if (typeof t === 'string') return t;
38
+ if (t && typeof t === 'object') return t['#text'] || '';
39
+ return '';
40
+ });
41
+ // 段落级直接文本(无 run 包裹的情况)
42
+ if (typeof p['a:t'] === 'string') parts.push(p['a:t']);
43
+ const line = parts.join('').trim();
44
+ if (line) paragraphs.push(line);
45
+ }
46
+ return paragraphs;
47
+ }
48
+
49
+ /**
50
+ * 判断 sp 是否为标题占位符
51
+ */
52
+ function isTitleShape(sp) {
53
+ const ph = sp?.['p:nvSpPr']?.['p:nvPr']?.['p:ph'];
54
+ if (!ph) return false;
55
+ const type = ph['@_type'];
56
+ return type === 'title' || type === 'ctrTitle';
57
+ }
58
+
59
+ function extractSlide(json) {
60
+ const cSld = json?.['p:sld']?.['p:cSld'];
61
+ const spTree = cSld?.['p:spTree'];
62
+ if (!spTree) return { title: '', body: [] };
63
+
64
+ const sps = toArray(spTree['p:sp']);
65
+ let title = '';
66
+ const body = [];
67
+
68
+ for (const sp of sps) {
69
+ const paras = collectParagraphs(sp);
70
+ if (paras.length === 0) continue;
71
+ if (!title && isTitleShape(sp)) {
72
+ title = paras.join(' ');
73
+ } else {
74
+ body.push(...paras);
75
+ }
76
+ }
77
+
78
+ // 表格 (a:tbl) — 简单按行拼接
79
+ for (const gf of toArray(spTree['p:graphicFrame'])) {
80
+ const tbl = gf?.['a:graphic']?.['a:graphicData']?.['a:tbl'];
81
+ if (!tbl) continue;
82
+ for (const tr of toArray(tbl['a:tr'])) {
83
+ const cells = toArray(tr['a:tc']).map(tc => {
84
+ return collectParagraphs(tc).join(' ');
85
+ });
86
+ const row = cells.filter(Boolean).join(' | ');
87
+ if (row) body.push(`| ${row} |`);
88
+ }
89
+ }
90
+
91
+ return { title, body };
92
+ }
93
+
94
+ function extractNotes(json) {
95
+ const cSld = json?.['p:notes']?.['p:cSld'];
96
+ const spTree = cSld?.['p:spTree'];
97
+ if (!spTree) return '';
98
+ const sps = toArray(spTree['p:sp']);
99
+ const parts = [];
100
+ for (const sp of sps) {
101
+ // 跳过页码占位符
102
+ const ph = sp?.['p:nvSpPr']?.['p:nvPr']?.['p:ph'];
103
+ if (ph && ph['@_type'] === 'sldNum') continue;
104
+ parts.push(...collectParagraphs(sp));
105
+ }
106
+ return parts.join(' ').trim();
107
+ }
108
+
109
+ async function parsePptx(filePath) {
110
+ const buffer = fs.readFileSync(filePath);
111
+ const zip = await JSZip.loadAsync(buffer);
112
+
113
+ const slideEntries = Object.keys(zip.files)
114
+ .filter(p => /^ppt\/slides\/slide\d+\.xml$/.test(p))
115
+ .sort((a, b) => {
116
+ const na = parseInt(a.match(/slide(\d+)\.xml$/)[1], 10);
117
+ const nb = parseInt(b.match(/slide(\d+)\.xml$/)[1], 10);
118
+ return na - nb;
119
+ });
120
+
121
+ const out = [];
122
+ for (let i = 0; i < slideEntries.length; i++) {
123
+ const slidePath = slideEntries[i];
124
+ const xml = await zip.file(slidePath).async('string');
125
+ const json = parser.parse(xml);
126
+ const { title, body } = extractSlide(json);
127
+
128
+ // 备注
129
+ const notesPath = slidePath.replace('slides/slide', 'notesSlides/notesSlide');
130
+ let notes = '';
131
+ const notesFile = zip.file(notesPath);
132
+ if (notesFile) {
133
+ const notesXml = await notesFile.async('string');
134
+ notes = extractNotes(parser.parse(notesXml));
135
+ }
136
+
137
+ let md = `## 第 ${i + 1} 页${title ? `: ${title}` : ''}\n\n`;
138
+ if (body.length > 0) md += body.join('\n\n') + '\n\n';
139
+ if (notes) md += `> 备注: ${notes}\n\n`;
140
+ out.push(md);
141
+ }
142
+
143
+ return out.join('').trim();
144
+ }
145
+
146
+ module.exports = {
147
+ name: 'pptx',
148
+ label: 'PPTX 解析 (jszip 直解)',
149
+ exts: ['.pptx'],
150
+ priority: 20,
151
+ async extract(filePath) {
152
+ return parsePptx(filePath);
153
+ },
154
+ async extractMeta(filePath) {
155
+ try {
156
+ const buffer = fs.readFileSync(filePath);
157
+ const zip = await JSZip.loadAsync(buffer);
158
+ const coreFile = zip.file('docProps/core.xml');
159
+ const meta = {};
160
+ if (coreFile) {
161
+ const xml = await coreFile.async('string');
162
+ const titleM = xml.match(/<dc:title[^>]*>([\s\S]*?)<\/dc:title>/);
163
+ const authorM = xml.match(/<dc:creator[^>]*>([\s\S]*?)<\/dc:creator>/);
164
+ if (titleM) meta.title = titleM[1].trim();
165
+ if (authorM) meta.author = authorM[1].trim();
166
+ }
167
+ const slideCount = Object.keys(zip.files).filter(p => /^ppt\/slides\/slide\d+\.xml$/.test(p)).length;
168
+ if (slideCount > 0) meta.pages = slideCount;
169
+ return meta;
170
+ } catch {
171
+ return {};
172
+ }
173
+ },
174
+ };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 策略注册中心
3
+ *
4
+ * 支持按扩展名匹配、按名称查找、多策略优先级降级。
5
+ */
6
+
7
+ const strategies = [];
8
+
9
+ function register(strategy) {
10
+ if (!strategy.name || !strategy.extract) {
11
+ throw new Error('策略必须包含 name 和 extract 方法');
12
+ }
13
+ const idx = strategies.findIndex(s => s.name === strategy.name);
14
+ if (idx >= 0) strategies[idx] = strategy;
15
+ else strategies.push(strategy);
16
+ }
17
+
18
+ function get(name) { return strategies.find(s => s.name === name); }
19
+
20
+ function matchAll(ext) {
21
+ return strategies
22
+ .filter(s => s.exts && s.exts.includes(ext))
23
+ .sort((a, b) => (b.priority || 0) - (a.priority || 0));
24
+ }
25
+
26
+ function match(ext) {
27
+ const candidates = matchAll(ext);
28
+ for (const s of candidates) {
29
+ if (!s.isAvailable || s.isAvailable()) return s;
30
+ }
31
+ return candidates[0] || null;
32
+ }
33
+
34
+ function list() { return [...strategies]; }
35
+
36
+ // ── 内置策略 ──────────────────────────────────
37
+
38
+ register(require('./pdf'));
39
+ register(require('./docx'));
40
+ register(require('./doc'));
41
+ register(require('./xlsx'));
42
+ register(require('./ppt'));
43
+ register(require('./text'));
44
+ register(require('./html'));
45
+ register(require('./epub'));
46
+ register(require('./baidu-ocr'));
47
+ register(require('./ocr-tesseract'));
48
+ register(require('./image')); // OCR 扩展点
49
+ register(require('./audio')); // 音频占位
50
+ register(require('./video')); // 视频占位
51
+
52
+ module.exports = { register, get, match, matchAll, list };
@@ -0,0 +1,91 @@
1
+ /**
2
+ * 文本/标记文件解析策略
3
+ * 支持: MD, TXT, CSV, JSON
4
+ */
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const iconv = require('iconv-lite');
8
+ const chardet = require('chardet');
9
+ const { toMarkdownTable } = require('../format');
10
+
11
+ const ENCODING_MAP = {
12
+ 'UTF-8': 'utf8', 'ASCII': 'ascii', 'ISO-8859-1': 'latin1',
13
+ 'GB2312': 'gb2312', 'GBK': 'gbk', 'BIG5': 'big5',
14
+ 'SHIFT_JIS': 'shiftjis', 'EUC-KR': 'euckr',
15
+ 'UTF-16LE': 'utf16le', 'UTF-16BE': 'utf16be',
16
+ };
17
+
18
+ function readWithEncoding(filePath) {
19
+ const buffer = fs.readFileSync(filePath);
20
+ const detected = chardet.detect(buffer);
21
+ const encoding = ENCODING_MAP[detected] || 'utf8';
22
+ try {
23
+ return iconv.decode(buffer, encoding);
24
+ } catch {
25
+ return buffer.toString('utf8');
26
+ }
27
+ }
28
+
29
+ function parseCsv(raw) {
30
+ const sample = raw.split(/\r?\n/).slice(0, 5).join('\n');
31
+ const tabCount = (sample.match(/\t/g) || []).length;
32
+ const commaCount = (sample.match(/,/g) || []).length;
33
+ const delim = tabCount > commaCount ? '\t' : ',';
34
+
35
+ // 完整状态机:处理跨行的引号字段
36
+ const rows = [];
37
+ let row = [];
38
+ let cur = '';
39
+ let inQuote = false;
40
+ for (let i = 0; i < raw.length; i++) {
41
+ const c = raw[i];
42
+ if (inQuote) {
43
+ if (c === '"' && raw[i + 1] === '"') { cur += '"'; i++; }
44
+ else if (c === '"') { inQuote = false; }
45
+ else { cur += c; }
46
+ } else {
47
+ if (c === '"') inQuote = true;
48
+ else if (c === delim) { row.push(cur.trim()); cur = ''; }
49
+ else if (c === '\r') { /* skip */ }
50
+ else if (c === '\n') {
51
+ row.push(cur.trim());
52
+ if (row.some(v => v.length > 0)) rows.push(row);
53
+ row = []; cur = '';
54
+ } else cur += c;
55
+ }
56
+ }
57
+ if (cur.length > 0 || row.length > 0) {
58
+ row.push(cur.trim());
59
+ if (row.some(v => v.length > 0)) rows.push(row);
60
+ }
61
+ return rows;
62
+ }
63
+
64
+ function extractText(filePath, ext) {
65
+ const raw = readWithEncoding(filePath);
66
+
67
+ if (ext === '.csv') {
68
+ const data = parseCsv(raw);
69
+ return toMarkdownTable(data);
70
+ }
71
+
72
+ if (ext === '.json') {
73
+ try {
74
+ return JSON.stringify(JSON.parse(raw), null, 2);
75
+ } catch {
76
+ return raw; // 不是合法 JSON 时按原文返回
77
+ }
78
+ }
79
+
80
+ return raw;
81
+ }
82
+
83
+ module.exports = {
84
+ name: 'text',
85
+ label: '文本/MD/CSV/JSON 解析',
86
+ exts: ['.md', '.txt', '.csv', '.json'],
87
+ extract(filePath) {
88
+ const ext = path.extname(filePath).toLowerCase();
89
+ return extractText(filePath, ext);
90
+ },
91
+ };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * 视频转文字策略 —— 占位
3
+ *
4
+ * 需要用户通过 registerStrategy 注入具体实现。
5
+ *
6
+ * 示例(ffmpeg 抽音轨 → audio 策略):
7
+ * require('./audio'); // 确保已注册
8
+ * registerStrategy({
9
+ * name: 'video',
10
+ * exts: ['.mp4', '.mpeg', '.webm'],
11
+ * priority: 20,
12
+ * async extract(filePath) {
13
+ * const tmp = filePath + '.wav';
14
+ * await execAsync(`ffmpeg -i "${filePath}" -vn -ar 16000 -ac 1 "${tmp}"`);
15
+ * const text = await extractText(tmp); // 走 audio 策略
16
+ * fs.unlinkSync(tmp);
17
+ * return text;
18
+ * }
19
+ * });
20
+ */
21
+
22
+ module.exports = {
23
+ name: 'video',
24
+ label: '视频转文字(未配置)',
25
+ exts: ['.mp4', '.mpeg', '.webm'],
26
+ priority: 0,
27
+ isAvailable() { return false; },
28
+ extract() { throw new Error('视频转文字策略未配置'); },
29
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Excel 解析策略 (xlsx)
3
+ *
4
+ * 合并单元格自动填充内容、转义 Markdown 控制字符、长表截断。
5
+ * WPS / Microsoft Office 生成的 .xlsx / .xls 均支持。
6
+ * .ods / .wps 不支持。
7
+ */
8
+ const XLSX = require('xlsx');
9
+ const { escapeCell } = require('../format');
10
+
11
+ const MAX_ROWS = 100;
12
+
13
+ /**
14
+ * 合并单元格内容填充:取左上角值,覆盖整个合并范围
15
+ */
16
+ function fillMerged(sheet, data) {
17
+ const merges = sheet['!merges'] || [];
18
+ if (merges.length === 0) return data;
19
+
20
+ const filled = data.map(row => [...row]);
21
+ for (const m of merges) {
22
+ const topVal = data[m.s.r]?.[m.s.c];
23
+ if (topVal == null || topVal === '') continue;
24
+ for (let r = m.s.r; r <= m.e.r; r++) {
25
+ if (!filled[r]) filled[r] = [];
26
+ for (let c = m.s.c; c <= m.e.c; c++) {
27
+ filled[r][c] = topVal;
28
+ }
29
+ }
30
+ }
31
+ return filled;
32
+ }
33
+
34
+ module.exports = {
35
+ name: 'xlsx',
36
+ label: 'Excel 解析 (xlsx)',
37
+ exts: ['.xlsx', '.xls'],
38
+ extract(filePath) {
39
+ const workbook = XLSX.readFile(filePath);
40
+ let result = '';
41
+
42
+ workbook.SheetNames.forEach(name => {
43
+ const sheet = workbook.Sheets[name];
44
+ const raw = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: true });
45
+ if (raw.length === 0) return;
46
+
47
+ const allData = fillMerged(sheet, raw);
48
+ const truncated = allData.length > MAX_ROWS;
49
+ const visible = truncated ? allData.slice(0, MAX_ROWS) : allData;
50
+
51
+ result += `## ${name} (${allData.length} 行)\n\n`;
52
+ if (visible.length > 0 && visible[0].length > 1) {
53
+ const lines = visible.map(row => row.map(escapeCell));
54
+ result += `| ${lines[0].join(' | ')} |\n`;
55
+ result += `| ${lines[0].map(() => '---').join(' | ')} |\n`;
56
+ for (let i = 1; i < lines.length; i++) {
57
+ result += `| ${lines[i].join(' | ')} |\n`;
58
+ }
59
+ } else {
60
+ result += visible.map(r => r.join('\t')).join('\n');
61
+ }
62
+ result += '\n';
63
+ if (truncated) result += `> ⚠ 表格已截断,仅显示前 ${MAX_ROWS} 行(共 ${allData.length} 行)\n\n`;
64
+ });
65
+
66
+ return result.trim();
67
+ },
68
+ extractMeta(filePath) {
69
+ const workbook = XLSX.readFile(filePath);
70
+ return { pages: workbook.SheetNames.length, sheets: workbook.SheetNames };
71
+ },
72
+ };