dsh-pdf-workbench 1.3.3 → 1.4.0

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 (82) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +225 -199
  3. package/assets/screenshot-attachments.jpg +0 -0
  4. package/assets/screenshot-canvas.jpg +0 -0
  5. package/assets/screenshot-questions.jpg +0 -0
  6. package/assets/screenshot-settings-data.jpg +0 -0
  7. package/assets/screenshot-settings-mode.jpg +0 -0
  8. package/assets/screenshot-settings-reading.jpg +0 -0
  9. package/client.js +5700 -849
  10. package/docs/DETAIL.md +1 -69
  11. package/docs/RELEASE.md +119 -119
  12. package/docs/SIDE-PREVIEW.md +5 -1
  13. package/docs/preview.svg +86 -0
  14. package/icon.svg +7 -6
  15. package/index.js +18 -2
  16. package/locale/en.json +1 -1
  17. package/locale/zh.json +1 -1
  18. package/package.json +1 -1
  19. package/screenshots.json +13 -8
  20. package/src/client/host-ui-entry.js +11 -11
  21. package/src/client/react-jsx-runtime.cjs +21 -21
  22. package/src/client/viewer.js +80 -80
  23. package/src/host/artifacts.js +31 -3
  24. package/src/host/attachments.js +159 -0
  25. package/src/host/backup.js +457 -0
  26. package/src/host/base-session.js +146 -0
  27. package/src/host/book-import.js +98 -0
  28. package/src/host/chapter-sessions.js +154 -0
  29. package/src/host/chapter-text.js +91 -0
  30. package/src/host/fonts.js +190 -0
  31. package/src/host/pdf-stream.js +168 -0
  32. package/src/host/ppt.js +153 -0
  33. package/src/host/print.js +191 -0
  34. package/src/host/questions.js +186 -0
  35. package/src/host/routes.js +671 -25
  36. package/src/host/state.js +1 -1
  37. package/src/host/zip.js +186 -0
  38. package/tools/AGENTS.md +33 -33
  39. package/tools/README.md +138 -138
  40. package/tools/auto_chapters.py +122 -122
  41. package/tools/dsfile.mjs +198 -198
  42. package/tools/export_chapter.py +108 -108
  43. package/tools/export_page.py +91 -91
  44. package/tools/md2overlay.py +200 -200
  45. package/tools/md2tex.py +422 -422
  46. package/tools/pdf_blocks.py +110 -110
  47. package/tools/pdf_fontsize.py +20 -20
  48. package/tools/pdf_merge.py +15 -15
  49. package/tools/pdf_pagesizes.py +8 -8
  50. package/tools/pdf_raster.py +21 -21
  51. package/tools/pdf_text.py +34 -0
  52. package/tools/pdfkit.py +896 -896
  53. package/tools/realign_overlay.py +248 -248
  54. package/tools/rebuild_overlay.py +55 -55
  55. package/tools/rename_chapters.py +93 -93
  56. package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
  57. package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
  58. package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
  59. package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
  60. 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
  61. package/vendor/cmaps/LICENSE.txt +36 -36
  62. package/vendor/fonts/excalifont/OFL.txt +98 -98
  63. package/vendor/fonts/zhhand/OFL.txt +99 -99
  64. package/vendor/host-ui.cjs +1719 -1719
  65. package/vendor/host-ui.css +799 -799
  66. package/vendor/pdf.min.mjs +28 -28
  67. package/vendor/pdf.worker.min.mjs +28 -28
  68. package/vendor/pdfjs-LICENSE.txt +177 -177
  69. package/vendor/rough/LICENSE +21 -21
  70. package/vendor/rough/rough.mjs +1 -1
  71. package/vendor/wasm/LICENSE_JBIG2 +196 -196
  72. package/vendor/wasm/LICENSE_OPENJPEG +39 -39
  73. package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
  74. package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
  75. package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
  76. package/vendor/wasm/LICENSE_QCMS +21 -21
  77. package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
  78. package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
  79. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
  80. package/tools/node.cmd +0 -3
  81. package/tools/py.cmd +0 -3
  82. package/vendor/fonts/zhhand/Xiaolai-Regular.ttf +0 -0
@@ -1,122 +1,122 @@
1
- # -*- coding: utf-8 -*-
2
- """整本上传 → 问出章节起始页 → 生成映射 → 调用 rename_chapters.py 改名。
3
-
4
- 用法:
5
- python auto_chapters.py --jobs jobs.json [--apply]
6
-
7
- jobs.json:
8
- [
9
- {"book": "概率论", "dir": "D:\\...\\分片\\概率论(1)", "full": "D:\\...\\书库\\xx.pdf"}
10
- ]
11
- """
12
- import argparse
13
- import json
14
- import re
15
- import subprocess
16
- import sys
17
- from pathlib import Path
18
-
19
- ROOT = Path(r"D:\数学书库")
20
- NODE = ROOT / "工具" / "node.cmd"
21
- DSFILE = ROOT / "工具" / "dsfile.mjs"
22
- RENAMER = ROOT / "工具" / "rename_chapters.py"
23
- PY = ROOT / "工具" / "py.cmd"
24
-
25
- PROMPT = """这本书是教材。请只输出各章(以及前置、附录、习题答案等独立部分)的起始页。
26
- 严格按下面格式,每行一条,不要表头、不要解释、不要 markdown 表格:
27
-
28
- 起始页|章号|标题
29
-
30
- 要求:
31
- - 起始页是该部分在本文档中的物理页(PDF 第几页,从 1 开始数),不是书上的印刷页码。
32
- - 章号写成「第一章」这种;书前面的封面/目录/前言合并成一行写「前置」;书后的附录/答案/索引写「附录」。
33
- - 按起始页从小到大排列,一条都不要漏。"""
34
-
35
-
36
- def run(cmd):
37
- r = subprocess.run([str(c) for c in cmd], capture_output=True, text=True,
38
- encoding="utf-8", errors="replace")
39
- return r.stdout
40
-
41
-
42
- def pdf_pages(pdf):
43
- out = run(["pdfinfo", str(pdf)])
44
- m = re.search(r"^Pages:\s+(\d+)", out, re.M)
45
- return int(m.group(1)) if m else None
46
-
47
-
48
- def parse(text, total):
49
- items = []
50
- for raw in text.splitlines():
51
- line = raw.strip().strip("|").replace("|", "|")
52
- m = re.match(r"^(\d+)\s*\|([^|]+)\|(.+)$", line)
53
- if not m:
54
- continue
55
- start = int(m.group(1))
56
- num = m.group(2).strip()
57
- title = re.sub(r"[\s`*]+", " ", m.group(3)).strip()
58
- if 1 <= start <= total:
59
- items.append({"start": start, "num": num, "title": title})
60
- # 去重 + 排序
61
- seen, uniq = set(), []
62
- for it in sorted(items, key=lambda x: x["start"]):
63
- if it["start"] in seen:
64
- continue
65
- seen.add(it["start"])
66
- uniq.append(it)
67
- if not uniq:
68
- return []
69
- if uniq[0]["start"] > 1:
70
- uniq.insert(0, {"start": 1, "num": "前置", "title": "封面目录"})
71
- for i, it in enumerate(uniq):
72
- it["end"] = (uniq[i + 1]["start"] - 1) if i + 1 < len(uniq) else total
73
- return uniq
74
-
75
-
76
- def code_for(i, it):
77
- if "前置" in it["num"]:
78
- return "c00"
79
- if any(k in it["num"] + it["title"] for k in ("附录", "答案", "索引", "参考")):
80
- return f"c9{9 - (i % 10)}"
81
- return f"c{i:02d}" if i < 100 else "c50"
82
-
83
-
84
- def main():
85
- ap = argparse.ArgumentParser()
86
- ap.add_argument("--jobs", required=True)
87
- ap.add_argument("--apply", action="store_true")
88
- a = ap.parse_args()
89
-
90
- jobs = json.loads(Path(a.jobs).read_text(encoding="utf-8"))
91
- for job in jobs:
92
- book, bdir, full = job["book"], Path(job["dir"]), Path(job["full"])
93
- total = pdf_pages(full)
94
- print(f"\n===== {book} ({total} 页) {full.name}")
95
- out = run([NODE, DSFILE, "run", full, "--purpose", "text_recognition",
96
- "--prompt", PROMPT])
97
- chs = parse(out, total)
98
- if not chs:
99
- print(" !! 没能解析出章节,原文如下:")
100
- print("\n".join(" " + l for l in out.splitlines()[:25]))
101
- continue
102
- chapters, used = [], set()
103
- for i, it in enumerate(chs, 1):
104
- code = code_for(i, it)
105
- while code in used:
106
- code = f"c{i:02d}x"
107
- used.add(code)
108
- label = f"{it['num']}_{it['title']}".replace("|", "_")
109
- chapters.append({"from": it["start"], "to": it["end"],
110
- "code": code, "label": label})
111
- print(f" {code} p{it['start']:>3}-{it['end']:<3} {it['num']} {it['title']}")
112
- mapping = ROOT / "缓存" / "章映射" / f"{book}.json"
113
- mapping.parent.mkdir(parents=True, exist_ok=True)
114
- mapping.write_text(json.dumps({"book": book, "chapters": chapters},
115
- ensure_ascii=False, indent=2), encoding="utf-8")
116
- cmd = [PY, RENAMER, bdir, mapping]
117
- if not a.apply:
118
- cmd.append("--dry-run")
119
- print(run(cmd))
120
-
121
-
122
- main()
1
+ # -*- coding: utf-8 -*-
2
+ """整本上传 → 问出章节起始页 → 生成映射 → 调用 rename_chapters.py 改名。
3
+
4
+ 用法:
5
+ python auto_chapters.py --jobs jobs.json [--apply]
6
+
7
+ jobs.json:
8
+ [
9
+ {"book": "概率论", "dir": "D:\\...\\分片\\概率论(1)", "full": "D:\\...\\书库\\xx.pdf"}
10
+ ]
11
+ """
12
+ import argparse
13
+ import json
14
+ import re
15
+ import subprocess
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ ROOT = Path(r"D:\数学书库")
20
+ NODE = ROOT / "工具" / "node.cmd"
21
+ DSFILE = ROOT / "工具" / "dsfile.mjs"
22
+ RENAMER = ROOT / "工具" / "rename_chapters.py"
23
+ PY = ROOT / "工具" / "py.cmd"
24
+
25
+ PROMPT = """这本书是教材。请只输出各章(以及前置、附录、习题答案等独立部分)的起始页。
26
+ 严格按下面格式,每行一条,不要表头、不要解释、不要 markdown 表格:
27
+
28
+ 起始页|章号|标题
29
+
30
+ 要求:
31
+ - 起始页是该部分在本文档中的物理页(PDF 第几页,从 1 开始数),不是书上的印刷页码。
32
+ - 章号写成「第一章」这种;书前面的封面/目录/前言合并成一行写「前置」;书后的附录/答案/索引写「附录」。
33
+ - 按起始页从小到大排列,一条都不要漏。"""
34
+
35
+
36
+ def run(cmd):
37
+ r = subprocess.run([str(c) for c in cmd], capture_output=True, text=True,
38
+ encoding="utf-8", errors="replace")
39
+ return r.stdout
40
+
41
+
42
+ def pdf_pages(pdf):
43
+ out = run(["pdfinfo", str(pdf)])
44
+ m = re.search(r"^Pages:\s+(\d+)", out, re.M)
45
+ return int(m.group(1)) if m else None
46
+
47
+
48
+ def parse(text, total):
49
+ items = []
50
+ for raw in text.splitlines():
51
+ line = raw.strip().strip("|").replace("|", "|")
52
+ m = re.match(r"^(\d+)\s*\|([^|]+)\|(.+)$", line)
53
+ if not m:
54
+ continue
55
+ start = int(m.group(1))
56
+ num = m.group(2).strip()
57
+ title = re.sub(r"[\s`*]+", " ", m.group(3)).strip()
58
+ if 1 <= start <= total:
59
+ items.append({"start": start, "num": num, "title": title})
60
+ # 去重 + 排序
61
+ seen, uniq = set(), []
62
+ for it in sorted(items, key=lambda x: x["start"]):
63
+ if it["start"] in seen:
64
+ continue
65
+ seen.add(it["start"])
66
+ uniq.append(it)
67
+ if not uniq:
68
+ return []
69
+ if uniq[0]["start"] > 1:
70
+ uniq.insert(0, {"start": 1, "num": "前置", "title": "封面目录"})
71
+ for i, it in enumerate(uniq):
72
+ it["end"] = (uniq[i + 1]["start"] - 1) if i + 1 < len(uniq) else total
73
+ return uniq
74
+
75
+
76
+ def code_for(i, it):
77
+ if "前置" in it["num"]:
78
+ return "c00"
79
+ if any(k in it["num"] + it["title"] for k in ("附录", "答案", "索引", "参考")):
80
+ return f"c9{9 - (i % 10)}"
81
+ return f"c{i:02d}" if i < 100 else "c50"
82
+
83
+
84
+ def main():
85
+ ap = argparse.ArgumentParser()
86
+ ap.add_argument("--jobs", required=True)
87
+ ap.add_argument("--apply", action="store_true")
88
+ a = ap.parse_args()
89
+
90
+ jobs = json.loads(Path(a.jobs).read_text(encoding="utf-8"))
91
+ for job in jobs:
92
+ book, bdir, full = job["book"], Path(job["dir"]), Path(job["full"])
93
+ total = pdf_pages(full)
94
+ print(f"\n===== {book} ({total} 页) {full.name}")
95
+ out = run([NODE, DSFILE, "run", full, "--purpose", "text_recognition",
96
+ "--prompt", PROMPT])
97
+ chs = parse(out, total)
98
+ if not chs:
99
+ print(" !! 没能解析出章节,原文如下:")
100
+ print("\n".join(" " + l for l in out.splitlines()[:25]))
101
+ continue
102
+ chapters, used = [], set()
103
+ for i, it in enumerate(chs, 1):
104
+ code = code_for(i, it)
105
+ while code in used:
106
+ code = f"c{i:02d}x"
107
+ used.add(code)
108
+ label = f"{it['num']}_{it['title']}".replace("|", "_")
109
+ chapters.append({"from": it["start"], "to": it["end"],
110
+ "code": code, "label": label})
111
+ print(f" {code} p{it['start']:>3}-{it['end']:<3} {it['num']} {it['title']}")
112
+ mapping = ROOT / "缓存" / "章映射" / f"{book}.json"
113
+ mapping.parent.mkdir(parents=True, exist_ok=True)
114
+ mapping.write_text(json.dumps({"book": book, "chapters": chapters},
115
+ ensure_ascii=False, indent=2), encoding="utf-8")
116
+ cmd = [PY, RENAMER, bdir, mapping]
117
+ if not a.apply:
118
+ cmd.append("--dry-run")
119
+ print(run(cmd))
120
+
121
+
122
+ main()
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
+ }