An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: Add PaddleOCR threshold settings https://github.com/siyuan-note/siyuan/issues/19984
Danielfaba6a8c8d74
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.jsonindex d88a4bad00..6c25b4bffa 100644--- a/app/appearance/langs/ar.json+++ b/app/appearance/langs/ar.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "عتبة الكشف",+ "ocrBoxThreshold": "عتبة الثقة لمربعات النص",+ "ocrRecognitionThreshold": "عتبة الثقة للتعرف",+ "ocrThresholdsTip": "اترك الحقل فارغًا لاستخدام إعدادات الكشف للنموذج وعتبة التعرف 0.5؛ القيم الأعلى تقلل التعرف الخاطئ لكنها قد تفوّت نصوصًا؛ ينطبق على عمليات التعرف اللاحقة فقط",+ "ocrThresholdRange": "يجب أن تكون عتبتا الكشف والمربعات أكبر من 0 وأقل من 1، وعتبة التعرف بين 0 و1","automationIncomplete": "القاعدة متوقفة؛ أكمل الإعداد: ${1}","databaseAutomations": "أتمتة","automationTip": "تسري القواعد على جميع طرق العرض. يُتراجع عن التعديلات الأصلية والإجراءات التلقائية معًا وتُستعاد الحالة السابقة عند الفشل. لا تُشغّل الإجراءات التلقائية قواعد أخرى",diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.jsonindex 9215bc288a..fdbd094ece 100644--- a/app/appearance/langs/de.json+++ b/app/appearance/langs/de.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Erkennungsschwelle für Textbereiche",+ "ocrBoxThreshold": "Konfidenzschwelle für Textrahmen",+ "ocrRecognitionThreshold": "Konfidenzschwelle für Texterkennung",+ "ocrThresholdsTip": "Leer lassen für die Erkennungsparameter des Modells und eine Texterkennungsschwelle von 0.5; höhere Werte reduzieren Fehlerkennungen, können aber Text übersehen; gilt nur für künftige Erkennungen",+ "ocrThresholdRange": "Bereichs- und Rahmenschwellen müssen größer als 0 und kleiner als 1 sein; die Texterkennungsschwelle muss zwischen 0 und 1 liegen","automationIncomplete": "Regel pausiert; Konfiguration vervollständigen: ${1}","databaseAutomations": "Automatisierungen","automationTip": "Regeln gelten für alle Ansichten. Ausgangsänderungen und automatische Aktionen werden gemeinsam rückgängig gemacht und bei Fehlern zurückgesetzt. Automatische Aktionen lösen keine weiteren Regeln aus",diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.jsonindex bcaee6c7c8..ffbda360eb 100644--- a/app/appearance/langs/en.json+++ b/app/appearance/langs/en.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Detection threshold",+ "ocrBoxThreshold": "Text box confidence threshold",+ "ocrRecognitionThreshold": "Recognition confidence threshold",+ "ocrThresholdsTip": "Leave blank to use model detection parameters and a recognition threshold of 0.5; higher thresholds reduce false positives but may miss text; applies to future recognition only",+ "ocrThresholdRange": "Detection and box thresholds must be greater than 0 and less than 1; recognition must be between 0 and 1","automationIncomplete": "Rule paused; complete the configuration: ${1}","databaseAutomations": "Automations","automationTip": "Rules apply to all views. Source edits and automatic actions are undone together and rolled back on failure. Automatic actions do not trigger other rules",diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.jsonindex 6a6220ee4c..cda7825e14 100644--- a/app/appearance/langs/es.json+++ b/app/appearance/langs/es.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Umbral de detección",+ "ocrBoxThreshold": "Umbral de confianza de los cuadros de texto",+ "ocrRecognitionThreshold": "Umbral de confianza de reconocimiento",+ "ocrThresholdsTip": "Dejar vacío para usar los parámetros de detección del modelo y un umbral de reconocimiento de 0.5; los valores altos reducen falsos positivos, pero pueden omitir texto; solo afecta a futuros reconocimientos",+ "ocrThresholdRange": "Los umbrales de detección y de cuadros deben ser mayores que 0 y menores que 1; el de reconocimiento debe estar entre 0 y 1","automationIncomplete": "Regla pausada; completa la configuración: ${1}","databaseAutomations": "Automatizaciones","automationTip": "Las reglas se aplican a todas las vistas. Los cambios originales y las acciones automáticas se deshacen juntos y se revierten si hay un error. Las acciones automáticas no activan otras reglas",diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.jsonindex ba913c703d..01182fdcf3 100644--- a/app/appearance/langs/fr.json+++ b/app/appearance/langs/fr.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Seuil de détection",+ "ocrBoxThreshold": "Seuil de confiance des zones de texte",+ "ocrRecognitionThreshold": "Seuil de confiance de reconnaissance",+ "ocrThresholdsTip": "Laisser vide pour utiliser les paramètres de détection du modèle et un seuil de reconnaissance de 0.5 ; des seuils plus élevés réduisent les faux positifs mais peuvent omettre du texte ; uniquement pour les prochaines reconnaissances",+ "ocrThresholdRange": "Les seuils de détection et des zones doivent être strictement compris entre 0 et 1 ; celui de reconnaissance doit être compris entre 0 et 1 inclus","automationIncomplete": "Règle suspendue ; complétez la configuration : ${1}","databaseAutomations": "Automatisations","automationTip": "Les règles s’appliquent à toutes les vues. Les modifications initiales et les actions automatiques sont annulées ensemble et restaurées en cas d’échec. Les actions automatiques ne déclenchent pas d’autres règles",diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.jsonindex e935f93bf1..2ddeba8515 100644--- a/app/appearance/langs/he.json+++ b/app/appearance/langs/he.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "סף זיהוי אזורים",+ "ocrBoxThreshold": "סף ביטחון לתיבות טקסט",+ "ocrRecognitionThreshold": "סף ביטחון לזיהוי טקסט",+ "ocrThresholdsTip": "יש להשאיר ריק לשימוש בפרמטרי זיהוי האזורים של המודל ובסף זיהוי טקסט של 0.5; ערכים גבוהים מפחיתים זיהוי שגוי אך עלולים להחמיץ טקסט; חל רק על זיהויים עתידיים",+ "ocrThresholdRange": "ספי זיהוי האזורים והתיבות חייבים להיות גדולים מ־0 וקטנים מ־1; סף זיהוי הטקסט חייב להיות בין 0 ל־1","automationIncomplete": "הכלל מושהה; יש להשלים את ההגדרות: ${1}","databaseAutomations": "אוטומציות","automationTip": "הכללים חלים על כל התצוגות. העריכות המקוריות והפעולות האוטומטיות מבוטלות יחד ומשוחזרות במקרה של כשל. פעולות אוטומטיות אינן מפעילות כללים אחרים",diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.jsonindex 2249c12605..1f5e8cf2ee 100644--- a/app/appearance/langs/hi.json+++ b/app/appearance/langs/hi.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "पहचान क्षेत्र की सीमा",+ "ocrBoxThreshold": "टेक्स्ट बॉक्स विश्वास सीमा",+ "ocrRecognitionThreshold": "अक्षर पहचान विश्वास सीमा",+ "ocrThresholdsTip": "मॉडल के पहचान पैरामीटर और 0.5 अक्षर पहचान सीमा के लिए खाली छोड़ें; अधिक सीमा गलत पहचान घटाती है लेकिन कुछ टेक्स्ट छूट सकता है; केवल आगे की पहचान पर लागू",+ "ocrThresholdRange": "क्षेत्र और बॉक्स की सीमाएँ 0 से बड़ी और 1 से छोटी हों; अक्षर पहचान की सीमा 0 से 1 के बीच हो","automationIncomplete": "नियम रोका गया है; कॉन्फ़िगरेशन पूरा करें: ${1}","databaseAutomations": "स्वचालन","automationTip": "नियम सभी दृश्यों पर लागू होते हैं। मूल संपादन और स्वचालित कार्रवाइयाँ एक साथ पूर्ववत होती हैं और विफलता पर सभी बदलाव वापस हो जाते हैं। स्वचालित कार्रवाइयाँ अन्य नियमों को शुरू नहीं करतीं",diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.jsonindex 08c2c706b2..5aa9d820e5 100644--- a/app/appearance/langs/id.json+++ b/app/appearance/langs/id.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Ambang deteksi",+ "ocrBoxThreshold": "Ambang keyakinan kotak teks",+ "ocrRecognitionThreshold": "Ambang keyakinan pengenalan",+ "ocrThresholdsTip": "Kosongkan untuk memakai parameter deteksi model dan ambang pengenalan 0.5; ambang lebih tinggi mengurangi kesalahan tetapi dapat melewatkan teks; hanya berlaku untuk pengenalan berikutnya",+ "ocrThresholdRange": "Ambang deteksi dan kotak harus lebih besar dari 0 dan lebih kecil dari 1; ambang pengenalan harus antara 0 dan 1","automationIncomplete": "Aturan dijeda; lengkapi konfigurasi: ${1}","databaseAutomations": "Otomatisasi","automationTip": "Aturan berlaku untuk semua tampilan. Perubahan sumber dan tindakan otomatis dibatalkan bersama serta dipulihkan jika gagal. Tindakan otomatis tidak memicu aturan lain",diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.jsonindex 94b30eb9bc..2baf3490c4 100644--- a/app/appearance/langs/it.json+++ b/app/appearance/langs/it.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Soglia di rilevamento",+ "ocrBoxThreshold": "Soglia di confidenza dei riquadri di testo",+ "ocrRecognitionThreshold": "Soglia di confidenza del riconoscimento",+ "ocrThresholdsTip": "Lasciare vuoto per usare i parametri di rilevamento del modello e una soglia di riconoscimento di 0.5; valori più alti riducono i falsi positivi ma possono omettere testo; si applica solo ai riconoscimenti successivi",+ "ocrThresholdRange": "Le soglie di rilevamento e dei riquadri devono essere maggiori di 0 e minori di 1; quella di riconoscimento deve essere compresa tra 0 e 1","automationIncomplete": "Regola in pausa; completa la configurazione: ${1}","databaseAutomations": "Automazioni","automationTip": "Le regole si applicano a tutte le viste. Le modifiche originali e le azioni automatiche vengono annullate insieme e ripristinate in caso di errore. Le azioni automatiche non attivano altre regole",diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.jsonindex e225e0d975..378324c3a0 100644--- a/app/appearance/langs/ja.json+++ b/app/appearance/langs/ja.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "検出しきい値",+ "ocrBoxThreshold": "テキスト領域の信頼度しきい値",+ "ocrRecognitionThreshold": "認識の信頼度しきい値",+ "ocrThresholdsTip": "空欄の場合はモデルの検出パラメーターと認識しきい値 0.5 を使用します。値を上げると誤認識を減らせますが、文字を見落とす場合があります。次回以降の認識にのみ適用されます",+ "ocrThresholdRange": "検出とテキスト領域のしきい値は 0 より大きく 1 未満、認識しきい値は 0 以上 1 以下にしてください","automationIncomplete": "ルールは停止中です。設定を完了してください:${1}","databaseAutomations": "自動化","automationTip": "ルールはすべてのビューで共有されます。元の編集と自動操作はまとめて取り消され、失敗時はすべて元に戻ります。自動操作は他のルールを起動しません",diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.jsonindex f947e0a245..10e55ad927 100644--- a/app/appearance/langs/ko.json+++ b/app/appearance/langs/ko.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "검출 임계값",+ "ocrBoxThreshold": "텍스트 영역 신뢰도 임계값",+ "ocrRecognitionThreshold": "인식 신뢰도 임계값",+ "ocrThresholdsTip": "비워 두면 모델의 검출 매개변수와 인식 임계값 0.5를 사용합니다. 값을 높이면 오인식이 줄지만 일부 텍스트를 놓칠 수 있습니다. 이후 인식에만 적용됩니다",+ "ocrThresholdRange": "검출 및 영역 임계값은 0보다 크고 1보다 작아야 하며, 인식 임계값은 0 이상 1 이하여야 합니다","automationIncomplete": "규칙이 일시 중지되었습니다. 설정을 완료하세요: ${1}","databaseAutomations": "자동화","automationTip": "규칙은 모든 보기에서 공유됩니다. 원본 편집과 자동 작업은 함께 실행 취소되며, 실패하면 모두 복원됩니다. 자동 작업은 다른 규칙을 실행하지 않습니다",diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.jsonindex 8c55dc325f..84c1be9a71 100644--- a/app/appearance/langs/nl.json+++ b/app/appearance/langs/nl.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Detectiedrempel",+ "ocrBoxThreshold": "Betrouwbaarheidsdrempel voor tekstvakken",+ "ocrRecognitionThreshold": "Betrouwbaarheidsdrempel voor herkenning",+ "ocrThresholdsTip": "Laat leeg voor de detectieparameters van het model en een herkenningsdrempel van 0.5; hogere waarden verminderen foutieve herkenning maar kunnen tekst missen; geldt alleen voor volgende herkenningen",+ "ocrThresholdRange": "Detectie- en tekstvakdrempels moeten groter dan 0 en kleiner dan 1 zijn; de herkenningsdrempel moet tussen 0 en 1 liggen","automationIncomplete": "Regel gepauzeerd; voltooi de configuratie: ${1}","databaseAutomations": "Automatiseringen","automationTip": "Regels gelden voor alle weergaven. Oorspronkelijke bewerkingen en automatische acties worden samen ongedaan gemaakt en bij fouten teruggedraaid. Automatische acties activeren geen andere regels",diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.jsonindex bb88fd0d7b..a2cc09c191 100644--- a/app/appearance/langs/pl.json+++ b/app/appearance/langs/pl.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Próg wykrywania",+ "ocrBoxThreshold": "Próg pewności obszarów tekstu",+ "ocrRecognitionThreshold": "Próg pewności rozpoznawania",+ "ocrThresholdsTip": "Pozostaw puste, aby użyć parametrów wykrywania modelu i progu rozpoznawania 0.5; wyższe progi zmniejszają liczbę błędnych rozpoznań, ale mogą pomijać tekst; dotyczy tylko kolejnych rozpoznań",+ "ocrThresholdRange": "Progi wykrywania i obszarów muszą być większe od 0 i mniejsze od 1; próg rozpoznawania musi mieścić się od 0 do 1","automationIncomplete": "Reguła wstrzymana; uzupełnij konfigurację: ${1}","databaseAutomations": "Automatyzacje","automationTip": "Reguły obowiązują we wszystkich widokach. Pierwotne zmiany i automatyczne działania są cofane razem, a po błędzie przywracany jest stan początkowy. Automatyczne działania nie uruchamiają innych reguł",diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.jsonindex ae14a3f20f..97a56cfe45 100644--- a/app/appearance/langs/pt-BR.json+++ b/app/appearance/langs/pt-BR.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Limiar de detecção",+ "ocrBoxThreshold": "Limiar de confiança das caixas de texto",+ "ocrRecognitionThreshold": "Limiar de confiança do reconhecimento",+ "ocrThresholdsTip": "Deixe vazio para usar os parâmetros de detecção do modelo e o limiar de reconhecimento de 0.5; valores maiores reduzem falsos positivos, mas podem omitir texto; aplica-se apenas a novos reconhecimentos",+ "ocrThresholdRange": "Os limiares de detecção e das caixas devem ser maiores que 0 e menores que 1; o de reconhecimento deve estar entre 0 e 1","automationIncomplete": "Regra pausada; complete a configuração: ${1}","databaseAutomations": "Automações","automationTip": "As regras se aplicam a todas as visualizações. As edições originais e as ações automáticas são desfeitas juntas e revertidas em caso de falha. As ações automáticas não acionam outras regras",diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.jsonindex 215eeaf1b6..ad4e1cc6b6 100644--- a/app/appearance/langs/ru.json+++ b/app/appearance/langs/ru.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Порог обнаружения",+ "ocrBoxThreshold": "Порог уверенности текстовых областей",+ "ocrRecognitionThreshold": "Порог уверенности распознавания",+ "ocrThresholdsTip": "Оставьте пустым для параметров обнаружения модели и порога распознавания 0.5; повышение порогов уменьшает ложные срабатывания, но может пропускать текст; действует только для последующего распознавания",+ "ocrThresholdRange": "Пороги обнаружения и областей должны быть больше 0 и меньше 1; порог распознавания должен быть от 0 до 1","automationIncomplete": "Правило приостановлено; завершите настройку: ${1}","databaseAutomations": "Автоматизация","automationTip": "Правила действуют во всех представлениях. Исходные изменения и автоматические действия отменяются вместе и откатываются при ошибке. Автоматические действия не запускают другие правила",diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.jsonindex 322cd0afff..3c7d2fea5f 100644--- a/app/appearance/langs/sk.json+++ b/app/appearance/langs/sk.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Prah detekcie",+ "ocrBoxThreshold": "Prah spoľahlivosti textových oblastí",+ "ocrRecognitionThreshold": "Prah spoľahlivosti rozpoznávania",+ "ocrThresholdsTip": "Ponechajte prázdne pre parametre detekcie modelu a prah rozpoznávania 0.5; vyššie prahy znižujú falošné rozpoznania, ale môžu vynechať text; platí iba pre ďalšie rozpoznávania",+ "ocrThresholdRange": "Prahy detekcie a oblastí musia byť väčšie ako 0 a menšie ako 1; prah rozpoznávania musí byť od 0 do 1","automationIncomplete": "Pravidlo pozastavené; dokončite konfiguráciu: ${1}","databaseAutomations": "Automatizácie","automationTip": "Pravidlá platia pre všetky zobrazenia. Pôvodné úpravy a automatické akcie sa vracajú späť spoločne a pri zlyhaní sa obnoví pôvodný stav. Automatické akcie nespúšťajú ďalšie pravidlá",diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.jsonindex a379192aa2..f61c67441f 100644--- a/app/appearance/langs/sr.json+++ b/app/appearance/langs/sr.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Праг детекције",+ "ocrBoxThreshold": "Праг поузданости текстуалних области",+ "ocrRecognitionThreshold": "Праг поузданости препознавања",+ "ocrThresholdsTip": "Оставите празно за параметре детекције модела и праг препознавања 0.5; виши прагови смањују погрешна препознавања, али могу пропустити текст; важи само за наредна препознавања",+ "ocrThresholdRange": "Прагови детекције и области морају бити већи од 0 и мањи од 1; праг препознавања мора бити од 0 до 1","automationIncomplete": "Правило је паузирано; довршите подешавање: ${1}","databaseAutomations": "Аутоматизације","automationTip": "Правила важе за све приказе. Изворне измене и аутоматске радње поништавају се заједно, а при грешци се враћа претходно стање. Аутоматске радње не покрећу друга правила",diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.jsonindex 58d50d3184..e0d728d86b 100644--- a/app/appearance/langs/th.json+++ b/app/appearance/langs/th.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "เกณฑ์การตรวจจับ",+ "ocrBoxThreshold": "เกณฑ์ความเชื่อมั่นของกรอบข้อความ",+ "ocrRecognitionThreshold": "เกณฑ์ความเชื่อมั่นของการรู้จำ",+ "ocrThresholdsTip": "เว้นว่างเพื่อใช้ค่าการตรวจจับของโมเดลและเกณฑ์การรู้จำ 0.5 การเพิ่มเกณฑ์ช่วยลดการรู้จำผิด แต่อาจทำให้พลาดข้อความ มีผลเฉพาะการรู้จำครั้งถัดไป",+ "ocrThresholdRange": "เกณฑ์การตรวจจับและกรอบข้อความต้องมากกว่า 0 และน้อยกว่า 1 ส่วนเกณฑ์การรู้จำต้องอยู่ระหว่าง 0 ถึง 1","automationIncomplete": "หยุดกฎไว้ชั่วคราว โปรดตั้งค่าให้ครบถ้วน: ${1}","databaseAutomations": "ระบบอัตโนมัติ","automationTip": "กฎใช้กับทุกมุมมอง การแก้ไขต้นทางและการทำงานอัตโนมัติจะถูกเลิกทำพร้อมกัน และย้อนกลับทั้งหมดหากล้มเหลว การทำงานอัตโนมัติจะไม่เรียกใช้กฎอื่น",diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.jsonindex aa163664f1..4edb9fdc8f 100644--- a/app/appearance/langs/tr.json+++ b/app/appearance/langs/tr.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Algılama eşiği",+ "ocrBoxThreshold": "Metin kutusu güven eşiği",+ "ocrRecognitionThreshold": "Tanıma güven eşiği",+ "ocrThresholdsTip": "Modelin algılama parametrelerini ve 0.5 tanıma eşiğini kullanmak için boş bırakın; yüksek eşikler yanlış tanımaları azaltır ancak metni atlayabilir; yalnızca sonraki tanımaları etkiler",+ "ocrThresholdRange": "Algılama ve kutu eşikleri 0’dan büyük ve 1’den küçük olmalıdır; tanıma eşiği 0 ile 1 arasında olmalıdır","automationIncomplete": "Kural duraklatıldı; yapılandırmayı tamamlayın: ${1}","databaseAutomations": "Otomasyonlar","automationTip": "Kurallar tüm görünümlerde geçerlidir. Kaynak düzenlemeleri ve otomatik işlemler birlikte geri alınır; hata durumunda tümü geri döndürülür. Otomatik işlemler başka kuralları tetiklemez",diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.jsonindex 6a90a36c2a..5f3a67e340 100644--- a/app/appearance/langs/uk.json+++ b/app/appearance/langs/uk.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "Поріг виявлення",+ "ocrBoxThreshold": "Поріг впевненості текстових областей",+ "ocrRecognitionThreshold": "Поріг впевненості розпізнавання",+ "ocrThresholdsTip": "Залиште порожнім для параметрів виявлення моделі та порога розпізнавання 0.5; вищі пороги зменшують хибні спрацювання, але можуть пропускати текст; діє лише для подальшого розпізнавання",+ "ocrThresholdRange": "Пороги виявлення та областей мають бути більшими за 0 і меншими за 1; поріг розпізнавання має бути від 0 до 1","automationIncomplete": "Правило призупинено; завершіть налаштування: ${1}","databaseAutomations": "Автоматизація","automationTip": "Правила діють у всіх поданнях. Початкові зміни й автоматичні дії скасовуються разом і відкочуються в разі помилки. Автоматичні дії не запускають інші правила",diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.jsonindex 451ab17e26..93f7d6f08e 100644--- a/app/appearance/langs/zh-CN.json+++ b/app/appearance/langs/zh-CN.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "检测阈值",+ "ocrBoxThreshold": "文本框置信度阈值",+ "ocrRecognitionThreshold": "识别置信度阈值",+ "ocrThresholdsTip": "留空使用模型检测参数和 0.5 的识别阈值;提高阈值可减少误识别,但可能漏字;仅影响后续识别",+ "ocrThresholdRange": "检测和文本框阈值须大于 0 且小于 1,识别阈值须在 0 到 1 之间","automationIncomplete": "规则已停用,请完善配置:${1}","databaseAutomations": "自动化","automationTip": "所有视图共享规则。原修改与自动操作一起撤销,失败时全部回滚。自动操作不会触发其他规则",diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.jsonindex a4f9d19188..256d8995ad 100644--- a/app/appearance/langs/zh-TW.json+++ b/app/appearance/langs/zh-TW.json@@ -1,4 +1,9 @@{+ "ocrDetectionThreshold": "偵測閾值",+ "ocrBoxThreshold": "文字框信賴度閾值",+ "ocrRecognitionThreshold": "辨識信賴度閾值",+ "ocrThresholdsTip": "留空使用模型偵測參數和 0.5 的辨識閾值;提高閾值可減少誤辨識,但可能漏字;僅影響後續辨識",+ "ocrThresholdRange": "偵測和文字框閾值須大於 0 且小於 1,辨識閾值須介於 0 到 1","automationIncomplete": "規則已停用,請完善設定:${1}","databaseAutomations": "自動化","automationTip": "所有檢視共用規則。原始修改與自動操作一併復原,失敗時全部回復。自動操作不會觸發其他規則",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.syindex 0fd22bc67e..11722af7cf 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": "20261002231520"+ "updated": "20261003073646"},"Children": [{@@ -1031,6 +1031,20 @@}]},+ {+ "ID": "20261003073646-xagh51u",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261003073646-xagh51u",+ "updated": "20261003073646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "With PaddleOCR selected, click the settings button beside Advanced 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."+ }+ ]+ },{"ID": "20261001000112-ogz08vw","Type": "NodeParagraph",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.syindex 04e2e787a1..28aff87072 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": "20261002231520"+ "updated": "20261003073646"},"Children": [{@@ -1043,6 +1043,20 @@}]},+ {+ "ID": "20261003073646-yye710a",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261003073646-yye710a",+ "updated": "20261003073646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "选择 PaddleOCR 后,可以通过高级设置右侧的设置按钮,分别调整检测阈值、文本框置信度阈值和识别置信度阈值。检测与文本框阈值须大于 0 且小于 1,识别阈值为 0 到 1。留空或重置并确认后,检测使用当前模型参数,识别使用 0.5。提高阈值可以减少图标误识别,但也可能漏掉模糊或较淡的文字。阈值按设备保存,适用于手动和自动识别;不会重新处理已有结果,可通过图片菜单重新识别。"+ }+ ]+ },{"ID": "20261001000112-6l7ji97","Type": "NodeParagraph",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.syindex d5ca892378..75cdf55c8b 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": "20261002231520"+ "updated": "20261003073646"},"Children": [{@@ -1029,6 +1029,20 @@}]},+ {+ "ID": "20261003073646-hpqqxqx",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261003073646-hpqqxqx",+ "updated": "20261003073646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "選擇 PaddleOCR 後,可以透過進階設定右側的設定按鈕,分別調整偵測閾值、文字框信賴度閾值和辨識信賴度閾值。偵測與文字框閾值須大於 0 且小於 1,辨識閾值為 0 到 1。留空或重設並確認後,偵測使用目前模型參數,辨識使用 0.5。提高閾值可以減少圖示誤辨識,但也可能漏掉模糊或較淡的文字。閾值依裝置儲存,適用於手動和自動辨識;不會重新處理既有結果,可透過圖片選單重新辨識。"+ }+ ]+ },{"ID": "20261001000112-hc489un","Type": "NodeParagraph",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.syindex 6826284b54..8026ccbd80 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": "20261002231520"+ "updated": "20261003073646"},"Children": [{@@ -1066,6 +1066,20 @@}]},+ {+ "ID": "20261003073646-o8u40dy",+ "Type": "NodeParagraph",+ "Properties": {+ "id": "20261003073646-o8u40dy",+ "updated": "20261003073646"+ },+ "Children": [+ {+ "Type": "NodeText",+ "Data": "PaddleOCR を選択すると、詳細設定の設定ボタンを押して、検出、テキスト領域の信頼度、認識の信頼度のしきい値を調整できます。検出とテキスト領域のしきい値は 0 より大きく 1 未満、認識しきい値は 0 以上 1 以下です。空欄またはリセット後に確定すると、現在のモデルの検出パラメーターと認識しきい値 0.5 を使用します。値を上げるとアイコンの誤認識を減らせますが、ぼやけた文字や薄い文字を見落とす場合があります。しきい値は端末ごとに保存され、手動認識と自動認識に適用されます。既存の結果は変更されません。必要に応じて画像メニューから再認識してください。"+ }+ ]+ },{"ID": "20261001000112-87qzkfr","Type": "NodeParagraph",diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.tsindex 449d5166a0..56ccbbe877 100644--- a/app/src/config/ocr.test.ts+++ b/app/src/config/ocr.test.ts@@ -3,12 +3,13 @@ import {readFileSync} from "node:fs";import {test} from "node:test";import {runInNewContext} from "node:vm";import {ModuleKind, ScriptTarget, transpileModule} from "typescript";+import type {OCRThresholds, SettingOCR} from "../types/api";const createOCRPanel = async () => {const compiled = transpileModule(readFileSync("src/config/ocr.ts", "utf8"), {compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},}).outputText;- const config = {ocr: {provider: "paddleocr", model: "small", auto: false}};+ const config: {ocr: SettingOCR} = {ocr: {provider: "paddleocr", model: "small", auto: false}};let serverConfig = {...config.ocr};let models = [{id: "small", name: "Small", builtIn: true}];let reads = 0;@@ -19,10 +20,11 @@ const createOCRPanel = async () => {const controls = Object.fromEntries(["ocrProvider", "ocrModel", "ocrAuto", "ocrImportModels", "ocrImport","detector", "detectorConfig", "recognizer", "recognizerConfig",+ "ocrAdvanced",].map(id => [id, {id, value: id === "ocrProvider" ? "paddleocr" : "small", checked: false, disabled: false, innerHTML: "",files: [{name: `${id}.onnx`}],- tagName: id === "ocrImport" ? "BUTTON" : "INPUT",+ tagName: id === "ocrImport" || id === "ocrAdvanced" ? "BUTTON" : "INPUT",closest: () => ({classList: {toggle() {}}}),}]));const listeners = new Map<string, (event: unknown) => Promise<void>>();@@ -40,14 +42,20 @@ 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: {}},+ runInNewContext(compiled, {exports, AbortController, window: {siyuan: {config, languages: {ocrThresholdRange: "invalid threshold"}},addEventListener: (name: string, callback: () => void, options: {signal: AbortSignal}) => {notifications.set(name, callback);options.signal.addEventListener("abort", () => notifications.delete(name));},}, require: () => ({OCR_CHANGED_EVENT: "ocr-test",+ 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") {@@ -69,6 +77,8 @@ const createOCRPanel = async () => {await new Promise(setImmediate);return {controls, config, requests, errors, close, renders: () => renders,+ openAdvanced: () => listeners.get("click")({target: {closest: () => controls.ocrAdvanced}, stopPropagation() {}}),+ advanced: () => advanced, dialogCloses: () => dialogCloses,reads: () => reads, snapshot, readRequests,notify: () => notifications.get("ocr-test")?.(),deferRead: () => { deferredRead = true; },@@ -128,6 +138,31 @@ for (const networkFailure of [false, true]) {});}+test("advanced OCR settings receive the latest thresholds and use the panel save queue", async () => {+ const panel = await createOCRPanel();+ panel.updateServer({provider: "paddleocr", model: "small", 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});+ await new Promise(setImmediate);+ 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);+ 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}});+ await toggle;+ assert.equal(panel.config.ocr.thresholds.recognition, 0.9);+ assert.equal(panel.renders(), renders);+ panel.close();+ assert.equal(panel.dialogCloses(), 1);+});+test("closing the OCR panel cancels queued saves and ignores a late response", async () => {const panel = await createOCRPanel();const first = panel.changeAuto(true);diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.tsindex 3f970acaa6..c7c6b9ca84 100644--- a/app/src/config/ocr.ts+++ b/app/src/config/ocr.ts@@ -1,4 +1,4 @@-import type {OCRConfigData, SettingOCR} from "../types/api";+import type {OCRConfigData, OCRThresholds, SettingOCR} from "../types/api";import {fetchSyncPost} from "../util/fetch";import {ContractFormData} from "../util/contractFormData";import {escapeAttr, escapeHtml} from "../util/escape";@@ -7,6 +7,7 @@ import {genButtonRowHtml} from "./render/render";import {showMessage} from "../dialog/message";import {OCR_CHANGED_EVENT} from "./ocrRuntime";import {objEquals} from "../util/functions";+import {openOCRThresholds} from "./ocrThresholds";export const ocrSearchStrings = (): string[] => ["OCR", "Tesseract", "PaddleOCR", "Tiny", "Small",@@ -14,6 +15,9 @@ export const ocrSearchStrings = (): string[] => [window.siyuan.languages.ocrModel,window.siyuan.languages.ocrAuto,window.siyuan.languages.ocrImportModels,+ window.siyuan.languages.ocrDetectionThreshold,+ window.siyuan.languages.ocrBoxThreshold,+ window.siyuan.languages.ocrRecognitionThreshold,];export const mountOCRSettings = (root: HTMLElement): (() => void) => {@@ -22,7 +26,8 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {let data: OCRConfigData;let busy = false;let pendingSaves = 0;- let saveQueue = Promise.resolve();+ let saveQueue = Promise.resolve(false);+ let thresholdDialog: ReturnType<typeof openOCRThresholds>;let refreshPending = false;let refreshTask: Promise<void>;let writeRevision = 0;@@ -38,9 +43,10 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {];const updateControls = () => {const isPaddleOCR = root.querySelector<HTMLSelectElement>("#ocrProvider").value === "paddleocr";- ["ocrModel", "ocrImportModels", "ocrImport"].forEach(id => {+ ["ocrModel", "ocrImportModels", "ocrImport", "ocrAdvanced"].forEach(id => {root.querySelector(`#${id}`).closest(".config-item").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);});@@ -66,6 +72,7 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {root.innerHTML = genSwitchRow("ocrAuto", languages.ocrAuto, languages.ocrAutoTip, data.config.auto) +selectRow("ocrProvider", languages.ocrProvider, languages.ocrProviderTip, providerOptions()) +selectRow("ocrModel", languages.ocrModel, languages.ocrModelTip, modelOptions()) ++ genButtonRowHtml("ocrAdvanced", languages.configGroupAdvanced, undefined, languages.config, "iconSettings") +`<div id="ocrImportModels" class="b3-label config-item">${genConfigItemMainHtml(languages.ocrImportModels, languages.ocrImportModelsTip)}${files.map(file => `<div class="fn__hr"></div><label class="fn__block"><span class="b3-label__text">${file.title}</span><div class="fn__hr--small"></div><input id="${file.id}" class="b3-text-field fn__block" type="file" accept="${file.suffix.split(",").map(suffix => `.${suffix}`).join(",")}"></label>`).join("")}</div>` +genButtonRowHtml("ocrImport", "", undefined, languages.import, "iconDownload");@@ -112,34 +119,31 @@ ${files.map(file => `<div class="fn__hr"></div><label class="fn__block"><span cl};root.innerHTML = "<div class=\"fn__loading\"><img src=\"/stage/loading-pure.svg\"></div>";window.addEventListener(OCR_CHANGED_EVENT, () => { void load().catch(handleError); }, {signal: controller.signal});- root.addEventListener("change", async event => {- event.stopPropagation();- const target = event.target as HTMLInputElement | HTMLSelectElement;- if (busy || !data) {- return;- }- if (files.some(file => file.id === target.id)) {- updateControls();- return;+ const saveConfig = async (thresholds?: OCRThresholds): Promise<boolean> => {+ if (closed || busy || !data) {+ return false;}const config: SettingOCR = {provider: root.querySelector<HTMLSelectElement>("#ocrProvider").value,model: root.querySelector<HTMLSelectElement>("#ocrModel").value,auto: root.querySelector<HTMLInputElement>("#ocrAuto").checked,+ thresholds,};writeRevision++;pendingSaves++;updateControls();// 串行保存每次选择,保留控件焦点和文件选择,最后一次完成后再校正界面状态。const save = async () => {+ let saved = false;try {if (closed) {- return;+ return false;}const response = await fetchSyncPost("/api/asset/setOCRConfig", config, undefined, true, controller.signal);if (response.code === 0 && !closed) {data.config = response.data;window.siyuan.config.ocr = response.data;+ saved = true;}} catch (error) {handleError(error);@@ -153,9 +157,19 @@ ${files.map(file => `<div class="fn__hr"></div><label class="fn__block"><span clif (refreshPending) void load().catch(handleError);}}+ return saved;};saveQueue = saveQueue.then(save, save);- await saveQueue;+ return saveQueue;+ };+ root.addEventListener("change", async event => {+ event.stopPropagation();+ const target = event.target as HTMLInputElement | HTMLSelectElement;+ if (files.some(file => file.id === target.id)) {+ updateControls();+ return;+ }+ await saveConfig();}, {signal: controller.signal});root.addEventListener("click", async event => {event.stopPropagation();@@ -163,6 +177,11 @@ ${files.map(file => `<div class="fn__hr"></div><label class="fn__block"><span clif (!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;@@ -198,6 +217,7 @@ ${files.map(file => `<div class="fn__hr"></div><label class="fn__block"><span cl});return () => {closed = true;+ thresholdDialog?.destroy();controller.abort();};};diff --git a/app/src/config/ocrThresholds.test.ts b/app/src/config/ocrThresholds.test.tsnew file mode 100644index 0000000000..cc388d3121--- /dev/null+++ b/app/src/config/ocrThresholds.test.ts@@ -0,0 +1,102 @@+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", default: "Default", configGroupAdvanced: "Advanced",+ }}}, 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/);+ 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.tsnew file mode 100644index 0000000000..4d57740bba--- /dev/null+++ b/app/src/config/ocrThresholds.ts@@ -0,0 +1,74 @@+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},+ {key: "box", title: languages.ocrBoxThreshold},+ {key: "recognition", title: languages.ocrRecognitionThreshold},+ ] as const;+ let closed = false;+ let saving = false;+ const dialog = new Dialog({+ title: `PaddleOCR - ${languages.configGroupAdvanced}`,+ 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}) => `<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(languages.default)}"></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/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 20fc2665c1..94385353a3 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -1476,6 +1476,10 @@ export type OCRModel = { "builtIn": boolean; "id": string; "name": string; };export type OCRProviderState = { "available": boolean; "id": string; };+export type OCRThresholds = { "box": number | null; "detection": number | null; "recognition": number | null; };++export type OCRThresholdsInput = { "box": number | null; "detection": number | null; "recognition": number | null; };+export type ObsidianAnalysisRequestInput = { "localPath": string; };export type ObsidianImportRequestInput = { "notebookName": string; "taskID": string; };@@ -1998,9 +2002,9 @@ export type SettingNotifications = { "browserCompatibility": boolean; "docTreeMaexport type SettingNotificationsInput = { "browserCompatibility"?: boolean | null; "docTreeMaxList"?: boolean | null; "formatPainterTip"?: boolean | null; "selectAllIncompleteTip"?: boolean | null; "selectAllTip"?: boolean | null; "tagMaxList"?: boolean | null; "workspaceNotSSD"?: boolean | null; };-export type SettingOCR = { "auto": boolean; "model": string; "provider": string; };+export type SettingOCR = { "auto": boolean; "model": string; "provider": string; "thresholds"?: OCRThresholds; };-export type SettingOCRInput = { "auto": boolean; "model": string; "provider": string; };+export type SettingOCRInput = { "auto": boolean; "model": string; "provider": string; "thresholds"?: OCRThresholdsInput | null; };export type SettingPetalDisabledData = { "dataChangePlugins": Array<string> | null; "globalPetalChanged": boolean; "globalPetalDisabled": boolean; "globalPetalEnabled": boolean; "globalPetalRevision": number; "reloadPlugins": Array<string> | null; "uninstallPlugins": Array<string> | null; "unloadPlugins": Array<string> | null; };diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex b93e4afe1e..e81202d4d5 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -27,8 +27,8 @@ declare namespace Config {accessAuthCode: string;oidc: IOIDC;ai: IAI;- /** 当前设备的本地 OCR 提供商和模型选择;切换后保留已有识别文本 */- ocr: {provider: string; model: string; auto: boolean};+ /** 当前设备的 OCR 设置;阈值只影响后续 PaddleOCR 识别,空值使用模型检测参数和 0.5 的识别阈值 */+ ocr: import("./api").SettingOCR;api: IAPI;appearance: IAppearance;bazaar: IBazaar;diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.goindex 29f159484b..a374bc0683 100644--- a/kernel/api/contract_ocr_test.go+++ b/kernel/api/contract_ocr_test.go@@ -336,6 +336,76 @@ func TestAPIContractOCRSettings(t *testing.T) {}}+func TestAPIContractOCRThresholdPersistence(t *testing.T) {+ setupAssetContractWorkspace(t)+ previousConfDir := util.ConfDir+ util.ConfDir = t.TempDir()+ t.Cleanup(func() { util.ConfDir = previousConfDir })+ engine := gin.New()+ engine.POST("/api/asset/setOCRConfig", setOCRConfig)+ path := "assets/threshold-preserved.png"+ util.SetAssetText(path, "existing result")+ t.Cleanup(func() { util.RemoveAssetText(path) })+ for _, test := range []struct {+ fields string+ success bool+ custom bool+ }{+ {`,"thresholds":{"detection":0.4,"box":0.7,"recognition":0.9}`, true, true},+ {"", true, true},+ {`,"thresholds":null`, true, true},+ {`,"thresholds":{"detection":0,"box":0.7,"recognition":0.9}`, false, true},+ {`,"thresholds":{"detection":0.4,"box":1,"recognition":0.9}`, false, true},+ {`,"thresholds":{"detection":0.4,"box":0.7,"recognition":1.1}`, false, true},+ {`,"thresholds":{"detection":null,"box":null,"recognition":null}`, true, false},+ } {+ body := `{"provider":"tesseract","model":"tiny","auto":false` + test.fields + `}`+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setOCRConfig", strings.NewReader(body)))+ requireAPIContract(t, "POST", "/api/asset/setOCRConfig", recorder)+ var response struct {+ Code int+ Data *apicontract.SettingOCR+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if (response.Code == 0) != test.success {+ t.Fatalf("%s: %s", body, recorder.Body.String())+ }+ got := model.Conf.GetOCR().Thresholds+ if test.custom {+ if got.Detection == nil || *got.Detection != 0.4 || got.Box == nil || *got.Box != 0.7 || got.Recognition == nil || *got.Recognition != 0.9 {+ t.Fatalf("saved thresholds lost: %+v", got)+ }+ } else if got != (conf.OCRThresholds{}) {+ t.Fatalf("reset did not restore defaults: %+v", got)+ }+ persisted, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))+ if err != nil {+ t.Fatal(err)+ }+ var saved struct{ OCR conf.OCR }+ if err = json.Unmarshal(persisted, &saved); err != nil {+ t.Fatal(err)+ }+ want, _ := json.Marshal(got)+ actual, _ := json.Marshal(saved.OCR.Thresholds)+ if !bytes.Equal(want, actual) {+ t.Fatalf("persisted thresholds %s != %s", actual, want)+ }+ if test.success {+ actual, _ = json.Marshal(response.Data.Thresholds)+ if !bytes.Equal(want, actual) {+ t.Fatalf("response lost thresholds: %s", actual)+ }+ }+ if util.GetAssetText(path) != "existing result" {+ t.Fatal("threshold update rewrote existing OCR")+ }+ }+}+func connectOCRNotifications(t *testing.T, engine *gin.Engine) *websocket.Conn {t.Helper()push := melody.New()diff --git a/kernel/api/ocr.go b/kernel/api/ocr.goindex f0c276dbc6..e67e84cf62 100644--- a/kernel/api/ocr.go+++ b/kernel/api/ocr.go@@ -22,9 +22,14 @@ var getOCRConfig = contractHandler(apicontract.GetOCRConfig, func(c *gin.Contextfor _, id := range []string{"tesseract", "paddleocr"} {providers = append(providers, apicontract.OCRProviderState{ID: id, Available: model.OCRProviderAvailable(id)})}- return apicontract.Success(apicontract.OCRConfigData{Config: apicontract.SettingOCR(value), Providers: providers, Models: models})+ return apicontract.Success(apicontract.OCRConfigData{Config: ocrConfigPayload(value), Providers: providers, Models: models})})+func ocrConfigPayload(value conf.OCR) apicontract.SettingOCR {+ thresholds := apicontract.OCRThresholds(value.Thresholds)+ return apicontract.SettingOCR{Provider: value.Provider, Model: value.Model, Auto: value.Auto, Thresholds: &thresholds}+}+func ocrModelPayload(id string) apicontract.OCRModel {name := idif id == "tiny" {@@ -38,10 +43,15 @@ func ocrModelPayload(id string) apicontract.OCRModel {}var setOCRConfig = contractHandler(apicontract.SetOCRConfig, serializeSetting("ocr", func(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {- if err := model.Conf.SetOCR(conf.OCR(request)); err != nil {+ value := model.Conf.GetOCR()+ value.Provider, value.Model, value.Auto = request.Provider, request.Model, request.Auto+ if request.Thresholds != nil {+ value.Thresholds = conf.OCRThresholds(*request.Thresholds)+ }+ if err := model.Conf.SetOCR(value); err != nil {return apicontract.Failure[apicontract.SettingOCR](-1, err.Error())}- return apicontract.Success(request)+ return apicontract.Success(ocrConfigPayload(value))}))var importOCRModels = contractHandler(apicontract.ImportOCRModels, func(c *gin.Context, request apicontract.ImportOCRModelsRequest) apicontract.Response[apicontract.OCRModel] {diff --git a/kernel/apicontract/ocr.go b/kernel/apicontract/ocr.goindex 5b152e0fc7..3149fd5449 100644--- a/kernel/apicontract/ocr.go+++ b/kernel/apicontract/ocr.go@@ -4,10 +4,21 @@ import "mime/multipart"// SettingOCR 的选择仅保存在当前设备;切换提供商或模型不删除、重跑已有识别结果。// auto 仅控制内核后台识别,手动识别继续使用 /api/asset/ocr 的既有输入和输出。+// thresholds 省略或为 null 时保留设备已保存的阈值;传入对象时整体替换。+// 修改阈值只影响后续识别,不修改模型文件或已有结果,Tesseract 不使用这些参数。type SettingOCR struct {- Provider string `json:"provider"`- Model string `json:"model"`- Auto bool `json:"auto"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ Auto bool `json:"auto"`+ Thresholds *OCRThresholds `json:"thresholds,omitempty" api:"optional"`+}++// OCRThresholds 的 detection、box 必须为 (0, 1) 内的有限数,recognition 为 [0, 1] 内的有限数。+// 对象内三个字段均须提供;字段为 null 时恢复默认:检测沿用当前模型 YAML,识别为 0.5。+type OCRThresholds struct {+ Detection *float64 `json:"detection"`+ Box *float64 `json:"box"`+ Recognition *float64 `json:"recognition"`}type OCRProviderState struct {diff --git a/kernel/apicontract/ocr_test.go b/kernel/apicontract/ocr_test.goindex a89915269d..8e4287fa48 100644--- a/kernel/apicontract/ocr_test.go+++ b/kernel/apicontract/ocr_test.go@@ -16,3 +16,21 @@ func TestOCRSettingStrictInput(t *testing.T) {t.Fatalf("valid settings: %+v %v", request, err)}}++func TestOCRThresholdContract(t *testing.T) {+ for _, fields := range []string{+ `{}`, `{"detection":0.3,"box":0.6}`, `{"detection":"0.3","box":0.6,"recognition":0.5}`,+ `{"detection":false,"box":null,"recognition":null}`,+ } {+ body := `{"provider":"paddleocr","model":"small","auto":false,"thresholds":` + fields + `}`+ if _, err := SetOCRConfig.Decode(strings.NewReader(body)); err == nil {+ t.Fatalf("accepted malformed thresholds: %s", body)+ }+ }+ for _, fields := range []string{`{"detection":null,"box":null,"recognition":null}`, `{"detection":0.3,"box":0.6,"recognition":0}`} {+ body := `{"provider":"paddleocr","model":"small","auto":false,"thresholds":` + fields + `}`+ if request, err := SetOCRConfig.Decode(strings.NewReader(body)); err != nil || request.Thresholds == nil {+ t.Fatalf("rejected valid thresholds: %s: %v", body, err)+ }+ }+}diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.jsonindex 586d2b4056..25f380940f 100644--- a/kernel/apicontract/schema.json+++ b/kernel/apicontract/schema.json@@ -33318,6 +33318,88 @@],"additionalProperties": false},+ "OCRThresholds": {+ "type": "object",+ "properties": {+ "box": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "detection": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "recognition": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "box",+ "detection",+ "recognition"+ ],+ "additionalProperties": false+ },+ "OCRThresholdsInput": {+ "type": "object",+ "properties": {+ "box": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "detection": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ },+ "recognition": {+ "anyOf": [+ {+ "type": "number"+ },+ {+ "type": "null"+ }+ ]+ }+ },+ "required": [+ "box",+ "detection",+ "recognition"+ ],+ "additionalProperties": false+ },"ObsidianAnalysisRequestInput": {"type": "object","properties": {@@ -46077,6 +46159,9 @@},"provider": {"type": "string"+ },+ "thresholds": {+ "$ref": "#/$defs/OCRThresholds"}},"required": [@@ -46097,6 +46182,16 @@},"provider": {"type": "string"+ },+ "thresholds": {+ "anyOf": [+ {+ "$ref": "#/$defs/OCRThresholdsInput"+ },+ {+ "type": "null"+ }+ ]}},"required": [diff --git a/kernel/conf/ocr.go b/kernel/conf/ocr.goindex 75c6fa994b..fd834fa366 100644--- a/kernel/conf/ocr.go+++ b/kernel/conf/ocr.go@@ -2,9 +2,17 @@ package conf// OCR 配置保存在设备配置中,模型文件和识别结果独立于提供商选择。type OCR struct {- Provider string `json:"provider"`- Model string `json:"model"`- Auto bool `json:"auto"`+ Provider string `json:"provider"`+ Model string `json:"model"`+ Auto bool `json:"auto"`+ Thresholds OCRThresholds `json:"thresholds"`+}++// OCRThresholds 中的空值沿用模型检测参数和 0.5 的识别阈值。+type OCRThresholds struct {+ Detection *float64 `json:"detection"`+ Box *float64 `json:"box"`+ Recognition *float64 `json:"recognition"`}func NewOCR(mobile bool) *OCR {diff --git a/kernel/model/ocr.go b/kernel/model/ocr.goindex 6f890057b2..fca53c0ac6 100644--- a/kernel/model/ocr.go+++ b/kernel/model/ocr.go@@ -77,6 +77,9 @@ func (config *AppConf) GetOCR() conf.OCR {}func (config *AppConf) SetOCR(value conf.OCR) error {+ if err := (ocr.Thresholds(value.Thresholds)).Validate(); err != nil {+ return err+ }if value.Provider != string(ocr.Tesseract) && value.Provider != string(ocr.PaddleOCR) {return errors.New("unknown OCR provider")}@@ -117,7 +120,7 @@ func currentPaddleConfig() ocr.PaddleConfig {} else if runtime.GOOS == "darwin" {filename = "libonnxruntime.dylib"}- result := ocr.PaddleConfig{Directory: ocrModelDirectory(value.Model), Library: filepath.Join(directory, filename)}+ result := ocr.PaddleConfig{Directory: ocrModelDirectory(value.Model), Library: filepath.Join(directory, filename), Thresholds: ocr.Thresholds(value.Thresholds)}if runtime.GOOS == "linux" {result.Worker = filepath.Join(directory, "siyuan-ocr")}diff --git a/kernel/ocr/paddle.go b/kernel/ocr/paddle.goindex 67e8ac268e..5098586620 100644--- a/kernel/ocr/paddle.go+++ b/kernel/ocr/paddle.go@@ -30,9 +30,10 @@ import (// PaddleConfig 指定一组检测和识别模型,Linux 使用原生辅助进程以兼容静态内核。type PaddleConfig struct {- Library string `json:"library"`- Worker string `json:"worker"`- Directory string `json:"directory"`+ Library string `json:"library"`+ Worker string `json:"worker"`+ Directory string `json:"directory"`+ Thresholds Thresholds `json:"thresholds"`}type modelConfig struct {@@ -136,7 +137,11 @@ func ValidateModels(directory string) error {}func (p *PaddleProvider) load(cfg PaddleConfig) error {- if cfg == p.loaded && p.detector != nil && p.recognizer != nil {+ if err := cfg.Thresholds.Validate(); err != nil {+ return err+ }+ // 后处理阈值每次识别时读取,调整阈值不重建原生会话。+ if cfg.Library == p.loaded.Library && cfg.Directory == p.loaded.Directory && cfg.Worker == p.loaded.Worker && p.detector != nil && p.recognizer != nil {return nil}p.close()@@ -272,7 +277,7 @@ func (p *PaddleProvider) Recognize(ctx context.Context, path string) ([]map[striif err != nil {return nil, err}- boxes, err := detectBoxes(detected, w, h, p.detection)+ boxes, err := detectBoxes(detected, w, h, cfg.Thresholds.detectionConfig(p.detection))if err != nil {return nil, err}@@ -292,7 +297,7 @@ func (p *PaddleProvider) Recognize(ctx context.Context, path string) ([]map[striif decodeErr != nil {return nil, decodeErr}- if strings.TrimSpace(text) == "" || confidence < 0.5 {+ if !cfg.Thresholds.accepts(text, confidence) {continue}left, top, right, bottom := box.bounds()diff --git a/kernel/ocr/paddle_test.go b/kernel/ocr/paddle_test.goindex 6a9326a46a..58ddf48f84 100644--- a/kernel/ocr/paddle_test.go+++ b/kernel/ocr/paddle_test.go@@ -8,6 +8,7 @@ import ("image/png""os""path/filepath"+ "reflect""strings""testing""time"@@ -72,7 +73,8 @@ func TestNativePaddleOCR(t *testing.T) {}for _, size := range []string{"tiny", "small"} {t.Run(size, func(t *testing.T) {- provider := &PaddleProvider{Config: func() PaddleConfig { return PaddleConfig{Library: library, Directory: filepath.Join(assets, size)} }}+ config := PaddleConfig{Library: library, Directory: filepath.Join(assets, size)}+ provider := &PaddleProvider{Config: func() PaddleConfig { return config }}defer provider.Close()ctx, cancel := context.WithTimeout(context.Background(), time.Minute)defer cancel()@@ -91,6 +93,21 @@ func TestNativePaddleOCR(t *testing.T) {if expected != "" && !strings.Contains(text.String(), expected) {t.Fatalf("missing expected text %q in %q", expected, text.String())}+ detector, recognizer := provider.detector, provider.recognizer+ zero := 0.0+ config.Thresholds.Recognition = &zero+ unfiltered, err := provider.Recognize(ctx, fixture)+ if err != nil || len(unfiltered) < len(rows) {+ t.Fatalf("lowering recognition threshold lost text: %v", err)+ }+ if provider.detector != detector || provider.recognizer != recognizer {+ t.Fatal("changing thresholds recreated native sessions")+ }+ config.Thresholds = Thresholds{}+ restored, err := provider.Recognize(ctx, fixture)+ if err != nil || !reflect.DeepEqual(rows, restored) {+ t.Fatalf("reset did not restore original recognition: %v", err)+ }})}}diff --git a/kernel/ocr/thresholds.go b/kernel/ocr/thresholds.gonew file mode 100644index 0000000000..c919553049--- /dev/null+++ b/kernel/ocr/thresholds.go@@ -0,0 +1,44 @@+package ocr++import (+ "errors"+ "math"+ "strings"+)++// Thresholds 仅覆盖本次识别的后处理参数,空值保留模型检测配置和既有识别阈值。+type Thresholds struct {+ Detection *float64 `json:"detection"`+ Box *float64 `json:"box"`+ Recognition *float64 `json:"recognition"`+}++func (t Thresholds) Validate() error {+ for _, value := range []*float64{t.Detection, t.Box} {+ if value != nil && (math.IsNaN(*value) || math.IsInf(*value, 0) || *value <= 0 || *value >= 1) {+ return errors.New("OCR detection and box thresholds must be greater than 0 and less than 1")+ }+ }+ if value := t.Recognition; value != nil && (math.IsNaN(*value) || math.IsInf(*value, 0) || *value < 0 || *value > 1) {+ return errors.New("OCR recognition threshold must be between 0 and 1")+ }+ return nil+}++func (t Thresholds) detectionConfig(config modelConfig) modelConfig {+ if t.Detection != nil {+ config.PostProcess.Threshold = *t.Detection+ }+ if t.Box != nil {+ config.PostProcess.BoxThreshold = *t.Box+ }+ return config+}++func (t Thresholds) accepts(text string, confidence float64) bool {+ threshold := 0.5+ if t.Recognition != nil {+ threshold = *t.Recognition+ }+ return strings.TrimSpace(text) != "" && confidence >= threshold+}diff --git a/kernel/ocr/thresholds_test.go b/kernel/ocr/thresholds_test.gonew file mode 100644index 0000000000..f279902cdf--- /dev/null+++ b/kernel/ocr/thresholds_test.go@@ -0,0 +1,75 @@+package ocr++import (+ "encoding/json"+ "math"+ "reflect"+ "testing"+)++func TestOCRThresholdFiltering(t *testing.T) {+ base := modelConfig{}+ base.PostProcess.Threshold, base.PostProcess.BoxThreshold, base.PostProcess.Unclip = 0.3, 0.6, 1.5+ output := tensor{data: make([]float32, 100), shape: []int64{1, 1, 10, 10}}+ for y := 2; y < 8; y++ {+ for x := 2; x < 8; x++ {+ output.data[y*10+x] = 0.7+ }+ }+ high := 0.8+ for _, test := range []struct {+ name string+ thresholds Thresholds+ boxes int+ }{+ {"model defaults", Thresholds{}, 1},+ {"detection removes weak pixels", Thresholds{Detection: &high}, 0},+ {"box removes weak regions", Thresholds{Box: &high}, 0},+ {"reset restores regions", Thresholds{}, 1},+ } {+ t.Run(test.name, func(t *testing.T) {+ boxes, err := detectBoxes(output, 100, 100, test.thresholds.detectionConfig(base))+ if err != nil || len(boxes) != test.boxes {+ t.Fatalf("boxes=%v err=%v", boxes, err)+ }+ })+ }+ if base.PostProcess.Threshold != 0.3 || base.PostProcess.BoxThreshold != 0.6 {+ t.Fatal("overrides mutated model defaults")+ }+ defaults, strict := Thresholds{}, Thresholds{Recognition: &high}+ if !defaults.accepts("text", 0.5) || defaults.accepts("text", 0.49) || strict.accepts("text", 0.7) || !strict.accepts("text", 0.8) || strict.accepts(" \n", 1) {+ t.Fatal("recognition confidence or empty-text filtering failed")+ }+}++func TestOCRThresholdValidation(t *testing.T) {+ for _, value := range []float64{math.NaN(), math.Inf(1), math.Inf(-1), -0.1, 1.1, 0, 1} {+ for _, options := range []Thresholds{{Detection: &value}, {Box: &value}} {+ if options.Validate() == nil {+ t.Fatalf("accepted invalid detector threshold %v", value)+ }+ }+ err := (Thresholds{Recognition: &value}).Validate()+ if (err == nil) != (value == 0 || value == 1) {+ t.Fatalf("recognition threshold %v: %v", value, err)+ }+ }+ value := 0.7+ if err := (Thresholds{Detection: &value, Box: &value, Recognition: &value}).Validate(); err != nil {+ t.Fatal(err)+ }+}++func TestOCRWorkerThresholdRoundTrip(t *testing.T) {+ detection, box, recognition := 0.4, 0.7, 0.9+ request := WorkerRequest{Config: PaddleConfig{Directory: "model", Thresholds: Thresholds{Detection: &detection, Box: &box, Recognition: &recognition}}, Image: "image.png"}+ data, err := json.Marshal(request)+ if err != nil {+ t.Fatal(err)+ }+ var decoded WorkerRequest+ if err = json.Unmarshal(data, &decoded); err != nil || !reflect.DeepEqual(request, decoded) {+ t.Fatalf("worker lost thresholds: %+v, %v", decoded, err)+ }+}