dsh-mineru 0.1.13 → 0.1.14
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/CHANGELOG.md +40 -3
- package/README.md +105 -11
- package/README.zh.md +76 -10
- package/RELEASE.md +2 -1
- package/lib/anchors.js +522 -0
- package/lib/artifacts.js +20 -0
- package/lib/chunk-merge.js +80 -0
- package/lib/client.js +27 -13
- package/lib/config.js +14 -11
- package/lib/http.js +15 -4
- package/lib/mineru-client.js +59 -6
- package/lib/page-ranges.js +204 -0
- package/lib/pdf-pages.js +151 -0
- package/lib/run-state.js +114 -0
- package/lib/skill.js +1 -1
- package/lib/tools.js +679 -26
- package/lib/types/client.d.ts +1 -1
- package/lib/types/index.d.ts +2 -0
- package/package.json +21 -10
package/lib/client.js
CHANGED
|
@@ -254,6 +254,27 @@ window.__ModuleLoader__.load({
|
|
|
254
254
|
var LANGUAGES = ["ch", "ch_server", "en", "japan", "korean", "chinese_cht", "ta", "te", "ka", "el", "th", "latin", "arabic", "cyrillic", "east_slavic", "devanagari"];
|
|
255
255
|
var EXTRA_FORMATS = ["docx", "html", "latex"];
|
|
256
256
|
|
|
257
|
+
// --- settings-view helpers start (self-contained; unit-mirrored by tests/settings-card.spec.js)
|
|
258
|
+
function makeSettingsView(allowed) {
|
|
259
|
+
return {
|
|
260
|
+
// Any plausible wire shape (array, single value, comma/space/YAML-list
|
|
261
|
+
// text) collapses to a canonical array of allowed members.
|
|
262
|
+
normalizeFormats: function (value) {
|
|
263
|
+
if (Array.isArray(value)) return value.filter(function (f) { return allowed.indexOf(f) >= 0; });
|
|
264
|
+
if (typeof value === "string") return value.split(/[\s,]+/).map(function (f) { return f.trim(); }).filter(function (f) { return f.length > 0 && allowed.indexOf(f) >= 0; });
|
|
265
|
+
return [];
|
|
266
|
+
},
|
|
267
|
+
// The saved-state marker: the canonical JSON of the last value the
|
|
268
|
+
// server confirmed. Dirty is *derived* from the delta, so a stale
|
|
269
|
+
// interaction flag can never light the indicator with zero edits.
|
|
270
|
+
isDirty: function (baseline, value) {
|
|
271
|
+
return baseline !== null && baseline !== JSON.stringify(value === undefined ? {} : value);
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
var settingsView = makeSettingsView(EXTRA_FORMATS);
|
|
276
|
+
// --- settings-view helpers end
|
|
277
|
+
|
|
257
278
|
function modeLabel(m) { return T("mode." + m); }
|
|
258
279
|
function modelLabel(m) { return m === "MinerU-HTML" ? T("model.mineruHtml") : T("model." + m); }
|
|
259
280
|
|
|
@@ -347,11 +368,10 @@ window.__ModuleLoader__.load({
|
|
|
347
368
|
// ------------------------------------------------------------------
|
|
348
369
|
function MineruSettingsTab() {
|
|
349
370
|
useLocaleVersion();
|
|
350
|
-
var [state, setState] = useState({ phase: "loading", revision: 0, value: {}, facts: null, defaults: {}, saveMsg: null, saveErr: null, testMsg: null, testErr: null });
|
|
371
|
+
var [state, setState] = useState({ phase: "loading", revision: 0, value: {}, baseline: null, facts: null, defaults: {}, saveMsg: null, saveErr: null, testMsg: null, testErr: null });
|
|
351
372
|
var [busy, setBusy] = useState({ save: false, reload: false, token: false, testToken: false, testAgent: false });
|
|
352
373
|
var [showAdvanced, setShowAdvanced] = useState(false);
|
|
353
374
|
var [tokenDraft, setTokenDraft] = useState("");
|
|
354
|
-
var [dirty, setDirty] = useState(false);
|
|
355
375
|
|
|
356
376
|
var reload = useCallback(async function (announce) {
|
|
357
377
|
try {
|
|
@@ -359,8 +379,8 @@ window.__ModuleLoader__.load({
|
|
|
359
379
|
var payload = await res.json();
|
|
360
380
|
if (!res.ok || !payload.ok) throw new Error(payload.error ?? ("HTTP " + res.status));
|
|
361
381
|
var value = payload.value ?? {};
|
|
362
|
-
|
|
363
|
-
|
|
382
|
+
value = { ...value, extraFormats: settingsView.normalizeFormats(value.extraFormats) };
|
|
383
|
+
setState(function (prev) { return { ...prev, phase: "ready", revision: payload.revision ?? 0, value: value, baseline: JSON.stringify(value), facts: payload.facts ?? prev.facts, defaults: payload.schemaHints?.defaults ?? {}, saveMsg: announce === true ? T("msg.reloaded") : null, saveErr: null }; });
|
|
364
384
|
} catch (err) {
|
|
365
385
|
setState(function (prev) { return { ...prev, phase: "error", saveErr: T("settings.loadFail", { err: err?.message ?? String(err) }) }; });
|
|
366
386
|
}
|
|
@@ -370,12 +390,11 @@ window.__ModuleLoader__.load({
|
|
|
370
390
|
|
|
371
391
|
var setValue = function (key, v) {
|
|
372
392
|
setState(function (prev) { return { ...prev, value: { ...prev.value, [key]: v } }; });
|
|
373
|
-
setDirty(true);
|
|
374
393
|
};
|
|
375
394
|
|
|
376
395
|
var save = async function () {
|
|
377
396
|
if (busy.save) return;
|
|
378
|
-
if (!
|
|
397
|
+
if (!settingsView.isDirty(state.baseline, state.value)) {
|
|
379
398
|
setState(function (prev) { return { ...prev, saveMsg: T("msg.noop"), saveErr: null }; });
|
|
380
399
|
return;
|
|
381
400
|
}
|
|
@@ -384,8 +403,7 @@ window.__ModuleLoader__.load({
|
|
|
384
403
|
try {
|
|
385
404
|
var res = await apiPost("/config", { patch: state.value, expectedRevision: state.revision });
|
|
386
405
|
if (res.status === 200 && res.payload?.ok) {
|
|
387
|
-
setState(function (prev) { return { ...prev, revision: res.payload.revision ?? prev.revision, saveMsg: T("msg.saved") }; });
|
|
388
|
-
setDirty(false);
|
|
406
|
+
setState(function (prev) { return { ...prev, revision: res.payload.revision ?? prev.revision, baseline: JSON.stringify(state.value), saveMsg: T("msg.saved") }; });
|
|
389
407
|
await reload();
|
|
390
408
|
} else if (res.status === 409) {
|
|
391
409
|
setState(function (prev) { return { ...prev, saveErr: T("msg.conflict") }; });
|
|
@@ -466,6 +484,7 @@ window.__ModuleLoader__.load({
|
|
|
466
484
|
|
|
467
485
|
var facts = state.facts ?? {};
|
|
468
486
|
var v = state.value;
|
|
487
|
+
var dirty = settingsView.isDirty(state.baseline, state.value);
|
|
469
488
|
var anyBusy = busy.save || busy.reload || busy.token || busy.testToken || busy.testAgent;
|
|
470
489
|
return jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 4 }, children: [
|
|
471
490
|
jsxs("div", { style: S.row, children: [
|
|
@@ -756,11 +775,6 @@ window.__ModuleLoader__.load({
|
|
|
756
775
|
if (ctx.locale) {
|
|
757
776
|
try {
|
|
758
777
|
ctx.effect(function () { return ctx.locale.register(NS, { zh: DICTS.zh, en: DICTS.en }); }, "dsh-mineru: dictionaries");
|
|
759
|
-
ctx.effect(function () {
|
|
760
|
-
var dis = [];
|
|
761
|
-
for (var loc in DICTS) dis.push(ctx.locale.register(NS, loc, DICTS[loc]));
|
|
762
|
-
return function () { for (var i = 0; i < dis.length; i++) dis[i](); };
|
|
763
|
-
}, "dsh-mineru: language-pack dictionaries");
|
|
764
778
|
ctx.effect(function () {
|
|
765
779
|
var rebind = function () {
|
|
766
780
|
currentT = ctx.locale.bind(NS) || currentT;
|
package/lib/config.js
CHANGED
|
@@ -128,9 +128,11 @@ export const DEFAULTS = Object.freeze({
|
|
|
128
128
|
|
|
129
129
|
export const CONFIG_SCHEMA = z.object({
|
|
130
130
|
apiBaseUrl: live(z.string().role('text')
|
|
131
|
+
.pattern(/^https?:\/\//i)
|
|
131
132
|
.default(DEFAULTS.apiBaseUrl)
|
|
132
133
|
.description('MinerU API base URL (https://mineru.net).')),
|
|
133
134
|
tokenCredential: live(z.string().role('text')
|
|
135
|
+
.pattern(/^[A-Za-z_][A-Za-z0-9_]*$/)
|
|
134
136
|
.default(DEFAULTS.tokenCredential)
|
|
135
137
|
.description('DSH Credential reference name holding the MinerU token.')),
|
|
136
138
|
mode: live(z.union([z.const('auto'), z.const('precision'), z.const('agent')])
|
|
@@ -139,7 +141,7 @@ export const CONFIG_SCHEMA = z.object({
|
|
|
139
141
|
modelVersion: live(z.union([z.const('pipeline'), z.const('vlm'), z.const('MinerU-HTML')])
|
|
140
142
|
.default(DEFAULTS.modelVersion)
|
|
141
143
|
.description('Precision-API model version (pipeline | vlm | MinerU-HTML).')),
|
|
142
|
-
language: live(z.
|
|
144
|
+
language: live(z.union(LANGUAGE_VALUES.map((value) => z.const(value)))
|
|
143
145
|
.default(DEFAULTS.language)
|
|
144
146
|
.description('Document language pack, e.g. ch, en, latin (see README table).')),
|
|
145
147
|
enableTable: live(z.boolean().default(DEFAULTS.enableTable)
|
|
@@ -155,25 +157,26 @@ export const CONFIG_SCHEMA = z.object({
|
|
|
155
157
|
.default(DEFAULTS.exposeMode)
|
|
156
158
|
.description('progressive: mineru_activate bootstrap + skill-based activation; always: register all tools globally.')),
|
|
157
159
|
artifactRootName: live(z.string().role('text')
|
|
160
|
+
.pattern(/^(?!\.{1,2}$)[^\/\\]+$/)
|
|
158
161
|
.default(DEFAULTS.artifactRootName)
|
|
159
162
|
.description('Artifact root directory name inside each session workspace.')),
|
|
160
|
-
pollIntervalMs: live(z.number().default(DEFAULTS.pollIntervalMs)
|
|
163
|
+
pollIntervalMs: live(z.number().min(500).max(60000).step(1).default(DEFAULTS.pollIntervalMs)
|
|
161
164
|
.description('Task-result poll interval (ms).')),
|
|
162
|
-
pollJitterMs: live(z.number().default(DEFAULTS.pollJitterMs)
|
|
165
|
+
pollJitterMs: live(z.number().min(0).max(10000).step(1).default(DEFAULTS.pollJitterMs)
|
|
163
166
|
.description('Per-query poll jitter (ms).')),
|
|
164
|
-
timeoutMs: live(z.number().default(DEFAULTS.timeoutMs)
|
|
167
|
+
timeoutMs: live(z.number().min(10000).max(3600000).step(1).default(DEFAULTS.timeoutMs)
|
|
165
168
|
.description('Whole-operation deadline (ms).')),
|
|
166
|
-
maxFileBytes: live(z.number().default(DEFAULTS.maxFileBytes)
|
|
169
|
+
maxFileBytes: live(z.number().min(0).max(512 * 1024 * 1024).step(1).default(DEFAULTS.maxFileBytes)
|
|
167
170
|
.description('Local file byte cap; 0 = per-mode API limits (200 MB / 10 MB).')),
|
|
168
|
-
inlineMarkdownBytes: live(z.number().default(DEFAULTS.inlineMarkdownBytes)
|
|
171
|
+
inlineMarkdownBytes: live(z.number().min(256).max(1024 * 1024).step(1).default(DEFAULTS.inlineMarkdownBytes)
|
|
169
172
|
.description('Markdown preview bytes returned inline with the tool result.')),
|
|
170
|
-
artifactUrlTtlSec: live(z.number().default(DEFAULTS.artifactUrlTtlSec)
|
|
173
|
+
artifactUrlTtlSec: live(z.number().min(60).max(30 * 24 * 3600).step(1).default(DEFAULTS.artifactUrlTtlSec)
|
|
171
174
|
.description('Signed artifact preview URL lifetime (seconds).')),
|
|
172
|
-
submitRatePerMin: live(z.number().default(DEFAULTS.submitRatePerMin)
|
|
175
|
+
submitRatePerMin: live(z.number().min(1).max(60).step(1).default(DEFAULTS.submitRatePerMin)
|
|
173
176
|
.description('Submission rate cap per minute (official limit: 50/min).')),
|
|
174
|
-
pollRatePerMin: live(z.number().default(DEFAULTS.pollRatePerMin)
|
|
177
|
+
pollRatePerMin: live(z.number().min(10).max(1000).step(1).default(DEFAULTS.pollRatePerMin)
|
|
175
178
|
.description('Result-query rate cap per minute (official limit: 1000/min).')),
|
|
176
|
-
dailySubmitLimit: live(z.number().default(DEFAULTS.dailySubmitLimit)
|
|
179
|
+
dailySubmitLimit: live(z.number().min(1).max(100000).step(1).default(DEFAULTS.dailySubmitLimit)
|
|
177
180
|
.description('Daily submission cap reported before the API rejects (official: 5000/day).')),
|
|
178
181
|
userAgent: live(z.string().role('text').default(DEFAULTS.userAgent)
|
|
179
182
|
.description('User-Agent header sent to MinerU.')),
|
|
@@ -218,4 +221,4 @@ export function resolveLoadConfig(config) {
|
|
|
218
221
|
const value = { ...DEFAULTS, ...(config ?? {}) };
|
|
219
222
|
validateConfig(value);
|
|
220
223
|
return value;
|
|
221
|
-
}
|
|
224
|
+
}
|
package/lib/http.js
CHANGED
|
@@ -13,9 +13,10 @@ import { randomBytes } from 'node:crypto';
|
|
|
13
13
|
import { mkdir, rm, stat } from 'node:fs/promises';
|
|
14
14
|
import { join } from 'node:path';
|
|
15
15
|
import { SettingsConflictError } from '@deepseek-ai/dsh-settings';
|
|
16
|
+
import { credentialRef } from '@deepseek-ai/dsh-credentials';
|
|
16
17
|
import { MineruError } from './mineru-client.js';
|
|
17
18
|
import { ArtifactError, inlineable, sanitizeFileName } from './artifacts.js';
|
|
18
|
-
import { DEFAULTS, SUPPORTED_EXTENSIONS } from './config.js';
|
|
19
|
+
import { DEFAULTS, SUPPORTED_EXTENSIONS, validateConfig } from './config.js';
|
|
19
20
|
|
|
20
21
|
const JSON_BODY_LIMIT = 1 << 20;
|
|
21
22
|
|
|
@@ -176,9 +177,11 @@ async function handle(req, res, deps) {
|
|
|
176
177
|
const raw = await readBody(req);
|
|
177
178
|
let body;
|
|
178
179
|
try { body = JSON.parse(raw || '{}'); } catch { sendJson(res, 400, { ok: false, error: 'invalid JSON body' }); return; }
|
|
179
|
-
const patch = body && typeof body.patch === 'object' && body.patch !== null ? body.patch : null;
|
|
180
|
+
const patch = body && typeof body.patch === 'object' && body.patch !== null && !Array.isArray(body.patch) ? body.patch : null;
|
|
180
181
|
if (!patch) { sendJson(res, 400, { ok: false, error: 'missing patch object' }); return; }
|
|
181
182
|
try {
|
|
183
|
+
// The derived settings form no longer calls the legacy register validator.
|
|
184
|
+
validateConfig({ ...DEFAULTS, ...deps.config(), ...patch });
|
|
182
185
|
await deps.settings.update(settingsNs, patch, Number.isInteger(body.expectedRevision) ? body.expectedRevision : undefined);
|
|
183
186
|
const descriptor = descriptorOf();
|
|
184
187
|
sendJson(res, 200, { ok: true, revision: descriptor?.revision ?? 0 });
|
|
@@ -195,11 +198,19 @@ async function handle(req, res, deps) {
|
|
|
195
198
|
const raw = await readBody(req);
|
|
196
199
|
let body;
|
|
197
200
|
try { body = JSON.parse(raw || '{}'); } catch { sendJson(res, 400, { ok: false, error: 'invalid JSON body' }); return; }
|
|
201
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
202
|
+
sendJson(res, 400, { ok: false, error: 'expected a credential object' });
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
198
205
|
const cfg = deps.config();
|
|
199
|
-
const refName =
|
|
206
|
+
const refName = cfg.tokenCredential;
|
|
207
|
+
if (body.ref !== undefined && body.ref !== refName) {
|
|
208
|
+
sendJson(res, 400, { ok: false, error: 'credential reference must match tokenCredential' });
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
200
211
|
let ref;
|
|
201
212
|
try {
|
|
202
|
-
ref =
|
|
213
|
+
ref = credentialRef(refName);
|
|
203
214
|
} catch {
|
|
204
215
|
sendJson(res, 400, { ok: false, error: 'invalid credential reference' });
|
|
205
216
|
return;
|
package/lib/mineru-client.js
CHANGED
|
@@ -39,6 +39,9 @@ export class MineruError extends Error {
|
|
|
39
39
|
const PRECISION_FILE_LIMIT = 200 * 1024 * 1024;
|
|
40
40
|
const AGENT_FILE_LIMIT = 10 * 1024 * 1024;
|
|
41
41
|
|
|
42
|
+
/** Per-request page cap of the precision API; a bigger request is split by `page_ranges`. */
|
|
43
|
+
export const PRECISION_PAGE_LIMIT = 200;
|
|
44
|
+
|
|
42
45
|
/** Map MinerU error codes to actionable messages. */
|
|
43
46
|
const ERROR_MESSAGES = Object.freeze({
|
|
44
47
|
A0202: 'MinerU Token 错误:请检查 Token 是否正确(Bearer 前缀由插件自动添加),或更换新 Token。',
|
|
@@ -51,7 +54,7 @@ const ERROR_MESSAGES = Object.freeze({
|
|
|
51
54
|
'-60003': 'MinerU 文件读取失败:请检查文件是否损坏并重新上传。',
|
|
52
55
|
'-60004': 'MinerU 收到空文件:请上传有效文件。',
|
|
53
56
|
'-60005': '文件大小超出限制:精准解析 API 最大支持 200MB,Agent 轻量解析 API 最大 10MB。',
|
|
54
|
-
'-60006': '文件页数超过限制:精准解析 API
|
|
57
|
+
'-60006': '文件页数超过限制:精准解析 API 单次请求最多 200 页。工作区内的 PDF 会自动按 page_ranges 分片提交并合并结果;出现本错误说明这份文件的页数无法在本地读出(非 PDF、加密或结构异常),或 pageRanges 写法无法在本地分片,请手动用 pageRanges 分段(每段 <= 200 页)后重试。',
|
|
55
58
|
'-60007': 'MinerU 模型服务暂时不可用,请稍后重试。',
|
|
56
59
|
'-60008': 'MinerU 文件读取超时:请检查 URL 是否可访问。',
|
|
57
60
|
'-60009': 'MinerU 任务提交队列已满,请稍后再试。',
|
|
@@ -70,7 +73,7 @@ const ERROR_MESSAGES = Object.freeze({
|
|
|
70
73
|
'-60022': 'MinerU 网页读取失败:可能因网络问题或限频导致,请稍后重试。',
|
|
71
74
|
'-30001': '文件大小超出 Agent 轻量解析接口限制(10MB):请改用精准解析 API(填写 Token)或拆分文件。',
|
|
72
75
|
'-30002': 'Agent 轻量解析接口不支持该文件类型:请上传 PDF/图片/Docx/PPTx/Xlsx。',
|
|
73
|
-
'-30003': '文件页数超出 Agent 轻量解析接口限制(20
|
|
76
|
+
'-30003': '文件页数超出 Agent 轻量解析接口限制(20 页):该接口按 IP 限流,插件不会自动分片;请改用精准解析 API(配置 MinerU Token,PDF 会自动分片),或用 pageRange 自行分段后多次调用。',
|
|
74
77
|
'-30004': 'MinerU Agent 接口请求参数错误:请检查必填参数。',
|
|
75
78
|
});
|
|
76
79
|
|
|
@@ -173,7 +176,15 @@ export class DailyCounter {
|
|
|
173
176
|
}
|
|
174
177
|
}
|
|
175
178
|
|
|
176
|
-
|
|
179
|
+
/**
|
|
180
|
+
* Reduce a caller-supplied `data_id` to the API's safe slug shape.
|
|
181
|
+
*
|
|
182
|
+
* Exported because the chunked path builds one `data_id` per request from it
|
|
183
|
+
* (a page-range suffix is appended so two chunks of the same file cannot be
|
|
184
|
+
* confused server-side).
|
|
185
|
+
* @param {unknown} value @returns {string|undefined}
|
|
186
|
+
*/
|
|
187
|
+
export function sanitizeDataId(value) {
|
|
177
188
|
const v = String(value ?? '').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 128);
|
|
178
189
|
return v || undefined;
|
|
179
190
|
}
|
|
@@ -196,11 +207,13 @@ function dataIdFor(item, index, opts) {
|
|
|
196
207
|
return sanitizeDataId(item.dataId ?? (opts.dataIdPrefix ? opts.dataIdPrefix + '-' + (index + 1) : undefined));
|
|
197
208
|
}/** One HTTP request with JSON decoding. 429 throws a retryable MineruError. */
|
|
198
209
|
async function requestJson({ url, method = 'GET', headers = {}, body, signal, timeoutMs = 60000, userAgent }) {
|
|
210
|
+
if (signal?.aborted) throw abortError();
|
|
199
211
|
const controller = new AbortController();
|
|
200
212
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
201
213
|
const onAbort = () => controller.abort();
|
|
202
214
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
203
215
|
let res;
|
|
216
|
+
let text;
|
|
204
217
|
try {
|
|
205
218
|
res = await fetch(url, {
|
|
206
219
|
method,
|
|
@@ -208,6 +221,8 @@ async function requestJson({ url, method = 'GET', headers = {}, body, signal, ti
|
|
|
208
221
|
body,
|
|
209
222
|
signal: controller.signal,
|
|
210
223
|
});
|
|
224
|
+
// Keep cancellation and the deadline attached until the body is consumed.
|
|
225
|
+
text = await res.text();
|
|
211
226
|
} catch (err) {
|
|
212
227
|
if (err?.name === 'AbortError') {
|
|
213
228
|
if (signal?.aborted) throw abortError();
|
|
@@ -218,7 +233,6 @@ async function requestJson({ url, method = 'GET', headers = {}, body, signal, ti
|
|
|
218
233
|
clearTimeout(timer);
|
|
219
234
|
signal?.removeEventListener('abort', onAbort);
|
|
220
235
|
}
|
|
221
|
-
const text = await res.text();
|
|
222
236
|
let payload = null;
|
|
223
237
|
if (text) {
|
|
224
238
|
try { payload = JSON.parse(text); } catch { /* non-JSON body */ }
|
|
@@ -547,9 +561,20 @@ export class MineruClient {
|
|
|
547
561
|
const items = await this.waitBatch({ batchId, api, opts, signal, onState });
|
|
548
562
|
const item = items[0];
|
|
549
563
|
if (!item) throw new MineruError('MinerU 批量结果为空', 'MINERU_API', { api });
|
|
564
|
+
// A settled-as-failed upload carries the server's reason (err_code and/or
|
|
565
|
+
// err_msg); report it here rather than letting the collector answer with a
|
|
566
|
+
// bare "state=failed". `waitTask` already throws MINERU_PARSE_FAILED for a
|
|
567
|
+
// failed precision task, so both single-file paths now behave alike.
|
|
568
|
+
if (item.state === 'failed') {
|
|
569
|
+
throw new MineruError(
|
|
570
|
+
messageForCode(item.errCode) ?? item.errMsg ?? 'MinerU 解析失败',
|
|
571
|
+
'MINERU_PARSE_FAILED',
|
|
572
|
+
{ api, rawCode: item.errCode === undefined ? undefined : String(item.errCode) },
|
|
573
|
+
);
|
|
574
|
+
}
|
|
550
575
|
return {
|
|
551
576
|
api, taskId: item.taskId, batchId, state: item.state,
|
|
552
|
-
fullZipUrl: item.fullZipUrl, errMsg: item.errMsg, progress: item.progress,
|
|
577
|
+
fullZipUrl: item.fullZipUrl, errMsg: item.errMsg, errCode: item.errCode, progress: item.progress,
|
|
553
578
|
};
|
|
554
579
|
}
|
|
555
580
|
const body = this.agentFileBody(opts, fileName);
|
|
@@ -733,6 +758,7 @@ export class MineruClient {
|
|
|
733
758
|
name: r.file_name,
|
|
734
759
|
state: r.state,
|
|
735
760
|
fullZipUrl: r.full_zip_url,
|
|
761
|
+
errCode: r.err_code,
|
|
736
762
|
errMsg: r.err_msg,
|
|
737
763
|
progress: r.extract_progress,
|
|
738
764
|
dataId: r.data_id,
|
|
@@ -743,6 +769,33 @@ export class MineruClient {
|
|
|
743
769
|
}
|
|
744
770
|
}
|
|
745
771
|
|
|
772
|
+
/**
|
|
773
|
+
* Resume a previously submitted precision batch WITHOUT requesting a new
|
|
774
|
+
* upload URL or uploading — `waitBatch` polls the existing batch to its
|
|
775
|
+
* terminal state. Used for chunks already submitted (running -> done, or a
|
|
776
|
+
* done batch whose result is re-downloaded). A batch settled as failed throws
|
|
777
|
+
* with `batchFailed`, so the caller re-submits that chunk.
|
|
778
|
+
* @param {{ batchId: string, opts: object, signal?: AbortSignal }} args
|
|
779
|
+
*/
|
|
780
|
+
async resumePrecisionBatch({ batchId, opts, signal }) {
|
|
781
|
+
const items = await this.waitBatch({ batchId, api: 'precision', opts, signal });
|
|
782
|
+
const item = items[0];
|
|
783
|
+
if (!item) throw new MineruError('MinerU 批量结果为空', 'MINERU_API', { api: 'precision' });
|
|
784
|
+
if (item.state === 'failed') {
|
|
785
|
+
const err = new MineruError(
|
|
786
|
+
messageForCode(item.errCode) ?? item.errMsg ?? 'MinerU 解析失败',
|
|
787
|
+
'MINERU_PARSE_FAILED',
|
|
788
|
+
{ api: 'precision', rawCode: item.errCode === undefined ? undefined : String(item.errCode) },
|
|
789
|
+
);
|
|
790
|
+
err.batchFailed = true;
|
|
791
|
+
throw err;
|
|
792
|
+
}
|
|
793
|
+
return {
|
|
794
|
+
api: 'precision', batchId, state: item.state,
|
|
795
|
+
fullZipUrl: item.fullZipUrl, errMsg: item.errMsg, errCode: item.errCode,
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
|
|
746
799
|
/** Download and extract one precision result zip. */
|
|
747
800
|
async collectPrecisionZip({ zipUrl, destDir, opts, signal }) {
|
|
748
801
|
await mkdir(destDir, { recursive: true });
|
|
@@ -823,4 +876,4 @@ export function effectiveModelFor(ext, modelVersion) {
|
|
|
823
876
|
}
|
|
824
877
|
}
|
|
825
878
|
return { modelVersion, forced: false };
|
|
826
|
-
}
|
|
879
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Page-range parsing and page-list splitting (pure functions, no I/O).
|
|
3
|
+
*
|
|
4
|
+
* The precision API takes `page_ranges` as a comma-separated string and rejects
|
|
5
|
+
* any single request asking for more than 200 pages, so a long document is split
|
|
6
|
+
* by *request shaping* — same upload, a different `page_ranges` per chunk — and
|
|
7
|
+
* never by rewriting the file locally.
|
|
8
|
+
*
|
|
9
|
+
* Two probed facts decide the rules below:
|
|
10
|
+
* - when `page_ranges` is present, the returned `content_list.json` renumbers
|
|
11
|
+
* `page_idx` from 0 for the requested subset (asking for pages 3-4 returns
|
|
12
|
+
* `page_idx` 0 and 1), so a block's original page can only be recovered from
|
|
13
|
+
* the page list that was requested — every chunk has to keep its own list;
|
|
14
|
+
* - negative indexes (`"2--2"`) are resolved by the server against the document,
|
|
15
|
+
* so such a spec can only be split after the local page count is known.
|
|
16
|
+
*
|
|
17
|
+
* A spec is parsed once into a page list and every chunk is a slice of it.
|
|
18
|
+
* Slices stay ascending and non-overlapping because the subset-to-original
|
|
19
|
+
* mapping is positional: an out-of-order spec would be mapped on the unverified
|
|
20
|
+
* assumption that the server returns blocks in the requested order.
|
|
21
|
+
* @module dsh-mineru/page-ranges
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Raised when a `page_ranges` spec cannot be used for local planning. */
|
|
25
|
+
export class PageRangeError extends Error {
|
|
26
|
+
/**
|
|
27
|
+
* @param {string} message user-facing reason
|
|
28
|
+
* @param {string} code stable machine code
|
|
29
|
+
* @param {string} [hint] what to write instead
|
|
30
|
+
*/
|
|
31
|
+
constructor(message, code, hint) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = 'PageRangeError';
|
|
34
|
+
this.code = code;
|
|
35
|
+
if (hint !== undefined) this.hint = hint;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const SINGLE = /^(\d+)$/;
|
|
40
|
+
const RANGE = /^(\d+)\s*-\s*(-?\d+)$/;
|
|
41
|
+
const NEGATIVE_ONLY = /^-\d+$/;
|
|
42
|
+
|
|
43
|
+
/** @param {unknown} value @returns {boolean} */
|
|
44
|
+
function isPositiveInt(value) {
|
|
45
|
+
return Number.isInteger(value) && value > 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Resolve one written page number against the document total.
|
|
50
|
+
* @param {string} raw a positive number, or a negative one counted from the end
|
|
51
|
+
* @param {number} [totalPages] required for negative numbers
|
|
52
|
+
* @returns {number} 1-based page number
|
|
53
|
+
*/
|
|
54
|
+
function resolvePageNumber(raw, totalPages) {
|
|
55
|
+
const value = Number.parseInt(raw, 10);
|
|
56
|
+
if (!Number.isInteger(value)) {
|
|
57
|
+
throw new PageRangeError('无法解析页码「' + raw + '」', 'unparsable-page');
|
|
58
|
+
}
|
|
59
|
+
if (value > 0) return value;
|
|
60
|
+
if (value === 0) {
|
|
61
|
+
throw new PageRangeError('页码从 1 开始,不支持 0', 'page-zero');
|
|
62
|
+
}
|
|
63
|
+
if (!isPositiveInt(totalPages)) {
|
|
64
|
+
throw new PageRangeError(
|
|
65
|
+
'倒数页码「' + raw + '」需要先知道文档总页数',
|
|
66
|
+
'need-total-pages',
|
|
67
|
+
'先本地读出页数(PDF 文件可以),或改用正数页码',
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
const resolved = totalPages + value + 1;
|
|
71
|
+
if (resolved < 1) {
|
|
72
|
+
throw new PageRangeError('倒数页码「' + raw + '」超出文档范围(共 ' + totalPages + ' 页)', 'page-out-of-range');
|
|
73
|
+
}
|
|
74
|
+
return resolved;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Collapse an ascending page list into [start, end] runs. */
|
|
78
|
+
function mergeConsecutive(pages) {
|
|
79
|
+
const ranges = [];
|
|
80
|
+
for (const page of pages) {
|
|
81
|
+
const last = ranges[ranges.length - 1];
|
|
82
|
+
if (last && page === last[1] + 1) last[1] = page;
|
|
83
|
+
else ranges.push([page, page]);
|
|
84
|
+
}
|
|
85
|
+
return ranges;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Render runs as a `page_ranges` string (`1-3,5`). */
|
|
89
|
+
function rangesToSpec(ranges) {
|
|
90
|
+
return ranges.map(([start, end]) => (start === end ? String(start) : start + '-' + end)).join(',');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Write an ascending page list as a canonical `page_ranges` string.
|
|
95
|
+
*
|
|
96
|
+
* The single place that turns a page list back into API syntax, so chunk specs
|
|
97
|
+
* and user-supplied specs cannot drift apart.
|
|
98
|
+
* @param {number[]} pages ascending, unique, 1-based
|
|
99
|
+
* @returns {string} e.g. `1-200,202`
|
|
100
|
+
*/
|
|
101
|
+
export function canonicalPageSpec(pages) {
|
|
102
|
+
if (!Array.isArray(pages) || pages.length === 0) throw new TypeError('pages must be a non-empty array');
|
|
103
|
+
let previous = 0;
|
|
104
|
+
for (const page of pages) {
|
|
105
|
+
if (!Number.isInteger(page) || page < 1) throw new TypeError('pages must be positive integers');
|
|
106
|
+
if (page <= previous) throw new TypeError('pages must be ascending and unique');
|
|
107
|
+
previous = page;
|
|
108
|
+
}
|
|
109
|
+
return rangesToSpec(mergeConsecutive(pages));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Parse a `page_ranges` spec into the page list it selects.
|
|
114
|
+
*
|
|
115
|
+
* @param {string} spec e.g. `"2,4-6"`, `"2--2"`
|
|
116
|
+
* @param {{totalPages?: number}} [options] required when the spec uses negative indexes
|
|
117
|
+
* @returns {{pages: number[], canonical: string, offset: number}} `offset` is the
|
|
118
|
+
* 0-based index of the first requested page, i.e. the subset index of page one
|
|
119
|
+
* @throws {PageRangeError} when the spec cannot be planned against locally
|
|
120
|
+
*/
|
|
121
|
+
export function parsePageRanges(spec, options = {}) {
|
|
122
|
+
const totalPages = options.totalPages;
|
|
123
|
+
if (typeof spec !== 'string') throw new TypeError('spec must be a string');
|
|
124
|
+
if (totalPages !== undefined && !isPositiveInt(totalPages)) {
|
|
125
|
+
throw new RangeError('totalPages must be a positive integer when provided');
|
|
126
|
+
}
|
|
127
|
+
const trimmed = spec.trim();
|
|
128
|
+
if (trimmed === '') throw new PageRangeError('pageRanges 不能为空字符串', 'empty-spec');
|
|
129
|
+
|
|
130
|
+
const pages = [];
|
|
131
|
+
let previousMax = 0;
|
|
132
|
+
for (const rawToken of trimmed.split(',')) {
|
|
133
|
+
const token = rawToken.trim();
|
|
134
|
+
if (token === '') {
|
|
135
|
+
throw new PageRangeError('pageRanges 里有多余的逗号:「' + spec + '」', 'empty-token');
|
|
136
|
+
}
|
|
137
|
+
const single = SINGLE.exec(token);
|
|
138
|
+
const range = RANGE.exec(token);
|
|
139
|
+
let start;
|
|
140
|
+
let end;
|
|
141
|
+
if (single) {
|
|
142
|
+
start = resolvePageNumber(single[1], totalPages);
|
|
143
|
+
end = start;
|
|
144
|
+
} else if (range) {
|
|
145
|
+
start = resolvePageNumber(range[1], totalPages);
|
|
146
|
+
end = resolvePageNumber(range[2], totalPages);
|
|
147
|
+
if (start > end) {
|
|
148
|
+
throw new PageRangeError('页码范围「' + token + '」起止倒置(' + start + ' > ' + end + ')', 'reversed-range', '按升序书写,例如 4-6');
|
|
149
|
+
}
|
|
150
|
+
} else if (NEGATIVE_ONLY.test(token)) {
|
|
151
|
+
throw new PageRangeError(
|
|
152
|
+
'不支持单独使用倒数页码「' + token + '」',
|
|
153
|
+
'negative-single',
|
|
154
|
+
'改用范围写法,例如 "2--2" 表示第 2 页到倒数第二页',
|
|
155
|
+
);
|
|
156
|
+
} else {
|
|
157
|
+
throw new PageRangeError('无法识别的页码范围片段「' + token + '」', 'unparsable-token', '支持写法:2、4-6、2--2,逗号分隔');
|
|
158
|
+
}
|
|
159
|
+
if (isPositiveInt(totalPages) && end > totalPages) {
|
|
160
|
+
throw new PageRangeError('页码范围「' + token + '」超出文档范围(共 ' + totalPages + ' 页)', 'page-out-of-range');
|
|
161
|
+
}
|
|
162
|
+
if (start <= previousMax) {
|
|
163
|
+
throw new PageRangeError(
|
|
164
|
+
'页码范围「' + token + '」与前一段重叠或未按升序排列',
|
|
165
|
+
'unsorted-overlap',
|
|
166
|
+
'按升序、不重叠地书写,例如 "2,4-6"',
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
for (let page = start; page <= end; page += 1) pages.push(page);
|
|
170
|
+
previousMax = end;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
pages,
|
|
175
|
+
canonical: canonicalPageSpec(pages),
|
|
176
|
+
offset: pages[0] - 1,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Cut a page list into per-request chunks of at most `maxPagesPerRequest` pages.
|
|
182
|
+
*
|
|
183
|
+
* @param {number[]} pages ascending 1-based page list (the whole request)
|
|
184
|
+
* @param {number} maxPagesPerRequest per-request page cap (200 on the precision API)
|
|
185
|
+
* @returns {Array<{index: number, pages: number[], spec: string, start: number, end: number, offset: number}>}
|
|
186
|
+
* one entry per request; a single entry means the request needs no splitting
|
|
187
|
+
*/
|
|
188
|
+
export function planPageChunks(pages, maxPagesPerRequest) {
|
|
189
|
+
if (!Array.isArray(pages) || pages.length === 0) throw new TypeError('pages must be a non-empty array');
|
|
190
|
+
if (!isPositiveInt(maxPagesPerRequest)) throw new RangeError('maxPagesPerRequest must be a positive integer');
|
|
191
|
+
const chunks = [];
|
|
192
|
+
for (let cursor = 0; cursor < pages.length; cursor += maxPagesPerRequest) {
|
|
193
|
+
const slice = pages.slice(cursor, cursor + maxPagesPerRequest);
|
|
194
|
+
chunks.push({
|
|
195
|
+
index: chunks.length + 1,
|
|
196
|
+
pages: slice,
|
|
197
|
+
spec: canonicalPageSpec(slice),
|
|
198
|
+
start: slice[0],
|
|
199
|
+
end: slice[slice.length - 1],
|
|
200
|
+
offset: slice[0] - 1,
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return chunks;
|
|
204
|
+
}
|