Skip to content

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

:art: Support configurable image OCR tooltips https://github.com/siyuan-note/siyuan/issues/20528

Danielae0f2ae9ba7e
diff --git a/app/appearance/langs/ar.json b/app/appearance/langs/ar.json
index 066a2137b6..b35eb56dab 100644
--- a/app/appearance/langs/ar.json
+++ b/app/appearance/langs/ar.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "تلميحات الصور",
+ "ocrShowText": "عرض نص OCR",
+ "ocrShowTextTip": "معاينة نص OCR المحفوظ في تلميحات الصور",
+ "ocrShowEmpty": "التنبيه عند عدم وجود نص OCR",
+ "ocrShowEmptyTip": "عرض تنبيه في تلميح الصورة عند عدم وجود نص OCR",
+ "ocrShowError": "التنبيه عند فشل OCR",
+ "ocrShowErrorTip": "عرض تنبيه في تلميح الصورة عند فشل التعرف على النص",
+ "ocrNoText": "لا يوجد نص OCR",
+ "ocrFailed": "فشل التعرف على النص باستخدام OCR",
"autoCloseRefBrackets": "إغلاق <code class='fn__code'>[[</code> تلقائيًا",
"autoCloseRefBracketsTip": "عند الكتابة [[ يُضاف ]] تلقائيًا، وكتابة ]] تُكمل المرجع إلى المستند الذي يطابق عنوانه تمامًا أو تُنشئ مستندًا جديدًا",
"currentTime": "الوقت الحالي",
diff --git a/app/appearance/langs/de.json b/app/appearance/langs/de.json
index 19fac162b3..62a01cd7bc 100644
--- a/app/appearance/langs/de.json
+++ b/app/appearance/langs/de.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Bildhinweise",
+ "ocrShowText": "OCR-Text anzeigen",
+ "ocrShowTextTip": "Gespeicherten OCR-Text im Bildhinweis anzeigen",
+ "ocrShowEmpty": "Auf fehlenden OCR-Text hinweisen",
+ "ocrShowEmptyTip": "Im Bildhinweis anzeigen, wenn kein OCR-Text vorhanden ist",
+ "ocrShowError": "Auf OCR-Fehler hinweisen",
+ "ocrShowErrorTip": "Im Bildhinweis anzeigen, wenn die Texterkennung fehlschlägt",
+ "ocrNoText": "Kein OCR-Text",
+ "ocrFailed": "OCR-Texterkennung fehlgeschlagen",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> automatisch schließen",
"autoCloseRefBracketsTip": "Beim Tippen von [[ wird ]] automatisch eingefügt; die Eingabe von ]] vervollständigt den Verweis auf das Dokument mit exakt passendem Titel oder erstellt ein neues Dokument",
"currentTime": "Aktuelle Uhrzeit",
diff --git a/app/appearance/langs/en.json b/app/appearance/langs/en.json
index 6bb551ea91..afec7a1b66 100644
--- a/app/appearance/langs/en.json
+++ b/app/appearance/langs/en.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Image tooltips",
+ "ocrShowText": "Show OCR text",
+ "ocrShowTextTip": "Preview saved OCR text in image tooltips",
+ "ocrShowEmpty": "Show a hint when OCR text is absent",
+ "ocrShowEmptyTip": "Show a hint in the image tooltip when there is no OCR text",
+ "ocrShowError": "Show OCR failure hints",
+ "ocrShowErrorTip": "Show a hint in the image tooltip when recognition fails",
+ "ocrNoText": "No OCR text",
+ "ocrFailed": "OCR recognition failed",
"autoCloseRefBrackets": "Auto-close <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Typing [[ automatically inserts ]]; typing ]] completes the reference to the document with an exactly matching title, or creates a new document",
"currentTime": "Current Time",
diff --git a/app/appearance/langs/es.json b/app/appearance/langs/es.json
index d861c23838..0c8bf63d94 100644
--- a/app/appearance/langs/es.json
+++ b/app/appearance/langs/es.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Información de las imágenes",
+ "ocrShowText": "Mostrar texto OCR",
+ "ocrShowTextTip": "Mostrar una vista previa del texto OCR guardado en la información de la imagen",
+ "ocrShowEmpty": "Avisar cuando no haya texto OCR",
+ "ocrShowEmptyTip": "Mostrar un aviso en la información de la imagen cuando no haya texto OCR",
+ "ocrShowError": "Avisar de errores de OCR",
+ "ocrShowErrorTip": "Mostrar un aviso en la información de la imagen cuando falle el reconocimiento",
+ "ocrNoText": "Sin texto OCR",
+ "ocrFailed": "Error en el reconocimiento OCR",
"autoCloseRefBrackets": "Cerrar <code class='fn__code'>[[</code> automáticamente",
"autoCloseRefBracketsTip": "Al escribir [[ se inserta ]] automáticamente; al escribir ]] se completa la referencia al documento cuyo título coincide exactamente o se crea un documento nuevo",
"currentTime": "Hora actual",
diff --git a/app/appearance/langs/fr.json b/app/appearance/langs/fr.json
index 2253469a09..3e1a9cd998 100644
--- a/app/appearance/langs/fr.json
+++ b/app/appearance/langs/fr.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Infobulles des images",
+ "ocrShowText": "Afficher le texte OCR",
+ "ocrShowTextTip": "Afficher un aperçu du texte OCR enregistré dans les infobulles des images",
+ "ocrShowEmpty": "Signaler l’absence de texte OCR",
+ "ocrShowEmptyTip": "Afficher une indication dans l’infobulle de l’image lorsqu’il n’y a pas de texte OCR",
+ "ocrShowError": "Signaler les échecs OCR",
+ "ocrShowErrorTip": "Afficher une indication dans l’infobulle de l’image lorsque la reconnaissance échoue",
+ "ocrNoText": "Aucun texte OCR",
+ "ocrFailed": "Échec de la reconnaissance OCR",
"autoCloseRefBrackets": "Fermeture automatique de <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Saisir [[ insère automatiquement ]] ; saisir ]] complète la référence vers le document dont le titre correspond exactement ou crée un nouveau document",
"currentTime": "Heure actuelle",
diff --git a/app/appearance/langs/he.json b/app/appearance/langs/he.json
index 4761a9432b..37f22ba607 100644
--- a/app/appearance/langs/he.json
+++ b/app/appearance/langs/he.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "חלוניות מידע של תמונות",
+ "ocrShowText": "הצגת טקסט OCR",
+ "ocrShowTextTip": "הצגת תצוגה מקדימה של טקסט OCR שמור בחלוניות המידע של תמונות",
+ "ocrShowEmpty": "הודעה כשאין טקסט OCR",
+ "ocrShowEmptyTip": "הצגת הודעה בחלונית המידע של התמונה כשאין טקסט OCR",
+ "ocrShowError": "הודעה על כשל ב-OCR",
+ "ocrShowErrorTip": "הצגת הודעה בחלונית המידע של התמונה כשזיהוי הטקסט נכשל",
+ "ocrNoText": "אין טקסט OCR",
+ "ocrFailed": "זיהוי OCR נכשל",
"autoCloseRefBrackets": "סגירה אוטומטית של <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "הקלדת [[ מוסיפה ]] אוטומטית; הקלדת ]] משלימה את ההפניה למסמך שכותרתו תואמת בדיוק, או יוצרת מסמך חדש",
"currentTime": "השעה הנוכחית",
diff --git a/app/appearance/langs/hi.json b/app/appearance/langs/hi.json
index 286df8bb8a..442b93017b 100644
--- a/app/appearance/langs/hi.json
+++ b/app/appearance/langs/hi.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "चित्र टूलटिप",
+ "ocrShowText": "OCR पाठ दिखाएँ",
+ "ocrShowTextTip": "चित्र के टूलटिप में सहेजे गए OCR पाठ का पूर्वावलोकन दिखाएँ",
+ "ocrShowEmpty": "OCR पाठ न होने पर सूचना दें",
+ "ocrShowEmptyTip": "OCR पाठ न होने पर चित्र के टूलटिप में सूचना दिखाएँ",
+ "ocrShowError": "OCR विफल होने पर सूचना दें",
+ "ocrShowErrorTip": "पहचान विफल होने पर चित्र के टूलटिप में सूचना दिखाएँ",
+ "ocrNoText": "कोई OCR पाठ नहीं",
+ "ocrFailed": "OCR पहचान विफल हुई",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> स्वतः बंद करें",
"autoCloseRefBracketsTip": "[[ टाइप करने पर ]] स्वतः जुड़ जाता है; ]] टाइप करने पर बिल्कुल मेल खाते शीर्षक वाले दस्तावेज़ का संदर्भ पूरा होता है या नया दस्तावेज़ बनता है",
"currentTime": "वर्तमान समय",
diff --git a/app/appearance/langs/id.json b/app/appearance/langs/id.json
index e87b763442..39038d3bd8 100644
--- a/app/appearance/langs/id.json
+++ b/app/appearance/langs/id.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Tooltip gambar",
+ "ocrShowText": "Tampilkan teks OCR",
+ "ocrShowTextTip": "Pratinjau teks OCR tersimpan di tooltip gambar",
+ "ocrShowEmpty": "Beri tahu jika tidak ada teks OCR",
+ "ocrShowEmptyTip": "Tampilkan pemberitahuan di tooltip gambar jika tidak ada teks OCR",
+ "ocrShowError": "Beri tahu jika OCR gagal",
+ "ocrShowErrorTip": "Tampilkan pemberitahuan di tooltip gambar jika pengenalan gagal",
+ "ocrNoText": "Tidak ada teks OCR",
+ "ocrFailed": "Pengenalan OCR gagal",
"autoCloseRefBrackets": "Tutup <code class='fn__code'>[[</code> otomatis",
"autoCloseRefBracketsTip": "Mengetik [[ otomatis menyisipkan ]]; mengetik ]] melengkapi referensi ke dokumen dengan judul yang sama persis, atau membuat dokumen baru",
"currentTime": "Waktu Saat Ini",
diff --git a/app/appearance/langs/it.json b/app/appearance/langs/it.json
index 1d00e68f53..d8005b1440 100644
--- a/app/appearance/langs/it.json
+++ b/app/appearance/langs/it.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Suggerimenti delle immagini",
+ "ocrShowText": "Mostra testo OCR",
+ "ocrShowTextTip": "Mostra un’anteprima del testo OCR salvato nei suggerimenti delle immagini",
+ "ocrShowEmpty": "Segnala l’assenza di testo OCR",
+ "ocrShowEmptyTip": "Mostra un avviso nel suggerimento dell’immagine quando non è presente testo OCR",
+ "ocrShowError": "Segnala gli errori OCR",
+ "ocrShowErrorTip": "Mostra un avviso nel suggerimento dell’immagine quando il riconoscimento fallisce",
+ "ocrNoText": "Nessun testo OCR",
+ "ocrFailed": "Riconoscimento OCR non riuscito",
"autoCloseRefBrackets": "Chiusura automatica di <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Digitando [[ viene inserito automaticamente ]]; digitando ]] si completa il riferimento al documento con titolo identico oppure si crea un nuovo documento",
"currentTime": "Ora attuale",
diff --git a/app/appearance/langs/ja.json b/app/appearance/langs/ja.json
index 5bee8dfaa9..d02c67358d 100644
--- a/app/appearance/langs/ja.json
+++ b/app/appearance/langs/ja.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "画像のツールチップ",
+ "ocrShowText": "OCR テキストを表示",
+ "ocrShowTextTip": "画像のツールチップに保存済みの OCR テキストを表示",
+ "ocrShowEmpty": "OCR テキストがない場合に通知",
+ "ocrShowEmptyTip": "OCR テキストがない画像のツールチップに通知を表示",
+ "ocrShowError": "OCR 失敗時に通知",
+ "ocrShowErrorTip": "文字認識に失敗した画像のツールチップに通知を表示",
+ "ocrNoText": "OCR テキストなし",
+ "ocrFailed": "OCR の文字認識に失敗しました",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> を自動で閉じる",
"autoCloseRefBracketsTip": "[[ を入力すると ]] を自動挿入し、]] を入力するとタイトルが完全一致するドキュメントへの参照を完成させるか、新しいドキュメントを作成します",
"currentTime": "現在時刻",
diff --git a/app/appearance/langs/ko.json b/app/appearance/langs/ko.json
index 465ed6a0d8..ae15ba97a4 100644
--- a/app/appearance/langs/ko.json
+++ b/app/appearance/langs/ko.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "이미지 툴팁",
+ "ocrShowText": "OCR 텍스트 표시",
+ "ocrShowTextTip": "이미지 툴팁에 저장된 OCR 텍스트 미리보기 표시",
+ "ocrShowEmpty": "OCR 텍스트가 없을 때 알림",
+ "ocrShowEmptyTip": "OCR 텍스트가 없는 이미지의 툴팁에 알림 표시",
+ "ocrShowError": "OCR 실패 시 알림",
+ "ocrShowErrorTip": "문자 인식에 실패한 이미지의 툴팁에 알림 표시",
+ "ocrNoText": "OCR 텍스트 없음",
+ "ocrFailed": "OCR 문자 인식 실패",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> 자동 닫기",
"autoCloseRefBracketsTip": "[[ 입력 시 ]]가 자동으로 삽입되며, ]] 입력 시 제목이 정확히 일치하는 문서로 참조를 완성하거나 새 문서를 만듭니다",
"currentTime": "현재 시간",
diff --git a/app/appearance/langs/nl.json b/app/appearance/langs/nl.json
index 201a6c8ab2..634b71b529 100644
--- a/app/appearance/langs/nl.json
+++ b/app/appearance/langs/nl.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Afbeeldingstooltips",
+ "ocrShowText": "OCR-tekst tonen",
+ "ocrShowTextTip": "Opgeslagen OCR-tekst bekijken in afbeeldingstooltips",
+ "ocrShowEmpty": "Melden wanneer OCR-tekst ontbreekt",
+ "ocrShowEmptyTip": "Een melding tonen in de afbeeldingstooltip wanneer er geen OCR-tekst is",
+ "ocrShowError": "OCR-fouten melden",
+ "ocrShowErrorTip": "Een melding tonen in de afbeeldingstooltip wanneer herkenning mislukt",
+ "ocrNoText": "Geen OCR-tekst",
+ "ocrFailed": "OCR-herkenning mislukt",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> automatisch sluiten",
"autoCloseRefBracketsTip": "Bij het typen van [[ wordt ]] automatisch ingevoegd; het typen van ]] voltooit de verwijzing naar het document met exact dezelfde titel of maakt een nieuw document aan",
"currentTime": "Huidige tijd",
diff --git a/app/appearance/langs/pl.json b/app/appearance/langs/pl.json
index 63fe5660bc..b34461068f 100644
--- a/app/appearance/langs/pl.json
+++ b/app/appearance/langs/pl.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Podpowiedzi obrazów",
+ "ocrShowText": "Pokaż tekst OCR",
+ "ocrShowTextTip": "Wyświetl podgląd zapisanego tekstu OCR w podpowiedziach obrazów",
+ "ocrShowEmpty": "Informuj o braku tekstu OCR",
+ "ocrShowEmptyTip": "Wyświetl informację w podpowiedzi obrazu, gdy nie ma tekstu OCR",
+ "ocrShowError": "Informuj o błędach OCR",
+ "ocrShowErrorTip": "Wyświetl informację w podpowiedzi obrazu, gdy rozpoznawanie się nie powiedzie",
+ "ocrNoText": "Brak tekstu OCR",
+ "ocrFailed": "Rozpoznawanie OCR nie powiodło się",
"autoCloseRefBrackets": "Automatyczne zamykanie <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Wpisanie [[ automatycznie dodaje ]]; wpisanie ]] kończy odwołanie do dokumentu o dokładnie pasującym tytule lub tworzy nowy dokument",
"currentTime": "Bieżąca godzina",
diff --git a/app/appearance/langs/pt-BR.json b/app/appearance/langs/pt-BR.json
index faf6083bb7..a6f4ab94de 100644
--- a/app/appearance/langs/pt-BR.json
+++ b/app/appearance/langs/pt-BR.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Dicas de imagens",
+ "ocrShowText": "Mostrar texto OCR",
+ "ocrShowTextTip": "Exibir uma prévia do texto OCR salvo nas dicas de imagens",
+ "ocrShowEmpty": "Avisar quando não houver texto OCR",
+ "ocrShowEmptyTip": "Mostrar um aviso na dica da imagem quando não houver texto OCR",
+ "ocrShowError": "Avisar sobre falhas de OCR",
+ "ocrShowErrorTip": "Mostrar um aviso na dica da imagem quando o reconhecimento falhar",
+ "ocrNoText": "Sem texto OCR",
+ "ocrFailed": "Falha no reconhecimento OCR",
"autoCloseRefBrackets": "Fechar <code class='fn__code'>[[</code> automaticamente",
"autoCloseRefBracketsTip": "Digitar [[ insere ]] automaticamente; digitar ]] completa a referência ao documento com título exatamente igual ou cria um novo documento",
"currentTime": "Hora atual",
diff --git a/app/appearance/langs/ru.json b/app/appearance/langs/ru.json
index 82b6246dcc..df9612df05 100644
--- a/app/appearance/langs/ru.json
+++ b/app/appearance/langs/ru.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Подсказки изображений",
+ "ocrShowText": "Показывать текст OCR",
+ "ocrShowTextTip": "Показывать сохранённый текст OCR в подсказках изображений",
+ "ocrShowEmpty": "Сообщать об отсутствии текста OCR",
+ "ocrShowEmptyTip": "Показывать сообщение в подсказке изображения, если текст OCR отсутствует",
+ "ocrShowError": "Сообщать об ошибках OCR",
+ "ocrShowErrorTip": "Показывать сообщение в подсказке изображения при ошибке распознавания",
+ "ocrNoText": "Нет текста OCR",
+ "ocrFailed": "Ошибка распознавания OCR",
"autoCloseRefBrackets": "Автозакрытие <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "При вводе [[ автоматически добавляется ]]; ввод ]] завершает ссылку на документ с точно совпадающим заголовком или создаёт новый документ",
"currentTime": "Текущее время",
diff --git a/app/appearance/langs/sk.json b/app/appearance/langs/sk.json
index bde87142e6..6ba000760e 100644
--- a/app/appearance/langs/sk.json
+++ b/app/appearance/langs/sk.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Tipy obrázkov",
+ "ocrShowText": "Zobraziť text OCR",
+ "ocrShowTextTip": "Zobraziť uložený text OCR v tipoch obrázkov",
+ "ocrShowEmpty": "Upozorniť na chýbajúci text OCR",
+ "ocrShowEmptyTip": "Zobraziť upozornenie v tipe obrázka, keď chýba text OCR",
+ "ocrShowError": "Upozorniť na zlyhanie OCR",
+ "ocrShowErrorTip": "Zobraziť upozornenie v tipe obrázka, keď rozpoznávanie zlyhá",
+ "ocrNoText": "Žiadny text OCR",
+ "ocrFailed": "Rozpoznávanie OCR zlyhalo",
"autoCloseRefBrackets": "Automaticky uzavrieť <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Pri písaní [[ sa automaticky vloží ]]; napísanie ]] dokončí odkaz na dokument s presne zhodným názvom alebo vytvorí nový dokument",
"currentTime": "Aktuálny čas",
diff --git a/app/appearance/langs/sr.json b/app/appearance/langs/sr.json
index 5de4c96889..d98cdc01ff 100644
--- a/app/appearance/langs/sr.json
+++ b/app/appearance/langs/sr.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Облачићи слике",
+ "ocrShowText": "Прикажи OCR текст",
+ "ocrShowTextTip": "Прикажи преглед сачуваног OCR текста у облачићима слике",
+ "ocrShowEmpty": "Обавести када нема OCR текста",
+ "ocrShowEmptyTip": "Прикажи обавештење у облачићу слике када нема OCR текста",
+ "ocrShowError": "Обавести о OCR грешци",
+ "ocrShowErrorTip": "Прикажи обавештење у облачићу слике када препознавање не успе",
+ "ocrNoText": "Нема OCR текста",
+ "ocrFailed": "OCR препознавање није успело",
"autoCloseRefBrackets": "Аутоматски затвори <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Куцање [[ аутоматски додаје ]]; куцање ]] довршава референцу на документ са тачно истим насловом или прави нови документ",
"currentTime": "Тренутно време",
diff --git a/app/appearance/langs/th.json b/app/appearance/langs/th.json
index bba19c0303..00f2053c16 100644
--- a/app/appearance/langs/th.json
+++ b/app/appearance/langs/th.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "คำแนะนำรูปภาพ",
+ "ocrShowText": "แสดงข้อความ OCR",
+ "ocrShowTextTip": "แสดงตัวอย่างข้อความ OCR ที่บันทึกไว้ในคำแนะนำรูปภาพ",
+ "ocrShowEmpty": "แจ้งเมื่อไม่มีข้อความ OCR",
+ "ocrShowEmptyTip": "แสดงการแจ้งเตือนในคำแนะนำรูปภาพเมื่อไม่มีข้อความ OCR",
+ "ocrShowError": "แจ้งเมื่อ OCR ล้มเหลว",
+ "ocrShowErrorTip": "แสดงการแจ้งเตือนในคำแนะนำรูปภาพเมื่อการรู้จำล้มเหลว",
+ "ocrNoText": "ไม่มีข้อความ OCR",
+ "ocrFailed": "การรู้จำ OCR ล้มเหลว",
"autoCloseRefBrackets": "ปิด <code class='fn__code'>[[</code> อัตโนมัติ",
"autoCloseRefBracketsTip": "เมื่อพิมพ์ [[ จะเติม ]] ให้อัตโนมัติ และเมื่อพิมพ์ ]] จะอ้างอิงเอกสารที่ชื่อตรงกันทุกตัวอักษร หรือสร้างเอกสารใหม่",
"currentTime": "เวลาปัจจุบัน",
diff --git a/app/appearance/langs/tr.json b/app/appearance/langs/tr.json
index bd5d5449c3..ec0e1b9155 100644
--- a/app/appearance/langs/tr.json
+++ b/app/appearance/langs/tr.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Görsel araç ipuçları",
+ "ocrShowText": "OCR metnini göster",
+ "ocrShowTextTip": "Kaydedilmiş OCR metnini görsel araç ipuçlarında önizle",
+ "ocrShowEmpty": "OCR metni yoksa bildir",
+ "ocrShowEmptyTip": "OCR metni olmadığında görsel araç ipucunda bir bildirim göster",
+ "ocrShowError": "OCR hatalarını bildir",
+ "ocrShowErrorTip": "Tanıma başarısız olduğunda görsel araç ipucunda bir bildirim göster",
+ "ocrNoText": "OCR metni yok",
+ "ocrFailed": "OCR tanıma başarısız oldu",
"autoCloseRefBrackets": "<code class='fn__code'>[[</code> otomatik kapat",
"autoCloseRefBracketsTip": "[[ yazıldığında ]] otomatik eklenir; ]] yazmak, başlığı tam olarak eşleşen belgeye başvuruyu tamamlar veya yeni bir belge oluşturur",
"currentTime": "Geçerli Saat",
diff --git a/app/appearance/langs/uk.json b/app/appearance/langs/uk.json
index b0c94e2878..4a559e97ba 100644
--- a/app/appearance/langs/uk.json
+++ b/app/appearance/langs/uk.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "Підказки зображень",
+ "ocrShowText": "Показувати текст OCR",
+ "ocrShowTextTip": "Показувати збережений текст OCR у підказках зображень",
+ "ocrShowEmpty": "Повідомляти про відсутність тексту OCR",
+ "ocrShowEmptyTip": "Показувати повідомлення в підказці зображення, якщо текст OCR відсутній",
+ "ocrShowError": "Повідомляти про помилки OCR",
+ "ocrShowErrorTip": "Показувати повідомлення в підказці зображення в разі помилки розпізнавання",
+ "ocrNoText": "Немає тексту OCR",
+ "ocrFailed": "Помилка розпізнавання OCR",
"autoCloseRefBrackets": "Автозакриття <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "Під час введення [[ автоматично додається ]]; введення ]] завершує посилання на документ із точно збіжною назвою або створює новий документ",
"currentTime": "Поточний час",
diff --git a/app/appearance/langs/zh-CN.json b/app/appearance/langs/zh-CN.json
index 782fe82680..a03203710b 100644
--- a/app/appearance/langs/zh-CN.json
+++ b/app/appearance/langs/zh-CN.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "图片提示",
+ "ocrShowText": "显示 OCR 文本",
+ "ocrShowTextTip": "在图片悬浮提示中预览已有 OCR 文本",
+ "ocrShowEmpty": "无 OCR 文本时提示",
+ "ocrShowEmptyTip": "图片没有 OCR 文本时,在悬浮提示中显示提示",
+ "ocrShowError": "OCR 失败时提示",
+ "ocrShowErrorTip": "图片识别失败时,在悬浮提示中显示提示",
+ "ocrNoText": "无 OCR 文本",
+ "ocrFailed": "OCR 识别失败",
"autoCloseRefBrackets": "自动闭合 <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "输入 [[ 时自动补全 ]],输入 ]] 时引用标题完全一致的文档,没有则新建文档",
"currentTime": "当前时间",
diff --git a/app/appearance/langs/zh-TW.json b/app/appearance/langs/zh-TW.json
index 9c1ad1171f..61406e5af3 100644
--- a/app/appearance/langs/zh-TW.json
+++ b/app/appearance/langs/zh-TW.json
@@ -1,4 +1,13 @@
{
+ "ocrTooltipSettings": "圖片提示",
+ "ocrShowText": "顯示 OCR 文字",
+ "ocrShowTextTip": "在圖片懸浮提示中預覽已有 OCR 文字",
+ "ocrShowEmpty": "無 OCR 文字時提示",
+ "ocrShowEmptyTip": "圖片沒有 OCR 文字時,在懸浮提示中顯示提示",
+ "ocrShowError": "OCR 失敗時提示",
+ "ocrShowErrorTip": "圖片辨識失敗時,在懸浮提示中顯示提示",
+ "ocrNoText": "無 OCR 文字",
+ "ocrFailed": "OCR 辨識失敗",
"autoCloseRefBrackets": "自動閉合 <code class='fn__code'>[[</code>",
"autoCloseRefBracketsTip": "輸入 [[ 時自動補上 ]],輸入 ]] 時引用標題完全相同的文件,沒有則新建文件",
"currentTime": "目前時間",
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 bc1b279c37..6ff2ed2b85 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": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1041,7 +1041,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003636-epvk98g",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1549,7 +1549,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202934-1h96or8",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1676,7 +1676,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-3zn8sf9",
- "updated": "20261010140118"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1716,7 +1716,7 @@
},
{
"Type": "NodeText",
- "Data": " Hover over a local image to view its OCR text; an empty result is shown explicitly. The text recognition icon identifies the OCR action, while the image icon copies the image as PNG, even when no OCR text is available. In a custom appearance profile, use "
+ "Data": " Hover over a local image to view OCR text and recognition hints according to your settings. The text recognition icon identifies the OCR action, while the image icon copies the image as PNG, even when no OCR text is available. In a custom appearance profile, use "
},
{
"Type": "NodeTextMark",
@@ -1750,6 +1750,47 @@
"Data": " Long OCR text is shortened to at most 200 characters and six lines, followed by three dots. Double-click the OCR icon to view the full text."
}
]
+ },
+ {
+ "ID": "20261014140201-g0z2wp6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261014140201-g0z2wp6",
+ "updated": "20261014140201"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "In "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Settings"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "Image tooltips"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " independently choose whether image tooltips show saved OCR text, a hint when no OCR text is available, and a recognition failure hint. Text previews are enabled by default; the other two hints are disabled. These choices are saved per device and work independently of automatic OCR. Hiding hints does not delete text or change search results. No OCR text does not necessarily mean recognition has failed. Failure hints reflect recognition failures during the current session; successful recognition or saving text clears them, and they are not retained after restarting the kernel. Mobile devices do not show these hover tooltips."
+ }
+ ]
}
]
}
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 b65a561e88..ab108beef5 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": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1053,7 +1053,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117002036-vmc0mx4",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1553,7 +1553,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202710-a51lo76",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1680,7 +1680,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-qkecuzx",
- "updated": "20261010140118"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1720,7 +1720,7 @@
},
{
"Type": "NodeText",
- "Data": "悬浮在本地图片上可查看 OCR 文字,无识别结果时会显示空内容提示。文字识别图标表示 OCR 操作,图片图标则将图片复制为 PNG,无 OCR 文字时也可复制图片。在自定义外观方案中,可通过 "
+ "Data": "悬浮在本地图片上可按设置查看 OCR 文本和识别提示。文字识别图标表示 OCR 操作,图片图标则将图片复制为 PNG,无 OCR 文字时也可复制图片。在自定义外观方案中,可通过 "
},
{
"Type": "NodeTextMark",
@@ -1754,6 +1754,47 @@
"Data": "OCR 悬浮预览最多显示 200 个字符、6 行,超出部分用三个点标记。双击 OCR 图标可查看完整文字。"
}
]
+ },
+ {
+ "ID": "20261014140201-p3solxq",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261014140201-p3solxq",
+ "updated": "20261014140201"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "可在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "设置"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "图片提示"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 分别控制图片悬浮提示中的 OCR 文本、无 OCR 文本提示和识别失败提示。默认显示文本预览,另外两项默认关闭。这些选择按设备保存,独立于自动 OCR 开关;隐藏提示不会删除文本或改变搜索结果。无 OCR 文本不一定表示识别失败。失败提示反映本次运行期间的识别失败,成功识别或保存文本后清除,重启内核后不保留。移动端不显示这类悬浮提示。"
+ }
+ ]
}
]
}
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 fee7b21a42..3269e9c96a 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": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1039,7 +1039,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003901-ze4mbzz",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1539,7 +1539,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414203058-foirrwk",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1666,7 +1666,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-ffpq13r",
- "updated": "20261010140118"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1706,7 +1706,7 @@
},
{
"Type": "NodeText",
- "Data": "懸浮在本機圖片上可查看 OCR 文字,無辨識結果時會顯示空內容提示。文字辨識圖示表示 OCR 操作,圖片圖示則將圖片複製為 PNG,無 OCR 文字時也可複製圖片。在自訂外觀方案中,可透過 "
+ "Data": "懸浮在本機圖片上可依設定查看 OCR 文字和辨識提示。文字辨識圖示表示 OCR 操作,圖片圖示則將圖片複製為 PNG,無 OCR 文字時也可複製圖片。在自訂外觀方案中,可透過 "
},
{
"Type": "NodeTextMark",
@@ -1740,6 +1740,47 @@
"Data": "OCR 懸浮預覽最多顯示 200 個字元、6 行,超出部分以三個點標記。按兩下 OCR 圖示可查看完整文字。"
}
]
+ },
+ {
+ "ID": "20261014140201-ppb3syl",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261014140201-ppb3syl",
+ "updated": "20261014140201"
+ },
+ "Children": [
+ {
+ "Type": "NodeText",
+ "Data": "可在 "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "圖片提示"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " 分別控制圖片懸浮提示中的 OCR 文字、無 OCR 文字提示和辨識失敗提示。預設顯示文字預覽,另外兩項預設關閉。這些選擇按裝置儲存,獨立於自動 OCR 開關;隱藏提示不會刪除文字或改變搜尋結果。無 OCR 文字不一定表示辨識失敗。失敗提示反映本次執行期間的辨識失敗,成功辨識或儲存文字後清除,重新啟動核心後不保留。行動端不顯示這類懸浮提示。"
+ }
+ ]
}
]
}
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 722d475772..504cec9eae 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": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1079,7 +1079,7 @@
"Properties": {
"ID": "20240530101000-5bix8t1",
"id": "20240530101000-9evyuhr",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1588,7 +1588,7 @@
"Properties": {
"ID": "20240530101000-aefldsk",
"id": "20240530101000-cpod2qy",
- "updated": "20261012014930"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1730,7 +1730,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20260930090802-fdfc9yh",
- "updated": "20261010140118"
+ "updated": "20261014140201"
},
"Children": [
{
@@ -1770,7 +1770,7 @@
},
{
"Type": "NodeText",
- "Data": " ローカル画像にマウスを合わせると OCR テキストを確認でき、認識結果が空の場合も表示されます。文字認識アイコンは OCR 操作を示し、画像アイコンは OCR テキストの有無にかかわらず画像を PNG としてコピーします。カスタム外観プロファイルでは "
+ "Data": " ローカル画像にマウスを合わせると、設定に応じて OCR テキストや認識の通知を確認できます。文字認識アイコンは OCR 操作を示し、画像アイコンは OCR テキストの有無にかかわらず画像を PNG としてコピーします。カスタム外観プロファイルでは "
},
{
"Type": "NodeTextMark",
@@ -1804,6 +1804,43 @@
"Data": " OCR のホバープレビューは最大 200 文字、6 行まで表示され、長いテキストは末尾の 3 つのドットで省略を示します。OCR アイコンをダブルクリックすると全文を確認できます。"
}
]
+ },
+ {
+ "ID": "20261014140201-14ga6f6",
+ "Type": "NodeParagraph",
+ "Properties": {
+ "id": "20261014140201-14ga6f6",
+ "updated": "20261014140201"
+ },
+ "Children": [
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "設定"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "OCR"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " - "
+ },
+ {
+ "Type": "NodeTextMark",
+ "TextMarkType": "kbd",
+ "TextMarkTextContent": "画像のツールチップ"
+ },
+ {
+ "Type": "NodeText",
+ "Data": " で、保存済みの OCR テキスト、OCR テキストがない場合の通知、認識に失敗した場合の通知をそれぞれ設定できます。テキストのプレビューはデフォルトで有効、ほかの 2 項目は無効です。設定は端末ごとに保存され、自動 OCR とは独立しています。通知を非表示にしても、テキストは削除されず、検索結果も変わりません。OCR テキストがないことは、必ずしも認識の失敗を意味しません。失敗の通知は今回の実行中に発生した認識の失敗を示し、認識の成功またはテキストの保存で解除され、カーネルの再起動後には保持されません。モバイルでは、このようなホバーツールチップは表示されません。"
+ }
+ ]
}
]
}
diff --git a/app/src/asset/imageAIOCR.test.ts b/app/src/asset/imageAIOCR.test.ts
index bcf7aaef6b..362de47b96 100644
--- a/app/src/asset/imageAIOCR.test.ts
+++ b/app/src/asset/imageAIOCR.test.ts
@@ -40,7 +40,7 @@ test("AI OCR prevents duplicate requests, refreshes saved results, and recovers
reject(new Error("Network failure"));
await networkFailure;
assert.equal(paths.length, 3);
- assert.equal(refreshed.length, 1);
+ assert.deepEqual(refreshed, [path, path, path]);
assert.equal(opened.length, 1);
assert.deepEqual(hidden, ["progress-id", "progress-id", "progress-id"]);
assert.ok(messages.includes("Network failure"));
diff --git a/app/src/asset/imageAIOCR.ts b/app/src/asset/imageAIOCR.ts
index 2186df72be..e0f19a9b50 100644
--- a/app/src/asset/imageAIOCR.ts
+++ b/app/src/asset/imageAIOCR.ts
@@ -16,12 +16,12 @@ export const reImageAIOCR = async (path: string) => {
try {
const response = await fetchSyncPost("/api/ai/ocr", {path});
if (response.code === 0) {
- invalidateImageOCRStatus(path);
openImageOCR(path);
}
} catch (error) {
showMessage(error.message, 7000, "error");
} finally {
+ invalidateImageOCRStatus(path);
pending.delete(path);
hideMessage(messageId);
}
diff --git a/app/src/asset/imageOCRStatus.test.ts b/app/src/asset/imageOCRStatus.test.ts
index 392527e303..c1204d0ddf 100644
--- a/app/src/asset/imageOCRStatus.test.ts
+++ b/app/src/asset/imageOCRStatus.test.ts
@@ -8,7 +8,7 @@ const loadCache = () => {
let now = 1000;
let requests = 0;
let events = 0;
- const pending: {resolve: (value: {code: number, data: {text: string}}) => void, reject: (error: Error) => void}[] = [];
+ const pending: {resolve: (value: {code: number, data: {text: string, failed?: boolean}}) => void, reject: (error: Error) => void}[] = [];
const api = {} as typeof import("./imageOCRStatus");
runInNewContext(transpileModule(readFileSync("src/asset/imageOCRStatus.ts", "utf8"), {
compilerOptions: {module: ModuleKind.CommonJS},
@@ -21,7 +21,7 @@ const loadCache = () => {
assert.equal(url, "/api/asset/getImageOCRText");
assert.equal(process, false);
requests++;
- return new Promise<{code: number, data: {text: string}}>((resolve, reject) => pending.push({resolve, reject}));
+ return new Promise<{code: number, data: {text: string, failed?: boolean}}>((resolve, reject) => pending.push({resolve, reject}));
}}),
});
return {api, pending, requests: () => requests, events: () => events, advance: () => now += 60001};
@@ -79,6 +79,25 @@ test("OCR changes invalidate only the resource and stale requests cannot replace
assert.equal(requests(), 3);
});
+test("OCR result cache retains recognition failures separately from saved text and read failures", async () => {
+ const {api, pending, requests} = loadCache();
+ const result = api.getImageOCRResult("assets/image.png");
+ const text = api.getImageOCRText("assets/image.png");
+ const presence = api.getImageOCRStatus("assets/image.png");
+ pending.shift().resolve({code: 0, data: {text: "saved", failed: true}});
+ assert.deepEqual(await result, {text: "saved", failed: true});
+ assert.equal(await text, "saved");
+ assert.equal(await presence, true);
+ assert.equal(requests(), 1);
+ api.invalidateImageOCRStatus("assets/image.png");
+ const updated = api.getImageOCRResult("assets/image.png");
+ pending.shift().resolve({code: 0, data: {text: "", failed: false}});
+ assert.deepEqual(await updated, {text: "", failed: false});
+ const unavailable = api.getImageOCRResult("assets/unavailable.png");
+ pending.shift().reject(new Error("network"));
+ assert.equal(await unavailable, undefined);
+});
+
test("OCR presence cache is bounded", async () => {
const {api, pending, requests} = loadCache();
for (let i = 0; i < 129; i++) {
diff --git a/app/src/asset/imageOCRStatus.ts b/app/src/asset/imageOCRStatus.ts
index 3aa2bfd37e..0b28ff3566 100644
--- a/app/src/asset/imageOCRStatus.ts
+++ b/app/src/asset/imageOCRStatus.ts
@@ -1,7 +1,9 @@
import {fetchSyncPost} from "../util/fetch";
+import type {ImageOCRTextData} from "../types/api";
// 悬浮提示和按钮共享识别结果,短期过期以反映后台识别和其他客户端的修改。
-const statuses = new Map<string, {expires: number, result: Promise<string | undefined>, status: Promise<boolean | undefined>}>();
+const statuses = new Map<string, {expires: number, result: Promise<ImageOCRTextData | undefined>,
+ text: Promise<string | undefined>, status: Promise<boolean | undefined>}>();
const cacheDuration = 60000;
const cacheLimit = 128;
@@ -14,12 +16,13 @@ const getImageOCREntry = (path: string) => {
if (response.code !== 0) {
return undefined;
}
- return response.data.text;
+ return response.data;
}).catch(() => undefined);
const entry = {
expires: Infinity,
result,
- status: result.then(text => text === undefined ? undefined : text.trim().length > 0),
+ text: result.then(data => data?.text),
+ status: result.then(data => data === undefined ? undefined : data.text.trim().length > 0),
};
statuses.delete(path);
statuses.set(path, entry);
@@ -41,7 +44,9 @@ const getImageOCREntry = (path: string) => {
export const getImageOCRStatus = (path: string): Promise<boolean | undefined> => getImageOCREntry(path).status;
-export const getImageOCRText = (path: string): Promise<string | undefined> => getImageOCREntry(path).result;
+export const getImageOCRText = (path: string): Promise<string | undefined> => getImageOCREntry(path).text;
+
+export const getImageOCRResult = (path: string): Promise<ImageOCRTextData | undefined> => getImageOCREntry(path).result;
export const invalidateImageOCRStatus = (path: string) => {
statuses.delete(path);
diff --git a/app/src/block/popover.test.ts b/app/src/block/popover.test.ts
index 748e9462fa..3b8cc8333c 100644
--- a/app/src/block/popover.test.ts
+++ b/app/src/block/popover.test.ts
@@ -12,7 +12,7 @@ const browserCases = async (source: string) => {
const requests: ((response: unknown) => void)[] = [];
let tooltip = "";
const assetRequests: {path: string, signal: AbortSignal, receive: (response: unknown) => void}[] = [];
- const ocrRequests: ((text: string | undefined) => void)[] = [];
+ const ocrRequests: ((text: string | undefined | {text: string, failed: boolean}) => void)[] = [];
class Panel {
element = document.createElement("div");
editors: {protyle: IProtyle}[] = [];
@@ -38,7 +38,8 @@ const browserCases = async (source: string) => {
const dependencies = {
BlockPanel: Panel,
fetchSyncPost: () => new Promise(resolve => requests.push(resolve)),
- getImageOCRText: () => new Promise<string | undefined>(resolve => ocrRequests.push(resolve)),
+ getImageOCRResult: () => new Promise<{text: string, failed: boolean} | undefined>(resolve => ocrRequests.push(result =>
+ resolve(typeof result === "string" ? {text: result, failed: false} : result))),
hideTooltip: () => {},
showTooltip: (text: string) => { tooltip = text; },
fetchPost: (_url: string, body: {path: string}, receive: (response: unknown) => void,
@@ -63,7 +64,8 @@ const browserCases = async (source: string) => {
config: {editor: {floatWindowMode: 0, floatWindowDelay: 20}},
menus: {menu: {element: document.createElement("div")}},
blockPanels: [],
- languages: {ocrResult: "OCR text", emptyContent: "No related content found", modifiedAt: "Modified", createdAt: "Created"},
+ languages: {ocrResult: "OCR text", ocrNoText: "No OCR text", ocrFailed: "OCR recognition failed",
+ emptyContent: "No related content found", modifiedAt: "Modified", createdAt: "Created"},
} as unknown as typeof window.siyuan;
window.JSAndroid = {} as typeof window.JSAndroid;
const root = document.createElement("div");
@@ -242,6 +244,33 @@ const browserCases = async (source: string) => {
check.ok(tooltip.endsWith("1<br>2<br>3<br>4<br>5<br>6"), "six complete lines remain unchanged");
check.equal(image.title, "");
check.equal(image.alt, "");
+ window.siyuan.config.ocr = {provider: "paddleocr", model: "tiny", auto: false,
+ showText: false, showEmpty: false, showError: false};
+ const previousOCRRequests = ocrRequests.length;
+ image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ check.equal(ocrRequests.length, previousOCRRequests, "disabled tooltip options skip OCR reads but retain asset information");
+ check.match(tooltip, /PNG · 1920 × 1080/);
+ window.siyuan.config.ocr.showEmpty = true;
+ image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ ocrRequests.at(-1)("");
+ await Promise.resolve();
+ check.match(tooltip, /No OCR text$/);
+ window.siyuan.config.ocr.showError = true;
+ image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ ocrRequests.at(-1)({text: "old text", failed: true});
+ await Promise.resolve();
+ check.match(tooltip, /OCR recognition failed$/);
+ check.equal(tooltip.includes("old text"), false);
+ image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ ocrRequests.at(-1)(undefined);
+ await Promise.resolve();
+ check.doesNotMatch(tooltip, /No OCR text|OCR recognition failed/, "read failures are not recognition failures");
+ window.siyuan.config.ocr.showText = true;
+ image.dispatchEvent(new MouseEvent("mouseover", {bubbles: true}));
+ window.siyuan.config.ocr.showText = false;
+ ocrRequests.at(-1)("late preview");
+ await Promise.resolve();
+ check.equal(tooltip.includes("late preview"), false, "late responses use the latest tooltip preferences");
const link = document.createElement("span");
link.setAttribute("data-type", "a");
link.setAttribute("data-href", "https://example.com/file.pdf");
diff --git a/app/src/block/popover.ts b/app/src/block/popover.ts
index 073af7425f..9b2c902a65 100644
--- a/app/src/block/popover.ts
+++ b/app/src/block/popover.ts
@@ -15,7 +15,8 @@ import {isTouchDevice} from "../util/functions";
import {escapeAriaLabel, escapeHtml, escapeLessThans, escapeHtmlTextAndAttr} from "../util/escape";
import {isListItemActionElement} from "../protyle/wysiwyg/listContext";
import {getImageTooltip} from "../protyle/render/imageTooltip";
-import {getImageOCRText} from "../asset/imageOCRStatus";
+import {getImageOCRResult} from "../asset/imageOCRStatus";
+import type {ImageOCRTextData} from "../types/api";
import {
cancelPendingPopover,
getPopoverGeneration,
@@ -194,16 +195,17 @@ export const initBlockPopover = (app: App) => {
tooltipAbortController = new AbortController();
const capturedController = tooltipAbortController;
let size: string;
- let ocrText: string;
+ let ocrResult: ImageOCRTextData;
const updateImageTooltip = () => {
if (!capturedController.signal.aborted && image.isConnected &&
(image.getAttribute("data-src") || image.getAttribute("src")) === imagePath) {
- showTooltip(getImageTooltip(image, size, ocrText), image, undefined, event);
+ showTooltip(getImageTooltip(image, size, ocrResult?.text, ocrResult?.failed), image, undefined, event);
}
};
- if (imagePath.startsWith("assets/")) {
- getImageOCRText(imagePath).then(text => {
- ocrText = text;
+ const ocr = window.siyuan.config.ocr;
+ if (imagePath.startsWith("assets/") && (ocr?.showText !== false || ocr?.showEmpty || ocr?.showError)) {
+ getImageOCRResult(imagePath).then(result => {
+ ocrResult = result;
updateImageTooltip();
});
}
diff --git a/app/src/config/ocr.test.ts b/app/src/config/ocr.test.ts
index 893e718cb6..e55695fd7d 100644
--- a/app/src/config/ocr.test.ts
+++ b/app/src/config/ocr.test.ts
@@ -10,6 +10,7 @@ import type {applySettingTabSearchVisibility, clearSettingTabSearch} from "./set
const generalRowNames = ["ocrAuto", "ocrProvider", "ocrModel", "ocrImport", "ocrAIModel", "ocrReasoningEffort"];
const advancedRowNames = ["ocrThreshold_detection", "ocrThreshold_box", "ocrThreshold_recognition"];
+const tooltipRowNames = ["ocr_showText", "ocr_showEmpty", "ocr_showError"];
test("OCR settings register separate searchable rows in shared desktop and mobile groups", () => {
const compiled = transpileModule(readFileSync("src/config/ocr.ts", "utf8"), {
@@ -59,6 +60,9 @@ test("OCR settings register separate searchable rows in shared desktop and mobil
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.equal(groupTitles.get("tooltip"), "ocrTooltipSettings");
+ assert.deepEqual(rows.filter(row => row.group === "tooltip").map(row => row.key), tooltipRowNames);
+ rows.filter(row => row.group === "tooltip").forEach(row => assert.ok(row.keywords.length === 2));
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/);
@@ -99,7 +103,7 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
contains(name: string) { return classes.has(name); },
};
};
- const controls = Object.fromEntries([...generalIds, ...advancedIds].map(id => [id, {
+ const controls = Object.fromEntries([...generalIds, ...advancedIds, ...tooltipRowNames].map(id => [id, {
id, value: id === "ocrProvider" ? "paddleocr" : id === "ocrAIModel" || id === "ocrReasoningEffort" ? "" : "tiny", checked: false, disabled: false, innerHTML: "",
tagName: id === "ocrImport" ? "BUTTON" : "INPUT",
validationMessage: "", validity: {badInput: false},
@@ -117,6 +121,7 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
});
const groups: Record<string, ReturnType<typeof groupElement>> = {
general: groupElement("general", generalIds), advanced: groupElement("advanced", advancedIds),
+ tooltip: groupElement("tooltip", tooltipRowNames),
};
const listeners = new Map<string, (event: unknown) => Promise<void>>();
let renders = 0;
@@ -240,9 +245,55 @@ const createOCRPanel = async (initial?: {config?: SettingOCR}) => {
controls.ocrAuto.checked = checked;
return listeners.get("change")({target: controls.ocrAuto, stopPropagation() {}});
},
+ changeTooltip: (key: "showText" | "showEmpty" | "showError", checked: boolean) => {
+ const control = controls[`ocr_${key}`];
+ control.checked = checked;
+ return listeners.get("change")({target: control, stopPropagation() {}});
+ },
};
};
+test("OCR tooltip switches save independently, recover after failed saves and receive notifications", async () => {
+ const panel = await createOCRPanel();
+ assert.equal(panel.controls.ocr_showText.checked, true);
+ assert.equal(panel.controls.ocr_showEmpty.checked, false);
+ assert.equal(panel.controls.ocr_showError.checked, false);
+ const hide = panel.changeTooltip("showText", false);
+ await new Promise(setImmediate);
+ const empty = panel.changeTooltip("showEmpty", true);
+ assert.equal(panel.requests[0].config.auto, false);
+ assert.equal(panel.requests[0].config.showText, false);
+ assert.equal(panel.controls.ocr_showEmpty.disabled, false);
+ panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
+ await hide;
+ await new Promise(setImmediate);
+ assert.equal(panel.requests[1].config.showText, false);
+ assert.equal(panel.requests[1].config.showEmpty, true);
+ panel.requests[1].resolve({code: 0, data: panel.requests[1].config});
+ await empty;
+ const error = panel.changeTooltip("showError", true);
+ await new Promise(setImmediate);
+ panel.requests[2].resolve({code: -1});
+ await error;
+ assert.equal(panel.controls.ocr_showError.checked, false);
+ assert.equal(panel.controls.ocr_showEmpty.checked, true);
+ panel.updateServer({provider: "tesseract", model: "tiny", auto: true,
+ showText: true, showEmpty: false, showError: true});
+ panel.notify();
+ await new Promise(setImmediate);
+ assert.equal(panel.controls.ocr_showText.checked, true);
+ assert.equal(panel.controls.ocr_showEmpty.checked, false);
+ assert.equal(panel.controls.ocr_showError.checked, true);
+ const automatic = panel.changeAuto(false);
+ await new Promise(setImmediate);
+ assert.equal(panel.requests[3].config.showText, true);
+ assert.equal(panel.requests[3].config.showError, true);
+ panel.requests[3].resolve({code: 0, data: panel.requests[3].config});
+ await automatic;
+ assert.equal(panel.renders(), 0);
+ panel.close();
+});
+
test("selecting AI uses a separate model and requires opting into automatic recognition", async () => {
const panel = await createOCRPanel();
assert.doesNotMatch(panel.controls.ocrProvider.innerHTML, /value="ai"/);
@@ -360,19 +411,19 @@ test("hidden trailing rows keep the last visible OCR row borderless for every pr
const marked = () => Object.values(panel.controls)
.filter(control => control.classList.contains("b3-label--noborder")).map(control => control.id);
// PaddleOCR:末尾两项隐藏,导入行成为最后可见项
- assert.deepEqual(marked(), ["ocrImport", "ocrThreshold_recognition"]);
+ assert.deepEqual(marked(), ["ocrImport", "ocrThreshold_recognition", "ocr_showError"]);
const tesseract = panel.changeProvider("tesseract");
await new Promise(setImmediate);
panel.requests[0].resolve({code: 0, data: panel.requests[0].config});
await tesseract;
// Tesseract:模型与导入行也隐藏,提供商行成为最后可见项
- assert.deepEqual(marked(), ["ocrProvider", "ocrThreshold_recognition"]);
+ assert.deepEqual(marked(), ["ocrProvider", "ocrThreshold_recognition", "ocr_showError"]);
const ai = panel.changeProvider("ai");
await new Promise(setImmediate);
panel.requests[1].resolve({code: 0, data: panel.requests[1].config});
await ai;
// AI:末尾两项可见,仅隐藏模型与导入行
- assert.deepEqual(marked(), ["ocrReasoningEffort", "ocrThreshold_recognition"]);
+ assert.deepEqual(marked(), ["ocrReasoningEffort", "ocrThreshold_recognition", "ocr_showError"]);
panel.close();
});
diff --git a/app/src/config/ocr.ts b/app/src/config/ocr.ts
index 570312c8f0..900206534f 100644
--- a/app/src/config/ocr.ts
+++ b/app/src/config/ocr.ts
@@ -45,6 +45,12 @@ const getThresholdFields = () => [
{key: "recognition", title: window.siyuan.languages.ocrRecognitionThreshold, placeholder: "0.5"},
] as const;
+const getTooltipFields = () => [
+ {key: "showText", title: window.siyuan.languages.ocrShowText, tip: window.siyuan.languages.ocrShowTextTip, default: true},
+ {key: "showEmpty", title: window.siyuan.languages.ocrShowEmpty, tip: window.siyuan.languages.ocrShowEmptyTip, default: false},
+ {key: "showError", title: window.siyuan.languages.ocrShowError, tip: window.siyuan.languages.ocrShowErrorTip, default: false},
+] as const;
+
export const registerOCRTab = (tab: SettingTabBuilder) => {
const languages = window.siyuan.languages;
tab.group("general", languages.configGroupOCREngine).slot({
@@ -84,6 +90,14 @@ export const registerOCRTab = (tab: SettingTabBuilder) => {
<span class="fn__space"></span>${genNumberInputHtml(`ocrThreshold_${field.key}`, "", 0, 1, "any")}</div>`,
});
});
+ const tooltip = tab.group("tooltip", languages.ocrTooltipSettings);
+ getTooltipFields().forEach(field => {
+ tooltip.slot({
+ key: `ocr_${field.key}`,
+ keywords: [field.title, field.tip],
+ html: () => genSwitchRow(`ocr_${field.key}`, field.title, field.tip, field.default),
+ });
+ });
};
export const mountOCRSettings = (root: HTMLElement): (() => void) => {
@@ -99,6 +113,12 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
let importDialog: ReturnType<typeof openOCRImportModelsDialog> | undefined;
const languages = window.siyuan.languages;
const thresholdFields = getThresholdFields();
+ const tooltipFields = getTooltipFields();
+ const updateTooltipInputs = () => {
+ tooltipFields.forEach(field => {
+ root.querySelector<HTMLInputElement>(`#ocr_${field.key}`).checked = data.config[field.key] ?? field.default;
+ });
+ };
const dirtyThresholds = new Set<keyof OCRThresholds>();
let thresholdValues: OCRThresholds;
const updateThresholdInputs = () => {
@@ -181,6 +201,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;
+ updateTooltipInputs();
updateThresholdInputs();
updateControls();
};
@@ -249,6 +270,9 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
provider: root.querySelector<HTMLSelectElement>("#ocrProvider").value,
model: root.querySelector<HTMLSelectElement>("#ocrModel").value,
auto: root.querySelector<HTMLInputElement>("#ocrAuto").checked,
+ showText: root.querySelector<HTMLInputElement>("#ocr_showText").checked,
+ showEmpty: root.querySelector<HTMLInputElement>("#ocr_showEmpty").checked,
+ showError: root.querySelector<HTMLInputElement>("#ocr_showError").checked,
aiModelId: root.querySelector<HTMLSelectElement>("#ocrAIModel").value,
reasoningEffort: root.querySelector<HTMLSelectElement>("#ocrReasoningEffort").value,
thresholds,
@@ -277,6 +301,7 @@ export const mountOCRSettings = (root: HTMLElement): (() => void) => {
root.querySelector<HTMLSelectElement>("#ocrProvider").value = data.config.provider;
root.querySelector<HTMLSelectElement>("#ocrModel").value = data.config.model;
root.querySelector<HTMLInputElement>("#ocrAuto").checked = data.config.auto;
+ updateTooltipInputs();
root.querySelector<HTMLSelectElement>("#ocrAIModel").innerHTML = aiModelOptions();
root.querySelector<HTMLSelectElement>("#ocrAIModel").value = data.config.aiModelId || "";
root.querySelector<HTMLSelectElement>("#ocrReasoningEffort").value = data.config.reasoningEffort || "";
diff --git a/app/src/menus/imageOCRMenu.test.ts b/app/src/menus/imageOCRMenu.test.ts
new file mode 100644
index 0000000000..43a2da1210
--- /dev/null
+++ b/app/src/menus/imageOCRMenu.test.ts
@@ -0,0 +1,38 @@
+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";
+
+test("shared local OCR menu refreshes tooltip state after successful and failed requests", async () => {
+ const api = {} as typeof import("./imageOCRMenu");
+ const invalidated: string[] = [];
+ let complete: () => void;
+ let currentPath = "assets/image.png";
+ runInNewContext(transpileModule(readFileSync("src/menus/imageOCRMenu.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports: api, window: {siyuan: {config: {ocr: {provider: "paddleocr"}}}}, require: () => ({
+ getImageOCRAvailability: () => ({text: true, local: true, ai: true}),
+ isDisabledFeature: () => false,
+ createDeclaredMenu: (_declaration: unknown, context: unknown) => context,
+ fetchPost: (url: string, body: {path: string}) => {
+ assert.equal(url, "/api/asset/ocr");
+ assert.equal(body.path, currentPath);
+ return new Promise<void>(resolve => { complete = resolve; });
+ },
+ invalidateImageOCRStatus: (path: string) => invalidated.push(path),
+ })});
+ const context = api.createImageOCRMenu({getAttribute: () => currentPath} as unknown as HTMLElement, "notebook") as unknown as {
+ runLocal: () => void;
+ };
+ context.runLocal();
+ complete();
+ await Promise.resolve();
+ assert.deepEqual(invalidated, ["assets/image.png"]);
+ currentPath = "assets/another.png";
+ context.runLocal();
+ currentPath = "assets/replaced.png";
+ complete();
+ await Promise.resolve();
+ assert.deepEqual(invalidated, ["assets/image.png", "assets/another.png"]);
+});
diff --git a/app/src/menus/imageOCRMenu.ts b/app/src/menus/imageOCRMenu.ts
index 3eaf51a44f..c350f0acfb 100644
--- a/app/src/menus/imageOCRMenu.ts
+++ b/app/src/menus/imageOCRMenu.ts
@@ -20,7 +20,7 @@ export const createImageOCRMenu = (image: HTMLElement, notebookID: string): IMen
runAI: () => { void reImageAIOCR(image.getAttribute("data-src")); },
runLocal: () => {
const currentPath = image.getAttribute("data-src");
- fetchPost("/api/asset/ocr", {path: currentPath}, () => invalidateImageOCRStatus(currentPath));
+ void fetchPost("/api/asset/ocr", {path: currentPath}).finally(() => invalidateImageOCRStatus(currentPath));
},
});
};
diff --git a/app/src/protyle/render/imageTooltip.test.ts b/app/src/protyle/render/imageTooltip.test.ts
new file mode 100644
index 0000000000..f63d4d955d
--- /dev/null
+++ b/app/src/protyle/render/imageTooltip.test.ts
@@ -0,0 +1,58 @@
+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 {escapeHtml} from "../../util/escape";
+
+const createTooltip = (preferences: Record<string, boolean> = {}) => {
+ const config = {ocr: preferences};
+ const api = {} as typeof import("./imageTooltip");
+ runInNewContext(transpileModule(readFileSync("src/protyle/render/imageTooltip.ts", "utf8"), {
+ compilerOptions: {module: ModuleKind.CommonJS, target: ScriptTarget.ES2021},
+ }).outputText, {exports: api, window: {siyuan: {config,
+ languages: {ocrResult: "OCR text", ocrNoText: "No OCR text", ocrFailed: "OCR recognition failed"}}},
+ require: () => ({escapeHtml, getImageTitle: () => "", getAssetName: () => "image", getAssetExtension: () => ".png"})});
+ const image = {getAttribute: () => "assets/image.png", alt: "", naturalWidth: 100, naturalHeight: 50} as unknown as HTMLImageElement;
+ return {get: (text?: string, failed = false) => api.getImageTooltip(image, "1 KiB", text, failed), config};
+};
+
+test("OCR tooltip preferences default to text only and distinguish absent text from unread results", () => {
+ const tip = createTooltip();
+ assert.equal(tip.get(), "image.png<br>PNG · 100 × 50 · 1 KiB");
+ assert.equal(tip.get(" \n "), tip.get());
+ assert.equal(tip.get(undefined, true), tip.get());
+ assert.match(tip.get("<script> & text\nline"), /OCR text:<br>&lt;script> &amp; text<br>line$/);
+ tip.config.ocr.showEmpty = true;
+ assert.match(tip.get(" \n "), /<br>No OCR text$/);
+ assert.doesNotMatch(tip.get(), /No OCR text/);
+});
+
+test("all OCR tooltip options work independently of automatic recognition and preserve saved text after failure", () => {
+ for (const auto of [false, true]) {
+ for (const showText of [false, true]) {
+ for (const showEmpty of [false, true]) {
+ for (const showError of [false, true]) {
+ const tip = createTooltip({auto, showText, showEmpty, showError});
+ assert.equal(tip.get("saved text").includes("OCR text:<br>saved text"), showText);
+ assert.equal(tip.get("").includes("No OCR text"), showEmpty);
+ assert.equal(tip.get("", true).includes("OCR recognition failed"), showError);
+ assert.equal(tip.get("saved text", true).includes("OCR text:<br>saved text"), showText);
+ assert.equal(tip.get("saved text", true).includes("OCR recognition failed"), showError);
+ assert.doesNotMatch(tip.get("", true), /No OCR text/);
+ assert.doesNotMatch(tip.get(undefined), /No OCR text|OCR recognition failed/);
+ }
+ }
+ }
+ }
+});
+
+test("OCR tooltip rendering uses the latest preferences and retains preview limits", () => {
+ const tip = createTooltip({showText: true, showEmpty: false, showError: false});
+ assert.match(tip.get("x".repeat(201)), new RegExp("x{200}\\.\\.\\.$"));
+ assert.match(tip.get("1\r\n2\r3\n4\n5\n6\n7"), /1<br>2<br>3<br>4<br>5<br>6\.\.\.$/);
+ tip.config.ocr.showText = false;
+ assert.doesNotMatch(tip.get("saved text"), /OCR text/);
+ tip.config.ocr.showError = true;
+ assert.match(tip.get("saved text", true), /OCR recognition failed$/);
+});
diff --git a/app/src/protyle/render/imageTooltip.ts b/app/src/protyle/render/imageTooltip.ts
index bf21948b43..b57e3c4ae1 100644
--- a/app/src/protyle/render/imageTooltip.ts
+++ b/app/src/protyle/render/imageTooltip.ts
@@ -20,7 +20,7 @@ const getOCRPreview = (text: string) => {
return preview;
};
-export const getImageTooltip = (image: HTMLImageElement, size?: string, ocrText?: string) => {
+export const getImageTooltip = (image: HTMLImageElement, size?: string, ocrText?: string, ocrFailed = false) => {
const source = image.getAttribute("data-src") || image.getAttribute("src") || "";
const path = source.split(/[?#]/)[0];
const inline = /^(data|blob):/.test(path);
@@ -40,11 +40,25 @@ export const getImageTooltip = (image: HTMLImageElement, size?: string, ocrText?
// 原始尺寸不受编辑器缩放和图片排版宽度影响。
const dimensions = image.naturalWidth && image.naturalHeight ? `${image.naturalWidth} × ${image.naturalHeight}` : "";
const information = [format, dimensions, size].filter(Boolean).map(value => escapeHtml(value)).join(" · ");
- const tooltip = text + (text && information ? "<br>" : "") + information;
+ let tooltip = text + (text && information ? "<br>" : "") + information;
+ const config = window.siyuan.config.ocr;
+ const append = (content: string) => {
+ tooltip += (tooltip ? "<br>" : "") + content;
+ };
+ if (ocrFailed && config?.showError) {
+ append(escapeHtml(window.siyuan.languages.ocrFailed));
+ }
const preview = ocrText === undefined ? "" : getOCRPreview(ocrText);
if (!preview) {
+ if (ocrText !== undefined && !ocrFailed && config?.showEmpty) {
+ append(escapeHtml(window.siyuan.languages.ocrNoText));
+ }
+ return tooltip;
+ }
+ if (config?.showText === false) {
return tooltip;
}
const ocr = escapeHtml(preview).replace(/\n/g, "<br>");
- return (tooltip ? tooltip + "<br>" : "") + escapeHtml(window.siyuan.languages.ocrResult) + ":<br>" + ocr;
+ append(escapeHtml(window.siyuan.languages.ocrResult) + ":<br>" + ocr);
+ return tooltip;
};
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 9ec422a1c3..3a454ec14c 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -1272,6 +1272,8 @@ export type HistoryItemsRequestInput = { "created": string; "notebook"?: string
export type HistoryPathRequestInput = { "historyPath": string; };
+export type ImageOCRTextData = { "failed": boolean; "text": string; };
+
export type ImportAutoDocument = { "token"?: string; "type": "document"; };
export type ImportAutoNotebook = { "notebook": Notebook | null; "type": "notebook"; };
@@ -2054,9 +2056,9 @@ export type SettingNotifications = { "browserCompatibility": boolean; "docTreeMa
export 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 = { "aiModelId"?: string; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string; "thresholds"?: OCRThresholds; };
+export type SettingOCR = { "aiModelId"?: string; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string; "showEmpty"?: boolean; "showError"?: boolean; "showText"?: boolean; "thresholds"?: OCRThresholds; };
-export type SettingOCRInput = { "aiModelId"?: string | null; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string | null; "thresholds"?: OCRThresholdsInput | null; };
+export type SettingOCRInput = { "aiModelId"?: string | null; "auto": boolean; "model": string; "provider": string; "reasoningEffort"?: string | null; "showEmpty"?: boolean | null; "showError"?: boolean | null; "showText"?: boolean | null; "thresholds"?: OCRThresholdsInput | null; };
export type SettingPatchData = { "issues": Array<SettingIssue> | null; };
@@ -3195,9 +3197,15 @@ export interface APIPOSTRoutes {
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated"];
};
+ /**
+ * 保留已有 text 字段;无文本、缺失 path 和加密资源返回空字符串。
+ * failed 来自实际识别失败,不由空文本推断;取消和不支持的图片不记为失败。
+ * 失败状态仅在当前内核运行期间保留最近 1024 个资源,成功识别或保存文本后清除,不写入 OCR 数据文件。
+ * 加密资源始终返回 failed=false;笔记本资源身份保留 box 参数,显示参数和片段不改变状态身份。
+ */
"/api/asset/getImageOCRText": {
request: AssetOCRTextRequestInput;
- response: { "code": 0; "data": AssetTextData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
+ response: { "code": 0; "data": ImageOCRTextData; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };
body: "json";
/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */
authorization?: readonly ["authenticated","admin","writable"];
diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.ts
index 6e739d8e1e..1029c31116 100644
--- a/app/src/types/config.d.ts
+++ b/app/src/types/config.d.ts
@@ -32,6 +32,7 @@ declare namespace Config {
* provider 为 ai 时,手动和自动识别均使用独立的 aiModelId;失效时不回退到其他模型或提供商。
* 首次从本地提供商切换到 AI 时关闭自动识别,之后可以显式开启。
* reasoningEffort 独立控制手动和自动 AI OCR,空字符串沿用模型默认。
+ * showText、showEmpty、showError 独立控制图片悬浮提示,不受自动识别开关影响,也不改变搜索结果。
*/
ocr: import("./api").SettingOCR;
api: IAPI;
diff --git a/kernel/api/asset.go b/kernel/api/asset.go
index 78c076fe6e..5f7df0bf7b 100644
--- a/kernel/api/asset.go
+++ b/kernel/api/asset.go
@@ -100,20 +100,20 @@ var fullReindexAssetContent = contractHandler(apicontract.FullReindexAssetConten
return apicontract.Success(apicontract.Null{})
})
-var getImageOCRText = contractHandler(apicontract.GetImageOCRText, func(c *gin.Context, request apicontract.AssetOCRTextRequest) apicontract.Response[apicontract.AssetTextData] {
+var getImageOCRText = contractHandler(apicontract.GetImageOCRText, func(c *gin.Context, request apicontract.AssetOCRTextRequest) apicontract.Response[apicontract.ImageOCRTextData] {
if request.Path == nil {
- return apicontract.Success(apicontract.AssetTextData{Text: ""})
+ return apicontract.Success(apicontract.ImageOCRTextData{Text: ""})
}
path := *request.Path
// 加密笔记本的资源不参与全局 OCR(OCR 文本存在全局 data/assets/ocr-texts.json)
if model.IsEncryptedOCRAsset(path) {
- return apicontract.Success(apicontract.AssetTextData{Text: ""})
+ return apicontract.Success(apicontract.ImageOCRTextData{Text: ""})
}
- return apicontract.Success(apicontract.AssetTextData{Text: util.GetAssetText(path)})
+ return apicontract.Success(apicontract.ImageOCRTextData{Text: util.GetAssetText(path), Failed: model.HasOCRFailure(path)})
})
var setImageOCRText = contractHandler(apicontract.SetImageOCRText, func(c *gin.Context, request apicontract.SetAssetOCRTextRequest) apicontract.Response[apicontract.Null] {
diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.go
index 18c93fafef..4054f57eac 100644
--- a/kernel/api/contract_ocr_test.go
+++ b/kernel/api/contract_ocr_test.go
@@ -56,9 +56,12 @@ func TestAPIContractOCREncryptedAssetAliases(t *testing.T) {
requireAPIContract(t, "POST", url, recorder)
var response struct {
Code int
- Data struct{ Text string }
+ Data struct {
+ Text string
+ Failed bool
+ }
}
- if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Data.Text != "" || (route == "ocr" && response.Code == 0) {
+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Data.Text != "" || response.Data.Failed || (route == "ocr" && response.Code == 0) {
t.Fatalf("encrypted OCR alias: %s, %v", recorder.Body.String(), err)
}
if util.GetAssetText(path) != "ordinary text" {
@@ -485,6 +488,8 @@ func TestAPIContractOCRFailurePreservesText(t *testing.T) {
t.Cleanup(func() { util.RemoveAssetText(path) })
engine := gin.New()
engine.POST("/api/asset/ocr", ocr)
+ engine.POST("/api/asset/getImageOCRText", getImageOCRText)
+ engine.POST("/api/asset/setImageOCRText", setImageOCRText)
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/ocr", strings.NewReader(`{"path":"assets/failure.png"}`)))
requireAPIContract(t, "POST", "/api/asset/ocr", recorder)
@@ -495,4 +500,19 @@ func TestAPIContractOCRFailurePreservesText(t *testing.T) {
if response.Code == 0 || util.GetAssetText(path) != "previous result" {
t.Fatalf("failed OCR replaced text: %s", recorder.Body.String())
}
+ var result apicontract.ImageOCRTextData
+ if requestOCRProvider(t, engine, "/api/asset/getImageOCRText", `{"path":"assets/failure.png#preview"}`, &result) != 0 ||
+ result.Text != "previous result" || !result.Failed {
+ t.Fatalf("recognition failure was not reported with saved text: %+v", result)
+ }
+ if requestOCRProvider(t, engine, "/api/asset/getImageOCRText", `{}`, &result) != 0 || result.Text != "" || result.Failed {
+ t.Fatalf("missing path inherited a failure: %+v", result)
+ }
+ if requestOCRProvider(t, engine, "/api/asset/setImageOCRText", `{"path":"assets/failure.png#preview","text":""}`, nil) != 0 {
+ t.Fatal("saving empty text failed")
+ }
+ if requestOCRProvider(t, engine, "/api/asset/getImageOCRText", `{"path":"assets/failure.png"}`, &result) != 0 ||
+ result.Text != "" || result.Failed {
+ t.Fatalf("empty saved text retained a recognition failure: %+v", result)
+ }
}
diff --git a/kernel/api/contract_ocr_tooltip_test.go b/kernel/api/contract_ocr_tooltip_test.go
new file mode 100644
index 0000000000..9b804c1a55
--- /dev/null
+++ b/kernel/api/contract_ocr_tooltip_test.go
@@ -0,0 +1,63 @@
+package api
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestAPIContractOCRTooltipPreferences(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/getOCRConfig", getOCRConfig)
+ engine.POST("/api/asset/setOCRConfig", setOCRConfig)
+ engine.POST("/api/setting/patch", patchSetting)
+ var initial apicontract.OCRConfigData
+ if requestOCRProvider(t, engine, "/api/asset/getOCRConfig", `{}`, &initial) != 0 ||
+ initial.Config.ShowText == nil || !*initial.Config.ShowText ||
+ initial.Config.ShowEmpty == nil || *initial.Config.ShowEmpty ||
+ initial.Config.ShowError == nil || *initial.Config.ShowError {
+ t.Fatalf("tooltip defaults: %+v", initial.Config)
+ }
+ const path = "assets/tooltip-preferences.png"
+ util.SetAssetText(path, "preserved text")
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ for _, body := range []string{
+ `{"provider":"tesseract","model":"tiny","auto":false,"showText":false,"showEmpty":true,"showError":true}`,
+ `{"provider":"tesseract","model":"tiny","auto":true}`,
+ `{"provider":"tesseract","model":"tiny","auto":false,"showText":null,"showEmpty":null,"showError":null}`,
+ } {
+ var response apicontract.SettingOCR
+ if requestOCRProvider(t, engine, "/api/asset/setOCRConfig", body, &response) != 0 ||
+ response.ShowText == nil || *response.ShowText || response.ShowEmpty == nil || !*response.ShowEmpty ||
+ response.ShowError == nil || !*response.ShowError {
+ t.Fatalf("tooltip setting compatibility: %s: %+v", body, response)
+ }
+ if util.GetAssetText(path) != "preserved text" {
+ t.Fatal("tooltip settings changed saved text")
+ }
+ data, err := os.ReadFile(filepath.Join(util.ConfDir, "conf.json"))
+ var saved struct{ OCR conf.OCR }
+ if err != nil || json.Unmarshal(data, &saved) != nil || saved.OCR.ShowText == nil ||
+ *saved.OCR.ShowText || !saved.OCR.ShowEmpty || !saved.OCR.ShowError {
+ t.Fatalf("tooltip preferences were not persisted: %+v, %v", saved.OCR, err)
+ }
+ }
+ if requestOCRProvider(t, engine, "/api/setting/patch", `{"ocr":{"showText":true,"showEmpty":false}}`, nil) != 0 {
+ t.Fatal("tooltip preferences could not be patched")
+ }
+ value := model.Conf.GetOCR()
+ if value.ShowText == nil || !*value.ShowText || value.ShowEmpty || !value.ShowError || value.Auto {
+ t.Fatalf("partial patch changed independent fields: %+v", value)
+ }
+}
diff --git a/kernel/api/ocr.go b/kernel/api/ocr.go
index d7a392968e..f7ceabc09c 100644
--- a/kernel/api/ocr.go
+++ b/kernel/api/ocr.go
@@ -43,8 +43,11 @@ var getOCRConfig = contractHandler(apicontract.GetOCRConfig, func(c *gin.Context
})
func ocrConfigPayload(value conf.OCR) apicontract.SettingOCR {
+ if value.ShowText == nil {
+ value.ShowText = new(true)
+ }
thresholds := apicontract.OCRThresholds(value.Thresholds)
- return apicontract.SettingOCR{Provider: value.Provider, Model: value.Model, Auto: value.Auto, Thresholds: &thresholds, AIModelID: &value.AIModelID, ReasoningEffort: &value.ReasoningEffort}
+ return apicontract.SettingOCR{Provider: value.Provider, Model: value.Model, Auto: value.Auto, Thresholds: &thresholds, AIModelID: &value.AIModelID, ReasoningEffort: &value.ReasoningEffort, ShowText: value.ShowText, ShowEmpty: &value.ShowEmpty, ShowError: &value.ShowError}
}
func ocrModelPayload(id string) apicontract.OCRModel {
@@ -62,6 +65,15 @@ var setOCRConfig = contractHandler(apicontract.SetOCRConfig, applyOCRSetting)
func applyOCRSetting(c *gin.Context, request apicontract.SettingOCR) apicontract.Response[apicontract.SettingOCR] {
value := model.Conf.GetOCR()
value.Provider, value.Model, value.Auto = request.Provider, request.Model, request.Auto
+ if request.ShowText != nil {
+ value.ShowText = request.ShowText
+ }
+ if request.ShowEmpty != nil {
+ value.ShowEmpty = *request.ShowEmpty
+ }
+ if request.ShowError != nil {
+ value.ShowError = *request.ShowError
+ }
if request.AIModelID != nil {
value.AIModelID = *request.AIModelID
}
diff --git a/kernel/apicontract/asset.go b/kernel/apicontract/asset.go
index 86e8cd9fa8..c025b55553 100644
--- a/kernel/apicontract/asset.go
+++ b/kernel/apicontract/asset.go
@@ -88,6 +88,11 @@ type AssetTextData struct {
Text string `json:"text"`
}
+type ImageOCRTextData struct {
+ Text string `json:"text"`
+ Failed bool `json:"failed"`
+}
+
// AssetOCRData 的列名沿用 Tesseract TSV 表头,所有提供商的单元格均为文本。
// AI 提供商仅返回原样 text,ocrJSON 为空数组,不生成坐标或置信度。
type AssetOCRData struct {
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index 27adcd7b64..71cec0fa8b 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -1026,7 +1026,12 @@ var ExportReStructuredText = define[ExportIDRequest, ExportNamedZipData]("export
var StatAsset = define[AssetPathRequest, AssetStatData]("statAsset", "/api/asset/statAsset", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{AdditionalCodes: []int{1}}, "POST")
var FullReindexAssetContent = define[EmptyRequest, Null]("fullReindexAssetContent", "/api/asset/fullReindexAssetContent", AuthenticatedAccess|AdminAccess|WritableAccess, NoBody, ResponseOptions{}, "POST")
-var GetImageOCRText = define[AssetOCRTextRequest, AssetTextData]("getImageOCRText", "/api/asset/getImageOCRText", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
+
+// GetImageOCRText 保留已有 text 字段;无文本、缺失 path 和加密资源返回空字符串。
+// failed 来自实际识别失败,不由空文本推断;取消和不支持的图片不记为失败。
+// 失败状态仅在当前内核运行期间保留最近 1024 个资源,成功识别或保存文本后清除,不写入 OCR 数据文件。
+// 加密资源始终返回 failed=false;笔记本资源身份保留 box 参数,显示参数和片段不改变状态身份。
+var GetImageOCRText = define[AssetOCRTextRequest, ImageOCRTextData]("getImageOCRText", "/api/asset/getImageOCRText", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
var SetImageOCRText = define[SetAssetOCRTextRequest, Null]("setImageOCRText", "/api/asset/setImageOCRText", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")
// AssetOCR 始终使用当前设备选择的提供商,内核可在无界面的环境中识别。
diff --git a/kernel/apicontract/ocr.go b/kernel/apicontract/ocr.go
index e00ad6a4f6..203c72115a 100644
--- a/kernel/apicontract/ocr.go
+++ b/kernel/apicontract/ocr.go
@@ -4,6 +4,8 @@ import "mime/multipart"
// SettingOCR 的选择仅保存在当前设备;切换提供商或模型不删除、重跑已有识别结果。
// auto 仅控制内核后台识别,手动识别继续使用 /api/asset/ocr 的既有输入和输出。
+// showText、showEmpty、showError 独立控制图片悬浮提示,不受 auto 影响,也不改变已有结果和搜索索引。
+// 三项省略或为 null 时保留已有选择;缺失设备配置默认开启文本预览,关闭无文本和失败提示。
// thresholds 省略或为 null 时保留设备已保存的阈值;传入对象时整体替换。
// 修改阈值只影响后续识别,不修改模型文件或已有结果,Tesseract 不使用这些参数。
// 仅内置 tiny;旧内置模型标识 small 会归一化为 tiny,自行导入的模型仍使用内容摘要标识。
@@ -16,6 +18,9 @@ type SettingOCR struct {
Provider string `json:"provider"`
Model string `json:"model"`
Auto bool `json:"auto"`
+ ShowText *bool `json:"showText,omitempty" api:"optional"`
+ ShowEmpty *bool `json:"showEmpty,omitempty" api:"optional"`
+ ShowError *bool `json:"showError,omitempty" api:"optional"`
AIModelID *string `json:"aiModelId,omitempty" api:"optional"`
ReasoningEffort *string `json:"reasoningEffort,omitempty" api:"optional"`
Thresholds *OCRThresholds `json:"thresholds,omitempty" api:"optional"`
diff --git a/kernel/apicontract/ocr_test.go b/kernel/apicontract/ocr_test.go
index 37ef2ce3e4..de9eab2680 100644
--- a/kernel/apicontract/ocr_test.go
+++ b/kernel/apicontract/ocr_test.go
@@ -46,3 +46,20 @@ func TestOCRAIModelCompatibility(t *testing.T) {
t.Fatal("accepted numeric model ID")
}
}
+
+func TestOCRTooltipSettingContract(t *testing.T) {
+ for _, key := range []string{"showText", "showEmpty", "showError"} {
+ for _, value := range []string{"true", "false", "null"} {
+ body := `{"provider":"paddleocr","model":"tiny","auto":false,"` + key + `":` + value + `}`
+ if _, err := SetOCRConfig.Decode(strings.NewReader(body)); err != nil {
+ t.Fatalf("rejected tooltip preference %s: %v", body, err)
+ }
+ }
+ for _, value := range []string{`"false"`, "1", "{}"} {
+ body := `{"provider":"paddleocr","model":"tiny","auto":false,"` + key + `":` + value + `}`
+ if _, err := SetOCRConfig.Decode(strings.NewReader(body)); err == nil {
+ t.Fatalf("accepted malformed tooltip preference: %s", body)
+ }
+ }
+ }
+}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 049eb55cef..be0b445ab8 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -28908,6 +28908,22 @@
],
"additionalProperties": false
},
+ "ImageOCRTextData": {
+ "type": "object",
+ "properties": {
+ "failed": {
+ "type": "boolean"
+ },
+ "text": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "failed",
+ "text"
+ ],
+ "additionalProperties": false
+ },
"ImportAutoDocument": {
"type": "object",
"properties": {
@@ -47345,6 +47361,15 @@
"reasoningEffort": {
"type": "string"
},
+ "showEmpty": {
+ "type": "boolean"
+ },
+ "showError": {
+ "type": "boolean"
+ },
+ "showText": {
+ "type": "boolean"
+ },
"thresholds": {
"$ref": "#/$defs/OCRThresholds"
}
@@ -47388,6 +47413,36 @@
}
]
},
+ "showEmpty": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "showError": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "showText": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
"thresholds": {
"anyOf": [
{
@@ -123548,7 +123603,7 @@
]
},
"data": {
- "$ref": "#/$defs/AssetTextData"
+ "$ref": "#/$defs/ImageOCRTextData"
},
"msg": {
"type": "string"
diff --git a/kernel/conf/ocr.go b/kernel/conf/ocr.go
index 6d3a1dac08..71c3a66b47 100644
--- a/kernel/conf/ocr.go
+++ b/kernel/conf/ocr.go
@@ -7,6 +7,9 @@ type OCR struct {
AIModelID string `json:"aiModelId"`
ReasoningEffort string `json:"reasoningEffort"`
Auto bool `json:"auto"`
+ ShowText *bool `json:"showText"`
+ ShowEmpty bool `json:"showEmpty"`
+ ShowError bool `json:"showError"`
Thresholds OCRThresholds `json:"thresholds"`
}
@@ -18,5 +21,5 @@ type OCRThresholds struct {
}
func NewOCR() *OCR {
- return &OCR{Provider: "paddleocr", Model: "tiny", Auto: false}
+ return &OCR{Provider: "paddleocr", Model: "tiny", Auto: false, ShowText: new(true)}
}
diff --git a/kernel/conf/ocr_test.go b/kernel/conf/ocr_test.go
index 4960ab4ba1..8c692583e7 100644
--- a/kernel/conf/ocr_test.go
+++ b/kernel/conf/ocr_test.go
@@ -3,7 +3,19 @@ package conf
import "testing"
func TestOCRDeviceDefaults(t *testing.T) {
- if config := NewOCR(); config.Provider != "paddleocr" || config.Model != "tiny" || config.Auto {
+ if config := NewOCR(); config.Provider != "paddleocr" || config.Model != "tiny" || config.Auto ||
+ config.ShowText == nil || !*config.ShowText || config.ShowEmpty || config.ShowError {
t.Fatalf("device defaults: %+v", config)
}
}
+
+func TestOCRTooltipNormalization(t *testing.T) {
+ legacy := NormalizeOCR(&OCR{Provider: "tesseract", Model: "tiny", Auto: true})
+ if legacy.ShowText == nil || !*legacy.ShowText || legacy.ShowEmpty || legacy.ShowError || !legacy.Auto {
+ t.Fatalf("legacy defaults: %+v", legacy)
+ }
+ saved := NormalizeOCR(&OCR{ShowText: new(false), ShowEmpty: true, ShowError: true})
+ if *saved.ShowText || !saved.ShowEmpty || !saved.ShowError {
+ t.Fatalf("saved tooltip preferences: %+v", saved)
+ }
+}
diff --git a/kernel/conf/settings_normalize.go b/kernel/conf/settings_normalize.go
index c0cffc8b72..3a539c1dd0 100644
--- a/kernel/conf/settings_normalize.go
+++ b/kernel/conf/settings_normalize.go
@@ -365,6 +365,9 @@ func NormalizeOCR(ocr *OCR) *OCR {
if ocr == nil {
ocr = NewOCR()
}
+ if ocr.ShowText == nil {
+ ocr.ShowText = new(true)
+ }
if "small" == ocr.Model {
// 内置模型统一为 Tiny,自行导入的模型仍保留内容摘要标识。
ocr.Model = "tiny"
diff --git a/kernel/model/ocr.go b/kernel/model/ocr.go
index 92a45810e0..9c17c07ba5 100644
--- a/kernel/model/ocr.go
+++ b/kernel/model/ocr.go
@@ -171,7 +171,14 @@ func OCRAsset(ctx context.Context, path string) (string, []map[string]string, er
return ocrAsset(ctx, path, Conf.GetOCR(), false)
}
-func ocrAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (string, []map[string]string, error) {
+func ocrAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (_ string, _ []map[string]string, resultErr error) {
+ if value.Provider != "ai" {
+ defer func() {
+ if !automatic || automaticOCRMatches(value) {
+ recordOCRFailure(path, resultErr)
+ }
+ }()
+ }
if value.Provider == "ai" {
text, err := aiOCRAsset(ctx, path, value, automatic)
return text, []map[string]string{}, err
@@ -221,6 +228,7 @@ func SetOCRAssetText(path, text string) {
}
path = util.OCRAssetKey(path)
util.SetAssetText(path, text)
+ clearOCRFailure(path)
documents, err := sql.QueryOCRAssetDocuments(path)
if err != nil {
logging.LogErrorf("query OCR asset documents failed: %s", err)
diff --git a/kernel/model/ocr_ai.go b/kernel/model/ocr_ai.go
index 513ab91dc4..31a348eb57 100644
--- a/kernel/model/ocr_ai.go
+++ b/kernel/model/ocr_ai.go
@@ -28,7 +28,12 @@ func AIOCRAsset(ctx context.Context, path string) (string, error) {
return aiOCRAsset(ctx, path, Conf.GetOCR(), false)
}
-func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (string, error) {
+func aiOCRAsset(ctx context.Context, path string, value conf.OCR, automatic bool) (_ string, resultErr error) {
+ defer func() {
+ if !automatic || automaticOCRMatches(value) {
+ recordOCRFailure(path, resultErr)
+ }
+ }()
confAISnapshot := Conf.LoadAI()
if util.IsDisabledFeature("ai") {
diff --git a/kernel/model/ocr_ai_index_test.go b/kernel/model/ocr_ai_index_test.go
index 5d4b85fa5c..02789ef580 100644
--- a/kernel/model/ocr_ai_index_test.go
+++ b/kernel/model/ocr_ai_index_test.go
@@ -101,6 +101,9 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {
if !errors.Is(err, context.Canceled) || util.GetAssetText(path) != test.want {
t.Fatalf("in-flight automatic response replaced text: %v, %q", err, util.GetAssetText(path))
}
+ if HasOCRFailure(path) {
+ t.Fatal("canceled automatic recognition was reported as failure")
+ }
})
}
beforeResponse = nil
@@ -147,6 +150,9 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {
Conf.OCR.Load().AIModelID = "vision"
providerFailure = true
autoOCRAssets()
+ if !HasOCRFailure(extra) {
+ t.Fatal("automatic AI provider failure was not recorded")
+ }
providerFailure = false
autoOCRAssets()
if calls != previousCalls+3 || util.ExistsAssetText(extra) {
@@ -157,6 +163,9 @@ func testAIOCRAssetIndex(t *testing.T, path, blockID string) {
if calls != previousCalls+4 || !util.ExistsAssetText(extra) {
t.Fatal("changed reasoning effort inherited the previous retry delay")
}
+ if HasOCRFailure(extra) {
+ t.Fatal("successful automatic AI recognition did not clear the failure")
+ }
if err = os.Remove(filepath.Join(util.DataDir, filepath.FromSlash(extra))); err != nil {
t.Fatal(err)
}
diff --git a/kernel/model/ocr_conf_test.go b/kernel/model/ocr_conf_test.go
index 77d12aeba0..cee45343c3 100644
--- a/kernel/model/ocr_conf_test.go
+++ b/kernel/model/ocr_conf_test.go
@@ -2,6 +2,7 @@ package model
import (
"encoding/json"
+ "reflect"
"testing"
"github.com/siyuan-note/siyuan/kernel/conf"
@@ -15,14 +16,15 @@ func TestOCRSmallMigrationPreservesPreferences(t *testing.T) {
t.Fatal(err)
}
original := value
+ original.ShowText = new(true)
if original.Model == "small" {
original.Model = "tiny"
}
got := normalizeOCRConfig(&value, true)
- if *got != original {
+ if !reflect.DeepEqual(*got, original) {
t.Fatalf("migration changed preferences: %+v", got)
}
- if again := normalizeOCRConfig(got, true); *again != original {
+ if again := normalizeOCRConfig(got, true); !reflect.DeepEqual(*again, original) {
t.Fatal("migration is not idempotent")
}
}
@@ -58,8 +60,9 @@ func TestNormalizeOCRConfig(t *testing.T) {
},
} {
t.Run(test.name, func(t *testing.T) {
+ test.want.ShowText = new(true)
got := normalizeOCRConfig(test.value, test.confFileExists)
- if *got != test.want {
+ if !reflect.DeepEqual(*got, test.want) {
t.Fatalf("OCR config: got %+v, want %+v", *got, test.want)
}
if test.value != nil && got != test.value {
diff --git a/kernel/model/ocr_index_test.go b/kernel/model/ocr_index_test.go
index d2827b5cbe..0064e4f468 100644
--- a/kernel/model/ocr_index_test.go
+++ b/kernel/model/ocr_index_test.go
@@ -125,6 +125,13 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {
if util.GetAssetText(path) != "editedocrkeyword" {
t.Fatal("failed recognition changed saved text")
}
+ if !HasOCRFailure(path + "#preview") {
+ t.Fatal("local provider failure was not recorded")
+ }
+ SetOCRAssetText(path, "editedocrkeyword")
+ if HasOCRFailure(path) {
+ t.Fatal("saving OCR text did not clear the failure")
+ }
provider.called = false
const notebookPath = "assets/notebook-image.png"
notebookImage := filepath.Join(util.DataDir, fixture.box.ID, filepath.FromSlash(notebookPath))
diff --git a/kernel/model/ocr_status.go b/kernel/model/ocr_status.go
new file mode 100644
index 0000000000..bcd35d2d92
--- /dev/null
+++ b/kernel/model/ocr_status.go
@@ -0,0 +1,57 @@
+package model
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/ocr"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const ocrFailureLimit = 1024
+
+var ocrFailures = struct {
+ sync.Mutex
+ paths map[string]time.Time
+}{paths: map[string]time.Time{}}
+
+// 失败提示只记录实际尝试的普通本地资源,不保存错误详情,也不写入同步数据。
+func recordOCRFailure(path string, err error) {
+ if err == nil || errors.Is(err, context.Canceled) || errors.Is(err, ocr.ErrUnsupportedImage) {
+ return
+ }
+ path = util.OCRAssetKey(strings.TrimSpace(path))
+ if !strings.HasPrefix(path, "assets/") || IsEncryptedOCRAsset(path) {
+ return
+ }
+ ocrFailures.Lock()
+ defer ocrFailures.Unlock()
+ if _, exists := ocrFailures.paths[path]; !exists && len(ocrFailures.paths) >= ocrFailureLimit {
+ oldest := ""
+ var oldestTime time.Time
+ for key, updated := range ocrFailures.paths {
+ if oldest == "" || updated.Before(oldestTime) {
+ oldest, oldestTime = key, updated
+ }
+ }
+ delete(ocrFailures.paths, oldest)
+ }
+ ocrFailures.paths[path] = time.Now()
+}
+
+// HasOCRFailure 查询当前内核运行期间的识别失败;笔记本身份与 OCR 文本使用相同规范键。
+func HasOCRFailure(path string) bool {
+ ocrFailures.Lock()
+ defer ocrFailures.Unlock()
+ _, failed := ocrFailures.paths[util.OCRAssetKey(path)]
+ return failed
+}
+
+func clearOCRFailure(path string) {
+ ocrFailures.Lock()
+ defer ocrFailures.Unlock()
+ delete(ocrFailures.paths, util.OCRAssetKey(path))
+}
diff --git a/kernel/model/ocr_status_test.go b/kernel/model/ocr_status_test.go
new file mode 100644
index 0000000000..c10459ea91
--- /dev/null
+++ b/kernel/model/ocr_status_test.go
@@ -0,0 +1,72 @@
+package model
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/ocr"
+)
+
+func TestOCRFailureStatus(t *testing.T) {
+ setupAssetUploadTest(t)
+ Conf.FileTree.Store(conf.NewFileTree())
+ const path = "assets/ocr-status-fixture.png"
+ for _, suffix := range []string{"", "?box=20261001021001-abcdefg", "?box=20261001021002-abcdefg"} {
+ t.Cleanup(func() { clearOCRFailure(path + suffix) })
+ }
+ recordOCRFailure(path+"#preview", errors.New("inference failed"))
+ if !HasOCRFailure(path) || !HasOCRFailure(path+"?width=100#preview") {
+ t.Fatal("display parameters changed failure identity")
+ }
+ firstBox := path + "?box=20261001021001-abcdefg"
+ secondBox := path + "?box=20261001021002-abcdefg"
+ if HasOCRFailure(firstBox) || HasOCRFailure(secondBox) {
+ t.Fatal("global failure leaked into notebook-scoped resources")
+ }
+ recordOCRFailure(firstBox, errors.New("inference failed"))
+ if !HasOCRFailure(firstBox+"&width=100#preview") || HasOCRFailure(secondBox) {
+ t.Fatal("notebook failure identity was not isolated")
+ }
+ clearOCRFailure(firstBox)
+ if HasOCRFailure(firstBox) || !HasOCRFailure(path) {
+ t.Fatal("clearing one resource changed another failure")
+ }
+ for _, err := range []error{nil, context.Canceled, fmt.Errorf("wrapped: %w", context.Canceled), ocr.ErrUnsupportedImage} {
+ recordOCRFailure(secondBox, err)
+ if HasOCRFailure(secondBox) {
+ t.Fatalf("non-failure recorded: %v", err)
+ }
+ }
+ recordOCRFailure("https://example.com/image.png", errors.New("not local"))
+ if HasOCRFailure("https://example.com/image.png") {
+ t.Fatal("external resource was recorded")
+ }
+}
+
+func TestOCRFailureStatusBounded(t *testing.T) {
+ setupAssetUploadTest(t)
+ Conf.FileTree.Store(conf.NewFileTree())
+ ocrFailures.Lock()
+ previous := ocrFailures.paths
+ ocrFailures.paths = map[string]time.Time{}
+ ocrFailures.Unlock()
+ t.Cleanup(func() {
+ ocrFailures.Lock()
+ ocrFailures.paths = previous
+ ocrFailures.Unlock()
+ })
+ for i := range ocrFailureLimit + 1 {
+ recordOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", i), errors.New("inference failed"))
+ }
+ ocrFailures.Lock()
+ count := len(ocrFailures.paths)
+ ocrFailures.Unlock()
+ if count != ocrFailureLimit || HasOCRFailure("assets/ocr-status-0000.png") ||
+ !HasOCRFailure(fmt.Sprintf("assets/ocr-status-%04d.png", ocrFailureLimit)) {
+ t.Fatalf("failure cache limit: %d", count)
+ }
+}