dsh-pdf-workbench 1.3.1 → 1.3.3
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/LICENSE +21 -21
- package/README.md +199 -192
- package/client.js +1037 -451
- package/docs/RELEASE.md +119 -110
- package/icon.svg +6 -6
- package/package.json +9 -1
- package/screenshots.json +8 -8
- package/src/client/host-ui-entry.js +11 -0
- package/src/client/react-jsx-runtime.cjs +21 -0
- package/src/client/viewer.js +80 -80
- package/src/host/routes.js +2 -0
- package/src/host/update.js +10 -1
- package/tools/AGENTS.md +33 -33
- package/tools/README.md +138 -138
- package/tools/auto_chapters.py +122 -122
- package/tools/dsfile.mjs +198 -198
- package/tools/export_chapter.py +108 -108
- package/tools/export_page.py +91 -91
- package/tools/md2overlay.py +200 -200
- package/tools/md2tex.py +422 -422
- package/tools/node.cmd +3 -0
- package/tools/pdf_blocks.py +110 -110
- package/tools/pdf_fontsize.py +20 -20
- package/tools/pdf_merge.py +15 -15
- package/tools/pdf_pagesizes.py +8 -8
- package/tools/pdf_raster.py +21 -21
- package/tools/pdfkit.py +896 -896
- package/tools/py.cmd +3 -0
- package/tools/realign_overlay.py +248 -248
- package/tools/rebuild_overlay.py +55 -55
- package/tools/rename_chapters.py +93 -93
- package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
- package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
- package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
- package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
- package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -11
- package/vendor/cmaps/LICENSE.txt +36 -36
- package/vendor/fonts/excalifont/OFL.txt +98 -98
- package/vendor/fonts/zhhand/OFL.txt +99 -99
- package/vendor/host-ui.cjs +1719 -0
- package/vendor/host-ui.css +799 -0
- package/vendor/pdf.min.mjs +28 -28
- package/vendor/pdf.worker.min.mjs +28 -28
- package/vendor/pdfjs-LICENSE.txt +177 -177
- package/vendor/rough/LICENSE +21 -21
- package/vendor/rough/rough.mjs +1 -1
- package/vendor/wasm/LICENSE_JBIG2 +196 -196
- package/vendor/wasm/LICENSE_OPENJPEG +39 -39
- package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
- package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
- package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
- package/vendor/wasm/LICENSE_QCMS +21 -21
- package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
- package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
- package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
package/tools/dsfile.mjs
CHANGED
|
@@ -1,198 +1,198 @@
|
|
|
1
|
-
// 工具/dsfile.mjs —— 调用 DeepSeek Files API 做服务端 PDF 解析,并让 deepseek-flash 按指令转写
|
|
2
|
-
//
|
|
3
|
-
// 用法:
|
|
4
|
-
// node dsfile.mjs upload <pdf> [--purpose rich_layout_recognition|text_recognition] [--days 30]
|
|
5
|
-
// node dsfile.mjs ask --file-id <id> --prompt "<指令>" [--prompt-file <md>] [--thinking on|off]
|
|
6
|
-
// node dsfile.mjs run <pdf> --prompt "<指令>" [--purpose ...] [--thinking on|off]
|
|
7
|
-
// node dsfile.mjs list
|
|
8
|
-
//
|
|
9
|
-
// API key 取自环境变量 DEEPSEEK_API_KEY;缺失时回落到 ~/.dsh/.credentials.yaml 的 refs.DEEPSEEK_API_KEY。
|
|
10
|
-
// 全程不打印 key。上传的 file_id 缓存在 缓存/api_files.json,同一文件不重复上传。
|
|
11
|
-
|
|
12
|
-
import fs from 'node:fs';
|
|
13
|
-
import path from 'node:path';
|
|
14
|
-
import os from 'node:os';
|
|
15
|
-
import crypto from 'node:crypto';
|
|
16
|
-
import { fileURLToPath } from 'node:url';
|
|
17
|
-
|
|
18
|
-
const BASE = 'https://api.deepseek.com';
|
|
19
|
-
const MODEL = 'deepseek-flash';
|
|
20
|
-
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
21
|
-
const CACHE = path.join(HERE, '..', '缓存', 'api_files.json');
|
|
22
|
-
|
|
23
|
-
function die(msg, code = 1) {
|
|
24
|
-
console.error(`[dsfile] 错误: ${msg}`);
|
|
25
|
-
process.exit(code);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function loadKey() {
|
|
29
|
-
if (process.env.DEEPSEEK_API_KEY && process.env.DEEPSEEK_API_KEY.trim()) {
|
|
30
|
-
return process.env.DEEPSEEK_API_KEY.trim();
|
|
31
|
-
}
|
|
32
|
-
const cred = path.join(os.homedir(), '.dsh', '.credentials.yaml');
|
|
33
|
-
try {
|
|
34
|
-
const txt = fs.readFileSync(cred, 'utf8');
|
|
35
|
-
const m = txt.match(/DEEPSEEK_API_KEY\s*:\s*["']?([A-Za-z0-9_\-]+)["']?/);
|
|
36
|
-
if (m) return m[1];
|
|
37
|
-
} catch { /* ignore */ }
|
|
38
|
-
die('拿不到 API key:请设置环境变量 DEEPSEEK_API_KEY,或在 ~/.dsh/.credentials.yaml 里配置。', 2);
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
function args(argv) {
|
|
42
|
-
const a = { _: [] };
|
|
43
|
-
for (let i = 0; i < argv.length; i++) {
|
|
44
|
-
const t = argv[i];
|
|
45
|
-
if (t.startsWith('--')) {
|
|
46
|
-
const k = t.slice(2);
|
|
47
|
-
const nxt = argv[i + 1];
|
|
48
|
-
if (nxt === undefined || nxt.startsWith('--')) a[k] = true;
|
|
49
|
-
else { a[k] = nxt; i++; }
|
|
50
|
-
} else a._.push(t);
|
|
51
|
-
}
|
|
52
|
-
return a;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
function readCache() {
|
|
56
|
-
try { return JSON.parse(fs.readFileSync(CACHE, 'utf8')); } catch { return { formatVersion: 1, records: [] }; }
|
|
57
|
-
}
|
|
58
|
-
function writeCache(c) {
|
|
59
|
-
fs.mkdirSync(path.dirname(CACHE), { recursive: true });
|
|
60
|
-
const tmp = `${CACHE}.tmp${process.pid}`;
|
|
61
|
-
fs.writeFileSync(tmp, JSON.stringify(c, null, 2), 'utf8');
|
|
62
|
-
fs.renameSync(tmp, CACHE); // 原子替换,多窗口并发写不会截断
|
|
63
|
-
}
|
|
64
|
-
function fingerprint(file, purpose) {
|
|
65
|
-
const st = fs.statSync(file);
|
|
66
|
-
const h = crypto.createHash('sha256');
|
|
67
|
-
h.update(`${path.resolve(file)}|${st.size}|${st.mtimeMs}|${purpose}`);
|
|
68
|
-
return h.digest('hex');
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async function api(pathname, opts = {}) {
|
|
72
|
-
const key = loadKey();
|
|
73
|
-
const r = await fetch(BASE + pathname, {
|
|
74
|
-
...opts,
|
|
75
|
-
headers: { Authorization: `Bearer ${key}`, ...(opts.headers || {}) },
|
|
76
|
-
signal: AbortSignal.timeout(opts.timeout || 300000),
|
|
77
|
-
});
|
|
78
|
-
const text = await r.text();
|
|
79
|
-
if (!r.ok) die(`HTTP ${r.status} ${pathname}\n${text.slice(0, 1200)}`, 3);
|
|
80
|
-
try { return JSON.parse(text); }
|
|
81
|
-
catch { die(`返回不是 JSON:${text.slice(0, 800)}`, 3); }
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
async function upload(a, quiet = false) {
|
|
85
|
-
const emit = (o) => {
|
|
86
|
-
if (quiet && !a.verbose) return;
|
|
87
|
-
const s = JSON.stringify(o, null, 2);
|
|
88
|
-
if (quiet) console.error(s); else console.log(s);
|
|
89
|
-
};
|
|
90
|
-
const file = a._[1];
|
|
91
|
-
if (!file) die('用法: upload <pdf> [--purpose ...]', 2);
|
|
92
|
-
if (!fs.existsSync(file)) die(`文件不存在: ${file}`, 2);
|
|
93
|
-
const purpose = a.purpose || 'rich_layout_recognition';
|
|
94
|
-
if (!['rich_layout_recognition', 'text_recognition', 'user_data'].includes(purpose))
|
|
95
|
-
die(`purpose 只能是 rich_layout_recognition / text_recognition / user_data`, 2);
|
|
96
|
-
|
|
97
|
-
const fp = fingerprint(file, purpose);
|
|
98
|
-
const cache = readCache();
|
|
99
|
-
const hit = cache.records.find((r) => r.fingerprint === fp);
|
|
100
|
-
if (hit && (!hit.expiresAt || hit.expiresAt > Date.now())) {
|
|
101
|
-
emit({ ok: true, cached: true, ...hit });
|
|
102
|
-
return hit;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const form = new FormData();
|
|
106
|
-
form.append('purpose', purpose); // 必须先于 file
|
|
107
|
-
if (a.days) {
|
|
108
|
-
form.append('expires_after[anchor]', 'created_at');
|
|
109
|
-
form.append('expires_after[seconds]', String(Math.round(Number(a.days) * 86400)));
|
|
110
|
-
}
|
|
111
|
-
form.append('file', await fs.openAsBlob(file), path.basename(file));
|
|
112
|
-
|
|
113
|
-
process.stderr.write(`[dsfile] 上传并解析 ${path.basename(file)}(purpose=${purpose}),大文件可能需要 1-2 分钟…\n`);
|
|
114
|
-
const res = await api('/files', { method: 'POST', body: form, timeout: 600000 });
|
|
115
|
-
|
|
116
|
-
const rec = {
|
|
117
|
-
fingerprint: fp,
|
|
118
|
-
file: path.resolve(file),
|
|
119
|
-
purpose,
|
|
120
|
-
fileId: res.id,
|
|
121
|
-
bytes: res.bytes,
|
|
122
|
-
pages_hint: null,
|
|
123
|
-
createdAt: res.created_at,
|
|
124
|
-
expiresAt: res.expires_at || (a.days ? res.created_at + Number(a.days) * 86400 : null),
|
|
125
|
-
};
|
|
126
|
-
cache.records = cache.records.filter((r) => r.fingerprint !== fp).concat([rec]);
|
|
127
|
-
writeCache(cache);
|
|
128
|
-
emit({ ok: true, cached: false, ...rec });
|
|
129
|
-
return rec;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function buildPrompt(a) {
|
|
133
|
-
let prompt = a.prompt;
|
|
134
|
-
if (!prompt && a['prompt-file']) prompt = fs.readFileSync(a['prompt-file'], 'utf8');
|
|
135
|
-
if (!prompt) return null;
|
|
136
|
-
if (a.pages) prompt = `只处理第 ${a.pages} 页(其余页一律忽略,不要输出)。\n\n` + prompt;
|
|
137
|
-
return prompt;
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
async function ask(a) {
|
|
141
|
-
const fileId = a['file-id'];
|
|
142
|
-
if (!fileId) die('用法: ask --file-id <id> --prompt "<指令>"', 2);
|
|
143
|
-
const prompt = buildPrompt(a);
|
|
144
|
-
if (!prompt) die('缺少 --prompt 或 --prompt-file', 2);
|
|
145
|
-
|
|
146
|
-
const body = {
|
|
147
|
-
model: MODEL,
|
|
148
|
-
messages: [{
|
|
149
|
-
role: 'user',
|
|
150
|
-
content: [
|
|
151
|
-
{ type: 'file', file_id: fileId },
|
|
152
|
-
{ type: 'text', text: prompt },
|
|
153
|
-
],
|
|
154
|
-
}],
|
|
155
|
-
max_tokens: Number(a['max-tokens'] || 16000),
|
|
156
|
-
};
|
|
157
|
-
if (a.thinking === 'off') body.thinking = { type: 'disabled' };
|
|
158
|
-
if (a.thinking === 'on') body.thinking = { type: 'enabled' };
|
|
159
|
-
|
|
160
|
-
const res = await api('/chat/completions', {
|
|
161
|
-
method: 'POST',
|
|
162
|
-
headers: { 'Content-Type': 'application/json' },
|
|
163
|
-
body: JSON.stringify(body),
|
|
164
|
-
});
|
|
165
|
-
const msg = res.choices?.[0]?.message || {};
|
|
166
|
-
const out = { text: msg.content || '', usage: res.usage || null, thinking: !!msg.reasoning_content };
|
|
167
|
-
if (a.json) console.log(JSON.stringify(out, null, 2));
|
|
168
|
-
else {
|
|
169
|
-
process.stdout.write(out.text);
|
|
170
|
-
if (a.usage) console.error(`[dsfile] usage: ${JSON.stringify(out.usage)}`);
|
|
171
|
-
}
|
|
172
|
-
return out;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
async function run(a) {
|
|
176
|
-
const file = a._[1];
|
|
177
|
-
if (!file) die('用法: run <pdf> --prompt "<指令>"', 2);
|
|
178
|
-
const prompt = buildPrompt(a);
|
|
179
|
-
if (!prompt) die('缺少 --prompt 或 --prompt-file', 2);
|
|
180
|
-
const rec = await upload({ ...a, _: ['upload', file] }, true);
|
|
181
|
-
return ask({ ...a, 'file-id': rec.fileId, prompt });
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
async function list() {
|
|
185
|
-
const res = await api('/files?limit=50&order=desc');
|
|
186
|
-
console.log(JSON.stringify(res, null, 2));
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
const a = args(process.argv.slice(2));
|
|
190
|
-
const cmd = a._[0];
|
|
191
|
-
if (cmd === 'upload') await upload(a);
|
|
192
|
-
else if (cmd === 'ask') await ask(a);
|
|
193
|
-
else if (cmd === 'run') await run(a);
|
|
194
|
-
else if (cmd === 'list') await list();
|
|
195
|
-
else {
|
|
196
|
-
console.error('子命令: upload | ask | run | list');
|
|
197
|
-
process.exit(2);
|
|
198
|
-
}
|
|
1
|
+
// 工具/dsfile.mjs —— 调用 DeepSeek Files API 做服务端 PDF 解析,并让 deepseek-flash 按指令转写
|
|
2
|
+
//
|
|
3
|
+
// 用法:
|
|
4
|
+
// node dsfile.mjs upload <pdf> [--purpose rich_layout_recognition|text_recognition] [--days 30]
|
|
5
|
+
// node dsfile.mjs ask --file-id <id> --prompt "<指令>" [--prompt-file <md>] [--thinking on|off]
|
|
6
|
+
// node dsfile.mjs run <pdf> --prompt "<指令>" [--purpose ...] [--thinking on|off]
|
|
7
|
+
// node dsfile.mjs list
|
|
8
|
+
//
|
|
9
|
+
// API key 取自环境变量 DEEPSEEK_API_KEY;缺失时回落到 ~/.dsh/.credentials.yaml 的 refs.DEEPSEEK_API_KEY。
|
|
10
|
+
// 全程不打印 key。上传的 file_id 缓存在 缓存/api_files.json,同一文件不重复上传。
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
|
|
18
|
+
const BASE = 'https://api.deepseek.com';
|
|
19
|
+
const MODEL = 'deepseek-flash';
|
|
20
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
21
|
+
const CACHE = path.join(HERE, '..', '缓存', 'api_files.json');
|
|
22
|
+
|
|
23
|
+
function die(msg, code = 1) {
|
|
24
|
+
console.error(`[dsfile] 错误: ${msg}`);
|
|
25
|
+
process.exit(code);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function loadKey() {
|
|
29
|
+
if (process.env.DEEPSEEK_API_KEY && process.env.DEEPSEEK_API_KEY.trim()) {
|
|
30
|
+
return process.env.DEEPSEEK_API_KEY.trim();
|
|
31
|
+
}
|
|
32
|
+
const cred = path.join(os.homedir(), '.dsh', '.credentials.yaml');
|
|
33
|
+
try {
|
|
34
|
+
const txt = fs.readFileSync(cred, 'utf8');
|
|
35
|
+
const m = txt.match(/DEEPSEEK_API_KEY\s*:\s*["']?([A-Za-z0-9_\-]+)["']?/);
|
|
36
|
+
if (m) return m[1];
|
|
37
|
+
} catch { /* ignore */ }
|
|
38
|
+
die('拿不到 API key:请设置环境变量 DEEPSEEK_API_KEY,或在 ~/.dsh/.credentials.yaml 里配置。', 2);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function args(argv) {
|
|
42
|
+
const a = { _: [] };
|
|
43
|
+
for (let i = 0; i < argv.length; i++) {
|
|
44
|
+
const t = argv[i];
|
|
45
|
+
if (t.startsWith('--')) {
|
|
46
|
+
const k = t.slice(2);
|
|
47
|
+
const nxt = argv[i + 1];
|
|
48
|
+
if (nxt === undefined || nxt.startsWith('--')) a[k] = true;
|
|
49
|
+
else { a[k] = nxt; i++; }
|
|
50
|
+
} else a._.push(t);
|
|
51
|
+
}
|
|
52
|
+
return a;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function readCache() {
|
|
56
|
+
try { return JSON.parse(fs.readFileSync(CACHE, 'utf8')); } catch { return { formatVersion: 1, records: [] }; }
|
|
57
|
+
}
|
|
58
|
+
function writeCache(c) {
|
|
59
|
+
fs.mkdirSync(path.dirname(CACHE), { recursive: true });
|
|
60
|
+
const tmp = `${CACHE}.tmp${process.pid}`;
|
|
61
|
+
fs.writeFileSync(tmp, JSON.stringify(c, null, 2), 'utf8');
|
|
62
|
+
fs.renameSync(tmp, CACHE); // 原子替换,多窗口并发写不会截断
|
|
63
|
+
}
|
|
64
|
+
function fingerprint(file, purpose) {
|
|
65
|
+
const st = fs.statSync(file);
|
|
66
|
+
const h = crypto.createHash('sha256');
|
|
67
|
+
h.update(`${path.resolve(file)}|${st.size}|${st.mtimeMs}|${purpose}`);
|
|
68
|
+
return h.digest('hex');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function api(pathname, opts = {}) {
|
|
72
|
+
const key = loadKey();
|
|
73
|
+
const r = await fetch(BASE + pathname, {
|
|
74
|
+
...opts,
|
|
75
|
+
headers: { Authorization: `Bearer ${key}`, ...(opts.headers || {}) },
|
|
76
|
+
signal: AbortSignal.timeout(opts.timeout || 300000),
|
|
77
|
+
});
|
|
78
|
+
const text = await r.text();
|
|
79
|
+
if (!r.ok) die(`HTTP ${r.status} ${pathname}\n${text.slice(0, 1200)}`, 3);
|
|
80
|
+
try { return JSON.parse(text); }
|
|
81
|
+
catch { die(`返回不是 JSON:${text.slice(0, 800)}`, 3); }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function upload(a, quiet = false) {
|
|
85
|
+
const emit = (o) => {
|
|
86
|
+
if (quiet && !a.verbose) return;
|
|
87
|
+
const s = JSON.stringify(o, null, 2);
|
|
88
|
+
if (quiet) console.error(s); else console.log(s);
|
|
89
|
+
};
|
|
90
|
+
const file = a._[1];
|
|
91
|
+
if (!file) die('用法: upload <pdf> [--purpose ...]', 2);
|
|
92
|
+
if (!fs.existsSync(file)) die(`文件不存在: ${file}`, 2);
|
|
93
|
+
const purpose = a.purpose || 'rich_layout_recognition';
|
|
94
|
+
if (!['rich_layout_recognition', 'text_recognition', 'user_data'].includes(purpose))
|
|
95
|
+
die(`purpose 只能是 rich_layout_recognition / text_recognition / user_data`, 2);
|
|
96
|
+
|
|
97
|
+
const fp = fingerprint(file, purpose);
|
|
98
|
+
const cache = readCache();
|
|
99
|
+
const hit = cache.records.find((r) => r.fingerprint === fp);
|
|
100
|
+
if (hit && (!hit.expiresAt || hit.expiresAt > Date.now())) {
|
|
101
|
+
emit({ ok: true, cached: true, ...hit });
|
|
102
|
+
return hit;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const form = new FormData();
|
|
106
|
+
form.append('purpose', purpose); // 必须先于 file
|
|
107
|
+
if (a.days) {
|
|
108
|
+
form.append('expires_after[anchor]', 'created_at');
|
|
109
|
+
form.append('expires_after[seconds]', String(Math.round(Number(a.days) * 86400)));
|
|
110
|
+
}
|
|
111
|
+
form.append('file', await fs.openAsBlob(file), path.basename(file));
|
|
112
|
+
|
|
113
|
+
process.stderr.write(`[dsfile] 上传并解析 ${path.basename(file)}(purpose=${purpose}),大文件可能需要 1-2 分钟…\n`);
|
|
114
|
+
const res = await api('/files', { method: 'POST', body: form, timeout: 600000 });
|
|
115
|
+
|
|
116
|
+
const rec = {
|
|
117
|
+
fingerprint: fp,
|
|
118
|
+
file: path.resolve(file),
|
|
119
|
+
purpose,
|
|
120
|
+
fileId: res.id,
|
|
121
|
+
bytes: res.bytes,
|
|
122
|
+
pages_hint: null,
|
|
123
|
+
createdAt: res.created_at,
|
|
124
|
+
expiresAt: res.expires_at || (a.days ? res.created_at + Number(a.days) * 86400 : null),
|
|
125
|
+
};
|
|
126
|
+
cache.records = cache.records.filter((r) => r.fingerprint !== fp).concat([rec]);
|
|
127
|
+
writeCache(cache);
|
|
128
|
+
emit({ ok: true, cached: false, ...rec });
|
|
129
|
+
return rec;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function buildPrompt(a) {
|
|
133
|
+
let prompt = a.prompt;
|
|
134
|
+
if (!prompt && a['prompt-file']) prompt = fs.readFileSync(a['prompt-file'], 'utf8');
|
|
135
|
+
if (!prompt) return null;
|
|
136
|
+
if (a.pages) prompt = `只处理第 ${a.pages} 页(其余页一律忽略,不要输出)。\n\n` + prompt;
|
|
137
|
+
return prompt;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function ask(a) {
|
|
141
|
+
const fileId = a['file-id'];
|
|
142
|
+
if (!fileId) die('用法: ask --file-id <id> --prompt "<指令>"', 2);
|
|
143
|
+
const prompt = buildPrompt(a);
|
|
144
|
+
if (!prompt) die('缺少 --prompt 或 --prompt-file', 2);
|
|
145
|
+
|
|
146
|
+
const body = {
|
|
147
|
+
model: MODEL,
|
|
148
|
+
messages: [{
|
|
149
|
+
role: 'user',
|
|
150
|
+
content: [
|
|
151
|
+
{ type: 'file', file_id: fileId },
|
|
152
|
+
{ type: 'text', text: prompt },
|
|
153
|
+
],
|
|
154
|
+
}],
|
|
155
|
+
max_tokens: Number(a['max-tokens'] || 16000),
|
|
156
|
+
};
|
|
157
|
+
if (a.thinking === 'off') body.thinking = { type: 'disabled' };
|
|
158
|
+
if (a.thinking === 'on') body.thinking = { type: 'enabled' };
|
|
159
|
+
|
|
160
|
+
const res = await api('/chat/completions', {
|
|
161
|
+
method: 'POST',
|
|
162
|
+
headers: { 'Content-Type': 'application/json' },
|
|
163
|
+
body: JSON.stringify(body),
|
|
164
|
+
});
|
|
165
|
+
const msg = res.choices?.[0]?.message || {};
|
|
166
|
+
const out = { text: msg.content || '', usage: res.usage || null, thinking: !!msg.reasoning_content };
|
|
167
|
+
if (a.json) console.log(JSON.stringify(out, null, 2));
|
|
168
|
+
else {
|
|
169
|
+
process.stdout.write(out.text);
|
|
170
|
+
if (a.usage) console.error(`[dsfile] usage: ${JSON.stringify(out.usage)}`);
|
|
171
|
+
}
|
|
172
|
+
return out;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
async function run(a) {
|
|
176
|
+
const file = a._[1];
|
|
177
|
+
if (!file) die('用法: run <pdf> --prompt "<指令>"', 2);
|
|
178
|
+
const prompt = buildPrompt(a);
|
|
179
|
+
if (!prompt) die('缺少 --prompt 或 --prompt-file', 2);
|
|
180
|
+
const rec = await upload({ ...a, _: ['upload', file] }, true);
|
|
181
|
+
return ask({ ...a, 'file-id': rec.fileId, prompt });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function list() {
|
|
185
|
+
const res = await api('/files?limit=50&order=desc');
|
|
186
|
+
console.log(JSON.stringify(res, null, 2));
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const a = args(process.argv.slice(2));
|
|
190
|
+
const cmd = a._[0];
|
|
191
|
+
if (cmd === 'upload') await upload(a);
|
|
192
|
+
else if (cmd === 'ask') await ask(a);
|
|
193
|
+
else if (cmd === 'run') await run(a);
|
|
194
|
+
else if (cmd === 'list') await list();
|
|
195
|
+
else {
|
|
196
|
+
console.error('子命令: upload | ask | run | list');
|
|
197
|
+
process.exit(2);
|
|
198
|
+
}
|
package/tools/export_chapter.py
CHANGED
|
@@ -1,108 +1,108 @@
|
|
|
1
|
-
"""Compose a whole chapter: every page with its revealed translation + annotations.
|
|
2
|
-
|
|
3
|
-
Usage:
|
|
4
|
-
python export_chapter.py <source.pdf> <overlay.pdf|-> <spec.json> <out.pdf>
|
|
5
|
-
|
|
6
|
-
`spec.json` is `{"pages":[{"page":3,"masks":[...],"annots":[...]}, ...]}`; pages not
|
|
7
|
-
listed are exported as the plain original page. Coordinates are normalized.
|
|
8
|
-
"""
|
|
9
|
-
import json
|
|
10
|
-
import os
|
|
11
|
-
import sys
|
|
12
|
-
|
|
13
|
-
import fitz
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
def rgb(value, fallback=(0.12, 0.12, 0.12)):
|
|
17
|
-
text = str(value or "").strip().lstrip("#")
|
|
18
|
-
if len(text) == 3:
|
|
19
|
-
text = "".join(char * 2 for char in text)
|
|
20
|
-
if len(text) != 6:
|
|
21
|
-
return fallback
|
|
22
|
-
try:
|
|
23
|
-
return tuple(int(text[index:index + 2], 16) / 255.0 for index in (0, 2, 4))
|
|
24
|
-
except ValueError:
|
|
25
|
-
return fallback
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
source_path, overlay_path, spec_path, out_path = sys.argv[1:5]
|
|
29
|
-
progress_path = sys.argv[5] if len(sys.argv) > 5 else ""
|
|
30
|
-
with open(spec_path, encoding="utf-8-sig") as handle:
|
|
31
|
-
spec = json.load(handle)
|
|
32
|
-
pages = spec.get("pages") if isinstance(spec, dict) else None
|
|
33
|
-
if not isinstance(pages, list):
|
|
34
|
-
pages = []
|
|
35
|
-
by_page = {}
|
|
36
|
-
for item in pages:
|
|
37
|
-
try:
|
|
38
|
-
by_page[int(item.get("page"))] = item
|
|
39
|
-
except (TypeError, ValueError):
|
|
40
|
-
continue
|
|
41
|
-
|
|
42
|
-
source = fitz.open(source_path)
|
|
43
|
-
overlay = fitz.open(overlay_path) if overlay_path != "-" and os.path.exists(overlay_path) else None
|
|
44
|
-
doc = fitz.open()
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
def write_progress(payload):
|
|
48
|
-
if progress_path == "":
|
|
49
|
-
return
|
|
50
|
-
with open(progress_path, "w", encoding="utf-8") as handle:
|
|
51
|
-
json.dump(payload, handle)
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
write_progress({"status": "running", "done": 0, "total": source.page_count})
|
|
55
|
-
|
|
56
|
-
for index in range(source.page_count):
|
|
57
|
-
if progress_path != "" and os.path.exists(progress_path + ".cancel"):
|
|
58
|
-
write_progress({"status": "cancelled", "done": index, "total": source.page_count})
|
|
59
|
-
sys.exit(0)
|
|
60
|
-
item = by_page.get(index + 1, {})
|
|
61
|
-
page = doc.new_page(width=source[0].rect.width, height=source[index].rect.height)
|
|
62
|
-
box = page.rect
|
|
63
|
-
page.show_pdf_page(box, source, index)
|
|
64
|
-
|
|
65
|
-
if overlay is not None and index < overlay.page_count:
|
|
66
|
-
for mask in item.get("masks") or []:
|
|
67
|
-
try:
|
|
68
|
-
rect = fitz.Rect(
|
|
69
|
-
float(mask["x"]) * box.width,
|
|
70
|
-
float(mask["y"]) * box.height,
|
|
71
|
-
(float(mask["x"]) + float(mask["w"])) * box.width,
|
|
72
|
-
(float(mask["y"]) + float(mask["h"])) * box.height,
|
|
73
|
-
)
|
|
74
|
-
except (KeyError, TypeError, ValueError):
|
|
75
|
-
continue
|
|
76
|
-
if rect.is_empty or rect.width <= 1 or rect.height <= 1:
|
|
77
|
-
continue
|
|
78
|
-
page.show_pdf_page(rect, overlay, index, clip=rect)
|
|
79
|
-
|
|
80
|
-
for entry in item.get("annots") or []:
|
|
81
|
-
color = rgb(entry.get("color"))
|
|
82
|
-
if entry.get("kind") == "text":
|
|
83
|
-
text = str(entry.get("text") or "")
|
|
84
|
-
if text.strip() == "":
|
|
85
|
-
continue
|
|
86
|
-
x = float(entry.get("x", 0)) * box.width
|
|
87
|
-
y = float(entry.get("y", 0)) * box.height
|
|
88
|
-
for offset, line in enumerate(text.split("\n")):
|
|
89
|
-
page.insert_text((x, y + 14 + offset * 18), line, fontsize=14,
|
|
90
|
-
fontname="china-s", color=color)
|
|
91
|
-
continue
|
|
92
|
-
points = [
|
|
93
|
-
fitz.Point(float(point[0]) * box.width, float(point[1]) * box.height)
|
|
94
|
-
for point in entry.get("points") or []
|
|
95
|
-
if isinstance(point, (list, tuple)) and len(point) >= 2
|
|
96
|
-
]
|
|
97
|
-
if len(points) < 2:
|
|
98
|
-
continue
|
|
99
|
-
page.draw_polyline(points, color=color, width=float(entry.get("width") or 2),
|
|
100
|
-
lineCap=1, lineJoin=1, overlay=True)
|
|
101
|
-
|
|
102
|
-
write_progress({"status": "running", "done": index + 1, "total": source.page_count})
|
|
103
|
-
|
|
104
|
-
tmp = out_path + ".tmp.pdf"
|
|
105
|
-
doc.save(tmp)
|
|
106
|
-
os.replace(tmp, out_path)
|
|
107
|
-
write_progress({"status": "done", "done": source.page_count, "total": source.page_count})
|
|
108
|
-
print(out_path)
|
|
1
|
+
"""Compose a whole chapter: every page with its revealed translation + annotations.
|
|
2
|
+
|
|
3
|
+
Usage:
|
|
4
|
+
python export_chapter.py <source.pdf> <overlay.pdf|-> <spec.json> <out.pdf>
|
|
5
|
+
|
|
6
|
+
`spec.json` is `{"pages":[{"page":3,"masks":[...],"annots":[...]}, ...]}`; pages not
|
|
7
|
+
listed are exported as the plain original page. Coordinates are normalized.
|
|
8
|
+
"""
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
|
|
13
|
+
import fitz
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def rgb(value, fallback=(0.12, 0.12, 0.12)):
|
|
17
|
+
text = str(value or "").strip().lstrip("#")
|
|
18
|
+
if len(text) == 3:
|
|
19
|
+
text = "".join(char * 2 for char in text)
|
|
20
|
+
if len(text) != 6:
|
|
21
|
+
return fallback
|
|
22
|
+
try:
|
|
23
|
+
return tuple(int(text[index:index + 2], 16) / 255.0 for index in (0, 2, 4))
|
|
24
|
+
except ValueError:
|
|
25
|
+
return fallback
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
source_path, overlay_path, spec_path, out_path = sys.argv[1:5]
|
|
29
|
+
progress_path = sys.argv[5] if len(sys.argv) > 5 else ""
|
|
30
|
+
with open(spec_path, encoding="utf-8-sig") as handle:
|
|
31
|
+
spec = json.load(handle)
|
|
32
|
+
pages = spec.get("pages") if isinstance(spec, dict) else None
|
|
33
|
+
if not isinstance(pages, list):
|
|
34
|
+
pages = []
|
|
35
|
+
by_page = {}
|
|
36
|
+
for item in pages:
|
|
37
|
+
try:
|
|
38
|
+
by_page[int(item.get("page"))] = item
|
|
39
|
+
except (TypeError, ValueError):
|
|
40
|
+
continue
|
|
41
|
+
|
|
42
|
+
source = fitz.open(source_path)
|
|
43
|
+
overlay = fitz.open(overlay_path) if overlay_path != "-" and os.path.exists(overlay_path) else None
|
|
44
|
+
doc = fitz.open()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def write_progress(payload):
|
|
48
|
+
if progress_path == "":
|
|
49
|
+
return
|
|
50
|
+
with open(progress_path, "w", encoding="utf-8") as handle:
|
|
51
|
+
json.dump(payload, handle)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
write_progress({"status": "running", "done": 0, "total": source.page_count})
|
|
55
|
+
|
|
56
|
+
for index in range(source.page_count):
|
|
57
|
+
if progress_path != "" and os.path.exists(progress_path + ".cancel"):
|
|
58
|
+
write_progress({"status": "cancelled", "done": index, "total": source.page_count})
|
|
59
|
+
sys.exit(0)
|
|
60
|
+
item = by_page.get(index + 1, {})
|
|
61
|
+
page = doc.new_page(width=source[0].rect.width, height=source[index].rect.height)
|
|
62
|
+
box = page.rect
|
|
63
|
+
page.show_pdf_page(box, source, index)
|
|
64
|
+
|
|
65
|
+
if overlay is not None and index < overlay.page_count:
|
|
66
|
+
for mask in item.get("masks") or []:
|
|
67
|
+
try:
|
|
68
|
+
rect = fitz.Rect(
|
|
69
|
+
float(mask["x"]) * box.width,
|
|
70
|
+
float(mask["y"]) * box.height,
|
|
71
|
+
(float(mask["x"]) + float(mask["w"])) * box.width,
|
|
72
|
+
(float(mask["y"]) + float(mask["h"])) * box.height,
|
|
73
|
+
)
|
|
74
|
+
except (KeyError, TypeError, ValueError):
|
|
75
|
+
continue
|
|
76
|
+
if rect.is_empty or rect.width <= 1 or rect.height <= 1:
|
|
77
|
+
continue
|
|
78
|
+
page.show_pdf_page(rect, overlay, index, clip=rect)
|
|
79
|
+
|
|
80
|
+
for entry in item.get("annots") or []:
|
|
81
|
+
color = rgb(entry.get("color"))
|
|
82
|
+
if entry.get("kind") == "text":
|
|
83
|
+
text = str(entry.get("text") or "")
|
|
84
|
+
if text.strip() == "":
|
|
85
|
+
continue
|
|
86
|
+
x = float(entry.get("x", 0)) * box.width
|
|
87
|
+
y = float(entry.get("y", 0)) * box.height
|
|
88
|
+
for offset, line in enumerate(text.split("\n")):
|
|
89
|
+
page.insert_text((x, y + 14 + offset * 18), line, fontsize=14,
|
|
90
|
+
fontname="china-s", color=color)
|
|
91
|
+
continue
|
|
92
|
+
points = [
|
|
93
|
+
fitz.Point(float(point[0]) * box.width, float(point[1]) * box.height)
|
|
94
|
+
for point in entry.get("points") or []
|
|
95
|
+
if isinstance(point, (list, tuple)) and len(point) >= 2
|
|
96
|
+
]
|
|
97
|
+
if len(points) < 2:
|
|
98
|
+
continue
|
|
99
|
+
page.draw_polyline(points, color=color, width=float(entry.get("width") or 2),
|
|
100
|
+
lineCap=1, lineJoin=1, overlay=True)
|
|
101
|
+
|
|
102
|
+
write_progress({"status": "running", "done": index + 1, "total": source.page_count})
|
|
103
|
+
|
|
104
|
+
tmp = out_path + ".tmp.pdf"
|
|
105
|
+
doc.save(tmp)
|
|
106
|
+
os.replace(tmp, out_path)
|
|
107
|
+
write_progress({"status": "done", "done": source.page_count, "total": source.page_count})
|
|
108
|
+
print(out_path)
|