Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: Edit OCR thresholds inline https://github.com/siyuan-note/siyuan/issues/20082

Daniel384d1caa139a
diff --git a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
index 7779b05acf..7c6766665a 100644
--- a/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
+++ b/app/guide/20210808180117-6v0mkxr/20200923234011-ieuun1p/20210808180303-xaduj2o/20200924100744-br924ar.sy
@@ -6,7 +6,7 @@
"id": "20200924100744-br924ar",
"title": "Assets",
"type": "doc",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -967,7 +967,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003636-epvk98g",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -1027,12 +1027,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003073646-xagh51u",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
"Type": "NodeText",
- "Data": "With PaddleOCR selected, click the settings button beside Recognition thresholds in the Advanced group to adjust the detection, text box confidence, and recognition confidence thresholds. Detection and box thresholds must be greater than 0 and less than 1; recognition accepts 0 through 1. Leave fields blank or reset them, then confirm to use the current model’s detection parameters and a recognition threshold of 0.5. Higher thresholds can reduce icons mistaken for text, but may miss blurry or faint text. Thresholds are saved per device and apply to manual and automatic recognition. Existing results remain unchanged; rerun recognition from the image menu when needed."
+ "Data": "With PaddleOCR selected, edit the detection, text box confidence, and recognition confidence thresholds directly in the Recognition thresholds group. Changes are saved automatically when you finish editing a field. Detection and box thresholds must be greater than 0 and less than 1; recognition accepts 0 through 1. Leave a field blank to use the current model’s detection parameters or the default recognition threshold of 0.5. Invalid input stays editable and is not saved. Higher thresholds can reduce icons mistaken for text, but may miss blurry or faint text. Thresholds are saved per device and apply to manual and automatic recognition. Existing results remain unchanged; rerun recognition from the image menu when needed."
}
]
},
diff --git a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
index 9c371fa0d9..50fe8a531d 100644
--- a/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
+++ b/app/guide/20210808180117-czj9bvb/20200812220555-lj3enxa/20210808180321-hbvl5c2/20200915214115-42b8zma.sy
@@ -6,7 +6,7 @@
"id": "20200915214115-42b8zma",
"title": "资源文件",
"type": "doc",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -979,7 +979,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117002036-vmc0mx4",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -1039,12 +1039,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003073646-yye710a",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
"Type": "NodeText",
- "Data": "选择 PaddleOCR 后,可以通过高级分组中识别阈值右侧的设置按钮,分别调整检测阈值、文本框置信度阈值和识别置信度阈值。检测与文本框阈值须大于 0 且小于 1,识别阈值为 0 到 1。留空或重置并确认后,检测使用当前模型参数,识别使用 0.5。提高阈值可以减少图标误识别,但也可能漏掉模糊或较淡的文字。阈值按设备保存,适用于手动和自动识别;不会重新处理已有结果,可通过图片菜单重新识别。"
+ "Data": "选择 PaddleOCR 后,可以在识别阈值分组中直接调整检测阈值、文本框置信度阈值和识别置信度阈值,编辑完成后自动保存。检测与文本框阈值须大于 0 且小于 1,识别阈值为 0 到 1。留空时,检测使用当前模型参数,识别使用默认值 0.5。无效输入会保留在原处供修改,不会保存。提高阈值可以减少图标误识别,但也可能漏掉模糊或较淡的文字。阈值按设备保存,适用于手动和自动识别;不会重新处理已有结果,可通过图片菜单重新识别。"
}
]
},
diff --git a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
index 6a334923b6..958412d8f5 100644
--- a/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
+++ b/app/guide/20211226090932-5lcq56f/20211226115423-d5z1joq/20211226121203-rjjngpz/20211226123038-4umgpxy.sy
@@ -6,7 +6,7 @@
"id": "20211226123038-4umgpxy",
"title": "資料文件",
"type": "doc",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -965,7 +965,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003901-ze4mbzz",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -1025,12 +1025,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003073646-hpqqxqx",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
"Type": "NodeText",
- "Data": "選擇 PaddleOCR 後,可以透過進階群組中辨識閾值右側的設定按鈕,分別調整偵測閾值、文字框信賴度閾值和辨識信賴度閾值。偵測與文字框閾值須大於 0 且小於 1,辨識閾值為 0 到 1。留空或重設並確認後,偵測使用目前模型參數,辨識使用 0.5。提高閾值可以減少圖示誤辨識,但也可能漏掉模糊或較淡的文字。閾值依裝置儲存,適用於手動和自動辨識;不會重新處理既有結果,可透過圖片選單重新辨識。"
+ "Data": "選擇 PaddleOCR 後,可以在辨識閾值群組中直接調整偵測閾值、文字框信心閾值和辨識信心閾值,編輯完成後自動儲存。偵測與文字框閾值須大於 0 且小於 1,辨識閾值為 0 到 1。留空時,偵測使用目前模型參數,辨識使用預設值 0.5。無效輸入會保留在原處供修改,不會儲存。提高閾值可以減少圖示誤判,但也可能遺漏模糊或較淡的文字。閾值按裝置儲存,適用於手動與自動辨識;不會重新處理已有結果,可透過圖片選單重新辨識。"
}
]
},
diff --git a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
index 811817150b..6b746934fb 100644
--- a/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
+++ b/app/guide/20240530133126-axarxgx/20240530101000-4qitucx/20240530101000-g3ugxml/20240530101000-1m5un7l.sy
@@ -7,7 +7,7 @@
"id": "20240530101000-1m5un7l",
"title": "アセット",
"type": "doc",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -1005,7 +1005,7 @@
"Properties": {
"ID": "20240530101000-5bix8t1",
"id": "20240530101000-9evyuhr",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
@@ -1062,12 +1062,12 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003073646-o8u40dy",
- "updated": "20261006112319"
+ "updated": "20261006114009"
},
"Children": [
{
"Type": "NodeText",
- "Data": "PaddleOCR を選択すると、詳細設定グループの認識のしきい値の設定ボタンを押して、検出、テキスト領域の信頼度、認識の信頼度のしきい値を調整できます。検出とテキスト領域のしきい値は 0 より大きく 1 未満、認識しきい値は 0 以上 1 以下です。空欄またはリセット後に確定すると、現在のモデルの検出パラメーターと認識しきい値 0.5 を使用します。値を上げるとアイコンの誤認識を減らせますが、ぼやけた文字や薄い文字を見落とす場合があります。しきい値は端末ごとに保存され、手動認識と自動認識に適用されます。既存の結果は変更されません。必要に応じて画像メニューから再認識してください。"
+ "Data": "PaddleOCR を選択すると、認識のしきい値グループで検出、テキスト領域の信頼度、認識の信頼度のしきい値を直接編集できます。入力の編集を終えると自動保存されます。検出とテキスト領域のしきい値は 0 より大きく 1 未満、認識しきい値は 0 以上 1 以下です。空欄では現在のモデルの検出パラメーター、またはデフォルトの認識しきい値 0.5 を使用します。無効な入力は編集できる状態で残り、保存されません。値を上げるとアイコンの誤認識を減らせますが、ぼやけた文字や薄い文字を見落とす場合があります。しきい値は端末ごとに保存され、手動認識と自動認識に適用されます。既存の結果は変更されません。必要に応じて画像メニューから再認識してください。"
}
]
},
diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.ts
index 23913b10d0..7e539754d9 100644
--- a/app/src/config/ocr.test.ts
+++ b/app/src/config/ocr.test.ts
@@ -16,11 +16,13 @@ test("OCR settings register separate searchable rows in shared desktop and mobil
genConfigItemMainHtml: (title: string, desc: string) => `${title} ${desc}`,
genSwitchRow: (id: string) => `<label><input id="${id}"></label>`,
genButtonRowHtml: (id: string) => `<label><button id="${id}"></button></label>`,
+ genNumberInputHtml: (id: string) => `<input class="b3-text-field" id="${id}" type="number">`,
})});
let group = "";
+ const groupTitles = new Map<string, string>();
const rows: Array<{group: string; key: string; keywords: string[]; html: () => string}> = [];
const tab = {
- group: (id: string) => { group = id; return tab; },
+ group: (id: string, title: string) => { group = id; groupTitles.set(id, title); return tab; },
slot: (spec: Omit<typeof rows[number], "group">) => { rows.push({...spec, group}); return tab; },
};
exports.registerOCRTab(tab);
@@ -30,6 +32,11 @@ test("OCR settings register separate searchable rows in shared desktop and mobil
assert.ok(aiRow.keywords.includes("ocrAIModelTip"));
assert.match(aiRow.html(), /class="b3-select/);
assert.deepEqual(rows.filter(row => row.group === "models").map(row => row.key), ["ocrImportModels", "ocrImport"]);
+ const thresholds = rows.filter(row => row.group === "advanced");
+ assert.equal(groupTitles.get("advanced"), "ocrThresholdSettings");
+ assert.deepEqual(thresholds.map(row => row.key), ["ocrThreshold_detection", "ocrThreshold_box", "ocrThreshold_recognition"]);
+ thresholds.forEach(row => assert.match(row.html(), /type="number"/));
+ assert.doesNotMatch(readFileSync("src/config/ocr.ts", "utf8"), /openOCRThresholds/);
const tabs = readFileSync("src/config/setting/tabs.ts", "utf8");
assert.match(tabs, /ocr: setting\.tab\([\s\S]*?afterMount: mountOCRTab,[\s\S]*?registerOCRTab/);
assert.match(tabs, /ocr: setting\.tab\([\s\S]*?icon: "iconOCR"/);
@@ -56,11 +63,14 @@ const createOCRPanel = async () => {
const controls = Object.fromEntries([
"ocrProvider", "ocrModel", "ocrAIModel", "ocrReasoningEffort", "ocrAuto", "ocrImportModels", "ocrImport",
"detector", "detectorConfig", "recognizer", "recognizerConfig",
- "ocrAdvanced",
+ "ocrThreshold_detection", "ocrThreshold_box", "ocrThreshold_recognition",
].map(id => [id, {
id, value: id === "ocrProvider" ? "paddleocr" : id === "ocrAIModel" || id === "ocrReasoningEffort" ? "" : "tiny", checked: false, disabled: false, innerHTML: "",
files: [{name: `${id}.onnx`}],
- tagName: id === "ocrImport" || id === "ocrAdvanced" ? "BUTTON" : "INPUT",
+ tagName: id === "ocrImport" ? "BUTTON" : "INPUT",
+ validationMessage: "", validity: {badInput: false},
+ setCustomValidity(message: string) { this.validationMessage = message; },
+ reportValidity() { return !this.validationMessage; },
closest: () => ({classList: {toggle() {}}}),
}]));
const listeners = new Map<string, (event: unknown) => Promise<void>>();
@@ -78,8 +88,6 @@ const createOCRPanel = async () => {
}> = [];
const errors: string[] = [];
const notifications = new Map<string, () => void>();
- let advanced: {initial: OCRThresholds; save: (value: OCRThresholds) => Promise<boolean>; destroy: () => void};
- let dialogCloses = 0;
const exports = {} as {mountOCRSettings: (element: unknown) => () => void};
runInNewContext(compiled, {exports, AbortController, window: {siyuan: {config, languages: {ocrThresholdRange: "invalid threshold"}},
addEventListener: (name: string, callback: () => void, options: {signal: AbortSignal}) => {
@@ -91,10 +99,6 @@ const createOCRPanel = async () => {
AI_CONFIG_CHANGED_EVENT: "ai-test",
trackSettingSave: (task: Promise<boolean>) => task,
getReasoningEffortOptions,
- openOCRThresholds: (initial: OCRThresholds, save: (value: OCRThresholds) => Promise<boolean>, onClose: () => void) => {
- advanced = {initial, save, destroy: () => { dialogCloses++; onClose(); }};
- return advanced;
- },
objEquals: (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right),
fetchSyncPost: (url: string, value: typeof config.ocr) => {
if (url === "/api/asset/getOCRConfig") {
@@ -114,10 +118,19 @@ const createOCRPanel = async () => {
})});
const close = exports.mountOCRSettings(root);
await new Promise(setImmediate);
+ const inputThreshold = (key: keyof OCRThresholds, value: string, badInput = false) => {
+ const control = controls[`ocrThreshold_${key}`];
+ control.value = value;
+ control.validity.badInput = badInput;
+ listeners.get("input")({target: control});
+ };
return {
controls, config, requests, errors, close, renders: () => renders,
- openAdvanced: () => listeners.get("click")({target: {closest: () => controls.ocrAdvanced}, stopPropagation() {}}),
- advanced: () => advanced, dialogCloses: () => dialogCloses,
+ inputThreshold,
+ changeThreshold: (key: keyof OCRThresholds, value: string, badInput = false) => {
+ inputThreshold(key, value, badInput);
+ return listeners.get("change")({target: controls[`ocrThreshold_${key}`], stopPropagation() {}});
+ },
reads: () => reads, snapshot, readRequests,
notify: () => notifications.get("ocr-test")?.(),
notifyAI: () => notifications.get("ai-test")?.(),
@@ -155,6 +168,7 @@ test("selecting AI uses a separate model and requires opting into automatic reco
assert.equal(panel.requests[0].config.auto, false);
assert.equal(panel.controls.ocrModel.disabled, true);
assert.equal(panel.controls.ocrAIModel.disabled, false);
+ assert.equal(panel.controls.ocrThreshold_detection.disabled, true);
panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
await saving;
assert.doesNotMatch(panel.controls.ocrAIModel.innerHTML, /value=""/);
@@ -270,29 +284,99 @@ for (const networkFailure of [false, true]) {
});
}
-test("advanced OCR settings receive the latest thresholds and use the panel save queue", async () => {
+test("inline thresholds receive notifications and save consecutive edits in order", async () => {
const panel = await createOCRPanel();
panel.updateServer({provider: "paddleocr", model: "tiny", auto: false,
thresholds: {detection: 0.4, box: 0.7, recognition: 0.8}});
panel.notify();
await new Promise(setImmediate);
const renders = panel.renders();
- await panel.openAdvanced();
- assert.equal(panel.advanced().initial.box, 0.7);
- const saving = panel.advanced().save({detection: 0.5, box: 0.8, recognition: 0.9});
+ assert.equal(panel.controls.ocrThreshold_box.value, "0.7");
+ const saving = panel.changeThreshold("detection", "0.5");
await new Promise(setImmediate);
+ const second = panel.changeThreshold("box", "0.8");
panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
- assert.equal(await saving, true);
- assert.equal(panel.config.ocr.thresholds.recognition, 0.9);
+ await saving;
+ await new Promise(setImmediate);
+ assert.deepEqual({...panel.requests[1].config.thresholds}, {detection: 0.5, box: 0.8, recognition: 0.8});
+ panel.requests[1].resolve({code: 0, data: panel.requests[1].config});
+ await second;
const toggle = panel.changeAuto(true);
await new Promise(setImmediate);
- assert.equal(panel.requests[1].config.thresholds, undefined);
- panel.requests[1].resolve({code: 0, data: {...panel.requests[1].config, thresholds: panel.config.ocr.thresholds}});
+ assert.equal(panel.requests[2].config.thresholds, undefined);
+ panel.requests[2].resolve({code: 0, data: {...panel.requests[2].config, thresholds: panel.config.ocr.thresholds}});
await toggle;
- assert.equal(panel.config.ocr.thresholds.recognition, 0.9);
+ assert.equal(panel.config.ocr.thresholds.box, 0.8);
assert.equal(panel.renders(), renders);
panel.close();
- assert.equal(panel.dialogCloses(), 1);
+});
+
+test("inline thresholds reject invalid ranges and partial numbers, retain edits and accept zero confidence", async () => {
+ const panel = await createOCRPanel();
+ for (const [key, value, badInput] of [
+ ["detection", "0", false], ["box", "1", false], ["recognition", "-0.1", false],
+ ["recognition", "1.1", false], ["detection", "Infinity", false], ["detection", "", true],
+ ] as const) {
+ await panel.changeThreshold(key, value, badInput);
+ assert.equal(panel.requests.length, 0);
+ assert.equal(panel.controls[`ocrThreshold_${key}`].validationMessage, "invalid threshold");
+ panel.notify();
+ await new Promise(setImmediate);
+ assert.equal(panel.controls[`ocrThreshold_${key}`].value, value);
+ }
+ const zero = panel.changeThreshold("recognition", "0");
+ await new Promise(setImmediate);
+ assert.equal(panel.requests[0].config.thresholds.recognition, 0);
+ panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
+ await zero;
+ assert.equal(panel.controls.ocrThreshold_recognition.value, "0");
+ const defaults = panel.changeThreshold("recognition", "");
+ await new Promise(setImmediate);
+ assert.equal(panel.requests[1].config.thresholds.recognition, null);
+ panel.requests[1].resolve({code: 0, data: panel.requests[1].config});
+ await defaults;
+ assert.equal(panel.controls.ocrThreshold_recognition.value, "");
+ panel.close();
+});
+
+test("failed inline saves restore confirmed values while preserving new input during an in-flight save", async () => {
+ const panel = await createOCRPanel();
+ panel.updateServer({provider: "paddleocr", model: "tiny", auto: false,
+ thresholds: {detection: 0.4, box: 0.7, recognition: 0.8}});
+ panel.notify();
+ await new Promise(setImmediate);
+ const saving = panel.changeThreshold("box", "0.9");
+ await new Promise(setImmediate);
+ panel.inputThreshold("detection", "0.6");
+ panel.requests[0].resolve({code: -1});
+ await saving;
+ assert.equal(panel.controls.ocrThreshold_box.value, "0.7");
+ assert.equal(panel.controls.ocrThreshold_detection.value, "0.6");
+ panel.updateServer({...panel.config.ocr, thresholds: {detection: 0.3, box: 0.5, recognition: 0.9}});
+ panel.notify();
+ await new Promise(setImmediate);
+ assert.equal(panel.controls.ocrThreshold_detection.value, "0.6");
+ assert.equal(panel.controls.ocrThreshold_box.value, "0.5");
+ const next = panel.changeThreshold("box", "0.8");
+ await new Promise(setImmediate);
+ assert.deepEqual({...panel.requests[1].config.thresholds}, {detection: 0.3, box: 0.8, recognition: 0.9});
+ panel.requests[1].resolve({code: 0, data: panel.requests[1].config});
+ await next;
+ assert.equal(panel.controls.ocrThreshold_detection.value, "0.6");
+ panel.close();
+});
+
+test("undoing an uncommitted threshold edit resumes updates from another window", async () => {
+ const panel = await createOCRPanel();
+ panel.inputThreshold("detection", "0.6");
+ panel.inputThreshold("detection", "");
+ panel.updateServer({provider: "paddleocr", model: "tiny", auto: false,
+ thresholds: {detection: 0.4, box: 0.7, recognition: 0.8}});
+ panel.notify();
+ await new Promise(setImmediate);
+ assert.equal(panel.controls.ocrThreshold_detection.value, "0.4");
+ assert.equal(panel.requests.length, 0);
+ panel.close();
});
test("closing the OCR panel cancels queued saves and ignores a late response", async () => {
diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.ts
index 74623d5c1b..746ec57af9 100644
--- a/app/src/config/ocr.ts
+++ b/app/src/config/ocr.ts
@@ -3,11 +3,10 @@ import {fetchSyncPost} from "../util/fetch";
import {ContractFormData} from "../util/contractFormData";
import {escapeAttr, escapeHtml} from "../util/escape";
import {genConfigItemMainHtml, genSwitchRow} from "./render/fragments";
-import {genButtonRowHtml} from "./render/render";
+import {genButtonRowHtml, genNumberInputHtml} from "./render/render";
import {showMessage} from "../dialog/message";
import {OCR_CHANGED_EVENT} from "./ocrRuntime";
import {objEquals} from "../util/functions";
-import {openOCRThresholds} from "./ocrThresholds";
import {AI_CONFIG_CHANGED_EVENT} from "./tabs/ai/aiRuntime";
import type {SettingTabBuilder} from "./setting/builder";
import {trackSettingSave} from "./setting/pending";
@@ -36,6 +35,12 @@ const getModelFiles = () => [
{id: "recognizerConfig", title: `${window.siyuan.languages.ocrRecognizer} - YAML`, suffix: "yml,yaml"},
];
+const getThresholdFields = () => [
+ {key: "detection", title: window.siyuan.languages.ocrDetectionThreshold, placeholder: window.siyuan.languages.ocrModelDefault},
+ {key: "box", title: window.siyuan.languages.ocrBoxThreshold, placeholder: window.siyuan.languages.ocrModelDefault},
+ {key: "recognition", title: window.siyuan.languages.ocrRecognitionThreshold, placeholder: "0.5"},
+] as const;
+
export const registerOCRTab = (tab: SettingTabBuilder) => {
const languages = window.siyuan.languages;
tab.group("general", "OCR").slot({
@@ -59,10 +64,14 @@ export const registerOCRTab = (tab: SettingTabBuilder) => {
keywords: [languages.reasoningEffortTooltip, languages.ocrReasoningEffortTip],
html: () => selectRow("ocrReasoningEffort", languages.reasoningEffortTooltip, languages.ocrReasoningEffortTip),
});
- tab.group("advanced", languages.configGroupAdvanced).slot({
- key: "ocrAdvanced",
- keywords: [languages.ocrThresholdSettings, languages.ocrDetectionThreshold, languages.ocrBoxThreshold, languages.ocrRecognitionThreshold],
- html: () => genButtonRowHtml("ocrAdvanced", languages.ocrThresholdSettings, undefined, languages.config, "iconSettings"),
+ const thresholds = tab.group("advanced", languages.ocrThresholdSettings);
+ getThresholdFields().forEach(field => {
+ thresholds.slot({
+ key: `ocrThreshold_${field.key}`,
+ keywords: [field.title, languages.ocrThresholdsTip],
+ html: () => `<label class="fn__flex b3-label config-item">${genConfigItemMainHtml(field.title, field.key === "detection" ? languages.ocrThresholdsTip : undefined)}
+<span class="fn__space"></span>${genNumberInputHtml(`ocrThreshold_${field.key}`, "", 0, 1, "any")}</label>`,
+ });
});
tab.group("models", languages.ocrImportModels).slot({
key: "ocrImportModels",
@@ -83,16 +92,32 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
let busy = false;
let pendingSaves = 0;
let saveQueue = Promise.resolve(false);
- let thresholdDialog: ReturnType<typeof openOCRThresholds>;
let refreshPending = false;
let refreshTask: Promise<void>;
let writeRevision = 0;
const languages = window.siyuan.languages;
const files = getModelFiles();
+ const thresholdFields = getThresholdFields();
+ const dirtyThresholds = new Set<keyof OCRThresholds>();
+ let thresholdValues: OCRThresholds;
+ const updateThresholdInputs = () => {
+ thresholdValues = {
+ detection: data.config.thresholds?.detection ?? null,
+ box: data.config.thresholds?.box ?? null,
+ recognition: data.config.thresholds?.recognition ?? null,
+ };
+ thresholdFields.forEach(field => {
+ if (!dirtyThresholds.has(field.key)) {
+ const input = root.querySelector<HTMLInputElement>(`#ocrThreshold_${field.key}`);
+ input.value = `${thresholdValues[field.key] ?? ""}`;
+ input.setCustomValidity("");
+ }
+ });
+ };
const updateControls = () => {
const isPaddleOCR = root.querySelector<HTMLSelectElement>("#ocrProvider").value === "paddleocr";
const isAI = root.querySelector<HTMLSelectElement>("#ocrProvider").value === "ai";
- ["ocrModel", "ocrImportModels", "ocrImport", "ocrAdvanced"].forEach(id => {
+ ["ocrModel", "ocrImportModels", "ocrImport"].forEach(id => {
root.querySelector(`#${id}`).closest(".config-item").classList.toggle("fn__none", !isPaddleOCR);
});
root.querySelector("#ocrAIModel").closest(".config-item").classList.toggle("fn__none", !isAI);
@@ -100,13 +125,15 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
["advanced", "models"].forEach(group => {
root.querySelector(`[data-config-group-id="${group}"]`)?.classList.toggle("fn__none", !isPaddleOCR);
});
- if (!isPaddleOCR) thresholdDialog?.destroy();
root.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLButtonElement>("input, select, button").forEach(element => {
element.disabled = busy || (element.tagName === "BUTTON" && pendingSaves > 0);
});
root.querySelector<HTMLSelectElement>("#ocrModel").disabled = busy || !isPaddleOCR;
root.querySelector<HTMLSelectElement>("#ocrAIModel").disabled = busy || !isAI;
root.querySelector<HTMLSelectElement>("#ocrReasoningEffort").disabled = busy || !isAI;
+ thresholdFields.forEach(field => {
+ root.querySelector<HTMLInputElement>(`#ocrThreshold_${field.key}`).disabled = busy || !isPaddleOCR;
+ });
root.querySelector<HTMLButtonElement>("#ocrImport").disabled = busy || pendingSaves > 0 || !isPaddleOCR || files.some(file => !root.querySelector<HTMLInputElement>(`#${file.id}`).files?.length);
};
const providerOptions = () => {
@@ -152,6 +179,7 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
root.querySelector<HTMLSelectElement>("#ocrAIModel").value = data.config.aiModelId || "";
root.querySelector<HTMLSelectElement>("#ocrReasoningEffort").value = data.config.reasoningEffort || "";
root.querySelector<HTMLInputElement>("#ocrAuto").checked = data.config.auto;
+ updateThresholdInputs();
updateControls();
};
const render = () => {
@@ -204,6 +232,9 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
root.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLButtonElement>("input, select, button").forEach(element => {
element.disabled = true;
});
+ thresholdFields.forEach(field => {
+ root.querySelector<HTMLInputElement>(`#ocrThreshold_${field.key}`).placeholder = field.placeholder;
+ });
window.addEventListener(OCR_CHANGED_EVENT, () => { void load().catch(handleError); }, {signal: controller.signal});
window.addEventListener(AI_CONFIG_CHANGED_EVENT, () => { void load().catch(handleError); }, {signal: controller.signal});
const saveConfig = async (thresholds?: OCRThresholds): Promise<boolean> => {
@@ -245,6 +276,7 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
root.querySelector<HTMLSelectElement>("#ocrAIModel").innerHTML = aiModelOptions();
root.querySelector<HTMLSelectElement>("#ocrAIModel").value = data.config.aiModelId || "";
root.querySelector<HTMLSelectElement>("#ocrReasoningEffort").value = data.config.reasoningEffort || "";
+ updateThresholdInputs();
updateControls();
if (refreshPending) void load().catch(handleError);
}
@@ -254,6 +286,18 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
saveQueue = saveQueue.then(save, save);
return trackSettingSave(saveQueue);
};
+ root.addEventListener("input", event => {
+ const input = event.target as HTMLInputElement;
+ const field = thresholdFields.find(field => input.id === `ocrThreshold_${field.key}`);
+ if (field) {
+ if (input.validity.badInput || input.value !== `${thresholdValues?.[field.key] ?? ""}`) {
+ dirtyThresholds.add(field.key);
+ } else {
+ dirtyThresholds.delete(field.key);
+ }
+ input.setCustomValidity("");
+ }
+ }, {signal: controller.signal});
root.addEventListener("change", async event => {
event.stopPropagation();
const target = event.target as HTMLInputElement | HTMLSelectElement;
@@ -262,6 +306,22 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
return;
}
if (!data) return;
+ const field = thresholdFields.find(field => target.id === `ocrThreshold_${field.key}`);
+ if (field) {
+ const input = target as HTMLInputElement;
+ const value = input.value === "" ? null : Number(input.value);
+ const invalid = input.validity.badInput || value !== null && (!Number.isFinite(value) ||
+ (field.key === "recognition" ? value < 0 || value > 1 : value <= 0 || value >= 1));
+ input.setCustomValidity(invalid ? languages.ocrThresholdRange : "");
+ if (!input.reportValidity()) {
+ dirtyThresholds.add(field.key);
+ return;
+ }
+ dirtyThresholds.delete(field.key);
+ thresholdValues = {...thresholdValues, [field.key]: value};
+ await saveConfig({...thresholdValues});
+ return;
+ }
if (target.id === "ocrProvider" && target.value === "ai" && data.config.provider !== "ai") {
root.querySelector<HTMLInputElement>("#ocrAuto").checked = false;
if (!data.config.aiModelId && data.aiModels?.length) {
@@ -277,11 +337,6 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
if (!button || busy || pendingSaves > 0 || !data) {
return;
}
- if (button.id === "ocrAdvanced") {
- thresholdDialog?.destroy();
- thresholdDialog = openOCRThresholds(data.config.thresholds, saveConfig, () => { thresholdDialog = undefined; });
- return;
- }
if (button.id === "ocrImport") {
writeRevision++;
busy = true;
@@ -314,7 +369,6 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
});
return () => {
closed = true;
- thresholdDialog?.destroy();
controller.abort();
};
};
diff --git a/app/src/config/ocrThresholds.test.ts b/app/src/config/ocrThresholds.test.ts
deleted file mode 100644
index e985deb189..0000000000
--- a/app/src/config/ocrThresholds.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import * as assert from "node:assert/strict";
-import {readFileSync} from "node:fs";
-import {test} from "node:test";
-import {runInNewContext} from "node:vm";
-import {ModuleKind, ScriptTarget, transpileModule} from "typescript";
-import type {OCRThresholds} from "../types/api";
-
-const createDialog = (mobile = false, initial: OCRThresholds = {detection: 0.4, box: 0.7, recognition: 0.8}) => {
- const compiled = transpileModule(readFileSync("src/config/ocrThresholds.ts", "utf8"), {
- compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
- }).outputText;
- const inputs = Object.fromEntries(Object.entries(initial).map(([key, value]) => [key, {
- value: value?.toString() ?? "", disabled: false, tagName: "INPUT", message: "",
- setCustomValidity(message: string) { this.message = message; },
- reportValidity() { return !this.message; },
- }]));
- const listeners = new Map<string, (event: unknown) => Promise<void>>();
- let options: {width: string; content: string; destroyCallback: () => void};
- let destroyed = 0;
- let closed = 0;
- class Dialog {
- element = {
- addEventListener: (event: string, listener: (event: unknown) => Promise<void>) => listeners.set(event, listener),
- querySelector: (selector: string) => inputs[selector.substring(5)],
- querySelectorAll: () => Object.values(inputs),
- };
- constructor(value: typeof options) { options = value; }
- destroy() { destroyed++; options.destroyCallback(); }
- }
- const requests: Array<{value: OCRThresholds; resolve: (success: boolean) => void}> = [];
- const exports = {} as {openOCRThresholds: (value: OCRThresholds, save: (value: OCRThresholds) => Promise<boolean>, close: () => void) => Dialog};
- runInNewContext(compiled, {exports, window: {siyuan: {languages: {
- ocrDetectionThreshold: "Detection", ocrBoxThreshold: "Box", ocrRecognitionThreshold: "Recognition",
- ocrThresholdRange: "invalid threshold", ocrModelDefault: "Model default", configGroupAdvanced: "Advanced",
- ocrThresholdsTip: "Leave blank to use defaults",
- }}}, require: () => ({Dialog, isMobile: () => mobile, escapeAttr: (value: string) => value})});
- const dialog = exports.openOCRThresholds(initial, value => new Promise(resolve => requests.push({value, resolve})), () => { closed++; });
- const click = (action: string) => listeners.get("click")({target: {closest: () => ({dataset: {action}})}});
- return {dialog, inputs, requests, click, options, destroyed: () => destroyed, closed: () => closed};
-};
-
-for (const mobile of [false, true]) {
- test(`OCR settings use the shared dialog and preserve draft values until confirmed (mobile=${mobile})`, async () => {
- const panel = createDialog(mobile);
- assert.equal(panel.options.width, mobile ? "92vw" : "520px");
- assert.doesNotMatch(panel.options.content, /<details|<summary/);
- assert.match(panel.options.content, /b3-dialog__content/);
- assert.match(panel.options.content, /Leave blank to use defaults/);
- assert.match(panel.options.content, /id="ocr-detection"[^>]*placeholder="Model default"/);
- assert.match(panel.options.content, /id="ocr-box"[^>]*placeholder="Model default"/);
- assert.match(panel.options.content, /id="ocr-recognition"[^>]*placeholder="0.5"/);
- panel.inputs.detection.value = "0.6";
- assert.equal(panel.requests.length, 0);
- const saving = panel.click("save");
- assert.equal(panel.requests[0].value.detection, 0.6);
- assert.equal(panel.requests[0].value.box, 0.7);
- assert.equal(panel.inputs.detection.disabled, true);
- await panel.click("save");
- assert.equal(panel.requests.length, 1);
- panel.requests[0].resolve(true);
- await saving;
- assert.equal(panel.destroyed(), 1);
- assert.equal(panel.closed(), 1);
- });
-}
-
-test("reset clears overrides, cancellation does not save, and confirmation persists defaults", async () => {
- const cancelled = createDialog();
- await cancelled.click("reset");
- assert.equal(cancelled.inputs.detection.value, "");
- await cancelled.click("cancel");
- assert.equal(cancelled.requests.length, 0);
- const panel = createDialog();
- await panel.click("reset");
- const saving = panel.click("save");
- assert.equal(JSON.stringify(panel.requests[0].value), JSON.stringify({detection: null, box: null, recognition: null}));
- panel.requests[0].resolve(true);
- await saving;
-});
-
-test("invalid thresholds stay editable and cannot be submitted; zero recognition confidence is accepted", async () => {
- const panel = createDialog();
- for (const value of ["0", "1", "-0.1", "NaN", "Infinity"]) {
- panel.inputs.detection.value = value;
- await panel.click("save");
- assert.equal(panel.requests.length, 0);
- assert.equal(panel.inputs.detection.message, "invalid threshold");
- }
- panel.inputs.detection.value = "";
- panel.inputs.recognition.value = "0";
- const saving = panel.click("save");
- assert.equal(panel.requests[0].value.recognition, 0);
- panel.requests[0].resolve(false);
- await saving;
- assert.equal(panel.destroyed(), 0);
- assert.equal(panel.inputs.recognition.disabled, false);
- assert.equal(panel.inputs.recognition.value, "0");
-});
-
-test("a late save response cannot close an already destroyed threshold dialog twice", async () => {
- const panel = createDialog();
- const saving = panel.click("save");
- panel.dialog.destroy();
- panel.requests[0].resolve(true);
- await saving;
- assert.equal(panel.destroyed(), 1);
-});
diff --git a/app/src/config/ocrThresholds.ts b/app/src/config/ocrThresholds.ts
deleted file mode 100644
index d90cbf3d5f..0000000000
--- a/app/src/config/ocrThresholds.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import type {OCRThresholds} from "../types/api";
-import {Dialog} from "../dialog";
-import {isMobile} from "../util/functions";
-import {escapeAttr} from "../util/escape";
-
-export const openOCRThresholds = (
- initial: OCRThresholds | undefined | null,
- save: (value: OCRThresholds) => Promise<boolean>,
- onClose: () => void,
-): Dialog => {
- const languages = window.siyuan.languages;
- const fields = [
- {key: "detection", title: languages.ocrDetectionThreshold, placeholder: languages.ocrModelDefault},
- {key: "box", title: languages.ocrBoxThreshold, placeholder: languages.ocrModelDefault},
- {key: "recognition", title: languages.ocrRecognitionThreshold, placeholder: "0.5"},
- ] as const;
- let closed = false;
- let saving = false;
- const dialog = new Dialog({
- title: `PaddleOCR - ${languages.ocrThresholdSettings}`,
- width: isMobile() ? "92vw" : "520px",
- content: `<div class="b3-dialog__content">
-<div class="b3-label__text">${languages.ocrThresholdsTip}</div><div class="fn__hr--b"></div>
-${fields.map(({key, title, placeholder}) => `<div class="b3-label b3-label--inner">
-<label class="config-name fn__block" for="ocr-${key}">${title}</label><div class="fn__hr"></div>
-<input id="ocr-${key}" class="b3-text-field fn__block" type="number" min="0" max="1" step="any" value="${initial?.[key] ?? ""}" placeholder="${escapeAttr(placeholder)}"></div>`).join("")}
-</div><div class="b3-dialog__action">
-<button class="b3-button b3-button--outline" data-action="reset">${languages.reset}</button><div class="fn__flex-1"></div>
-<button class="b3-button b3-button--cancel" data-action="cancel">${languages.cancel}</button><div class="fn__space"></div>
-<button class="b3-button b3-button--text" data-action="save">${languages.confirm}</button></div>`,
- destroyCallback: () => { closed = true; onClose(); },
- });
- dialog.element.addEventListener("input", event => {
- const input = event.target as HTMLInputElement;
- if (input.tagName === "INPUT") input.setCustomValidity("");
- });
- dialog.element.addEventListener("click", async event => {
- const button = (event.target as HTMLElement).closest<HTMLButtonElement>("button[data-action]");
- if (!button || saving || closed) return;
- if (button.dataset.action === "cancel") {
- dialog.destroy();
- return;
- }
- if (button.dataset.action === "reset") {
- fields.forEach(({key}) => {
- const input = dialog.element.querySelector<HTMLInputElement>(`#ocr-${key}`);
- input.value = "";
- input.setCustomValidity("");
- });
- return;
- }
- const value: OCRThresholds = {detection: null, box: null, recognition: null};
- for (const {key} of fields) {
- const input = dialog.element.querySelector<HTMLInputElement>(`#ocr-${key}`);
- const number = input.value === "" ? null : Number(input.value);
- const invalid = number !== null && (!Number.isFinite(number) ||
- (key === "recognition" ? number < 0 || number > 1 : number <= 0 || number >= 1));
- input.setCustomValidity(invalid ? languages.ocrThresholdRange : "");
- if (!input.reportValidity()) return;
- value[key] = number;
- }
- saving = true;
- dialog.element.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(control => { control.disabled = true; });
- try {
- if (await save(value) && !closed) dialog.destroy();
- } finally {
- saving = false;
- if (!closed) {
- dialog.element.querySelectorAll<HTMLInputElement | HTMLButtonElement>("input, button").forEach(control => { control.disabled = false; });
- }
- }
- });
- return dialog;
-};
diff --git a/app/src/config/render/render.ts b/app/src/config/render/render.ts
index 55e9252d32..d22669a709 100644
--- a/app/src/config/render/render.ts
+++ b/app/src/config/render/render.ts
@@ -15,7 +15,7 @@ import {genConfigItemMainHtml, genConfigItemName, genSwitchRow} from "./fragment
export const genNumberInputHtml = (
id: string,
- value: number,
+ value: number | "",
min?: number,
max?: number,
step?: string,