Skip to content

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

:bug: Align image AI OCR availability and formats https://github.com/siyuan-note/siyuan/issues/20082

Daniel5443e7b2f00f
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 52ca65baaa..51d5a7c72d 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": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -967,7 +967,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003636-epvk98g",
- "updated": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1364,7 +1364,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202934-1h96or8",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1536,7 +1536,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003224949-gtf3qng",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1559,7 +1559,7 @@
},
{
"Type": "NodeText",
- "Data": ", which sends the local image to the configured agent model for text recognition. The model must support image input. AI OCR runs only when requested and shares the existing OCR text, editing, copying, and search index. Failed recognition preserves the previous result. Encrypted notebook images are not supported."
+ "Data": ", which sends the local image to the configured agent model for text recognition. The model must support image input. AI OCR runs only when requested and shares the existing OCR text, editing, copying, and search index. Failed recognition preserves the previous result. Encrypted notebook images are not supported. PNG, JPEG, GIF, and WebP are supported directly; BMP and TIFF are converted to PNG, and HEIC/HEIF to JPEG without reducing resolution. The original and converted images must each be within 20 MiB, and the converted image within 40 million pixels. Recognition actions are hidden for network images, and the OCR menu is hidden for encrypted notebook images. Unsupported formats such as AVIF, SVG, and ICO do not show the AI OCR action."
}
]
}
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 594651c42d..d713308403 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": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -979,7 +979,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117002036-vmc0mx4",
- "updated": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1372,7 +1372,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414202710-a51lo76",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1544,7 +1544,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003224949-weus2iw",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1567,7 +1567,7 @@
},
{
"Type": "NodeText",
- "Data": ",将本地图片发送给已配置的智能体模型进行文字识别,模型须支持图片输入。AI OCR 仅手动执行,结果复用现有 OCR 文本、编辑、复制和搜索索引;识别失败时保留原结果。加密笔记本图片不支持此功能。"
+ "Data": ",将本地图片发送给已配置的智能体模型进行文字识别,模型须支持图片输入。AI OCR 仅手动执行,结果复用现有 OCR 文本、编辑、复制和搜索索引;识别失败时保留原结果。加密笔记本图片不支持此功能。支持 PNG、JPEG、GIF 和 WebP;BMP、TIFF 转为 PNG,HEIC/HEIF 转为 JPEG,保留原图分辨率。原始图片和转换后的图片均不得超过 20 MiB,转换后的图片不得超过四千万像素。网络图片隐藏识别入口,加密笔记本图片隐藏 OCR 菜单;AVIF、SVG、ICO 等不支持的格式隐藏 AI 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 1ffdd52d48..e91ff8ea3a 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": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -965,7 +965,7 @@
"HeadingLevel": 2,
"Properties": {
"id": "20230117003901-ze4mbzz",
- "updated": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1358,7 +1358,7 @@
"HeadingLevel": 3,
"Properties": {
"id": "20230414203058-foirrwk",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1530,7 +1530,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003224949-qe1gsny",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1553,7 +1553,7 @@
},
{
"Type": "NodeText",
- "Data": ",將本機圖片傳送給已設定的智能體模型進行文字辨識,模型須支援圖片輸入。AI OCR 僅手動執行,結果沿用現有 OCR 文字、編輯、複製與搜尋索引;辨識失敗時保留原結果。加密筆記本圖片不支援此功能。"
+ "Data": ",將本機圖片傳送給已設定的智能體模型進行文字辨識,模型須支援圖片輸入。AI OCR 僅手動執行,結果沿用現有 OCR 文字、編輯、複製與搜尋索引;辨識失敗時保留原結果。加密筆記本圖片不支援此功能。支援 PNG、JPEG、GIF 和 WebP;BMP、TIFF 轉為 PNG,HEIC/HEIF 轉為 JPEG,保留原圖解析度。原始圖片和轉換後的圖片均不得超過 20 MiB,轉換後的圖片不得超過四千萬像素。網路圖片隱藏辨識入口,加密筆記本圖片隱藏 OCR 選單;AVIF、SVG、ICO 等不支援的格式隱藏 AI 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 81ef0aacaf..1169cc027a 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": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1005,7 +1005,7 @@
"Properties": {
"ID": "20240530101000-5bix8t1",
"id": "20240530101000-9evyuhr",
- "updated": "20261003234011"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1407,7 +1407,7 @@
"Properties": {
"ID": "20240530101000-aefldsk",
"id": "20240530101000-cpod2qy",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1594,7 +1594,7 @@
"Type": "NodeParagraph",
"Properties": {
"id": "20261003224949-qenn1ez",
- "updated": "20261003224949"
+ "updated": "20261004005806"
},
"Children": [
{
@@ -1617,7 +1617,7 @@
},
{
"Type": "NodeText",
- "Data": " を選択すると、ローカル画像を設定済みのエージェントモデルに送信して文字を認識します。画像入力に対応したモデルが必要です。AI OCR は手動でのみ実行され、既存の OCR テキスト、編集、コピー、検索インデックスを利用します。認識に失敗した場合は元の結果を保持します。暗号化ノートブックの画像には対応していません。"
+ "Data": " を選択すると、ローカル画像を設定済みのエージェントモデルに送信して文字を認識します。画像入力に対応したモデルが必要です。AI OCR は手動でのみ実行され、既存の OCR テキスト、編集、コピー、検索インデックスを利用します。認識に失敗した場合は元の結果を保持します。暗号化ノートブックの画像には対応していません。PNG、JPEG、GIF、WebP に対応しています。BMP と TIFF は PNG に、HEIC/HEIF は JPEG に変換し、元の解像度を保持します。元画像と変換後の画像はそれぞれ 20 MiB 以下、変換後の画像は 4,000 万画素以下である必要があります。ネットワーク画像では認識項目を、暗号化ノートブックの画像では OCR メニューを非表示にします。AVIF、SVG、ICO などの未対応形式では AI OCR 項目を表示しません。"
}
]
}
diff --git a/app/src/asset/imageOCRAvailability.test.ts b/app/src/asset/imageOCRAvailability.test.ts
new file mode 100644
index 0000000000..8b6cd01c6f
--- /dev/null
+++ b/app/src/asset/imageOCRAvailability.test.ts
@@ -0,0 +1,57 @@
+import * as assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+import test from "node:test";
+import {ScriptTarget, transpileModule} from "typescript";
+
+const source = transpileModule(readFileSync("src/asset/imageOCRAvailability.ts", "utf8")
+ .replace(/^import .*;\r?\n/gm, "").replace(/^export /gm, ""), {
+ compilerOptions: {target: ScriptTarget.ES2020},
+}).outputText;
+const availability = new Function("isEncryptedBox", source + "\nreturn getImageOCRAvailability;")(
+ (id: string) => id === "encrypted",
+);
+
+test("OCR recognition requires local unencrypted assets, including scoped notebook sources", () => {
+ for (const path of ["assets/image.png", "assets/image.PNG?box=ordinary&style=thumb#preview"]) {
+ assert.deepEqual(availability(path, "ordinary"), {text: true, local: true, ai: true});
+ }
+ for (const path of ["https://example.com/image.png", "file:///image.png", "data:image/png;base64,AA", "", null]) {
+ assert.deepEqual(availability(path, "ordinary"), {text: true, local: false, ai: false});
+ }
+ for (const [path, notebookId] of [
+ ["assets/image.png", "encrypted"],
+ ["assets/image.png?style=thumb&box=encrypted#preview", "ordinary"],
+ ["assets/image.png?box=%65ncrypted", "ordinary"],
+ ]) {
+ assert.deepEqual(availability(path, notebookId), {text: false, local: false, ai: false});
+ }
+});
+
+test("AI OCR advertises only native or convertible image formats", () => {
+ for (const extension of ["png", "jpg", "jpeg", "gif", "webp", "bmp", "tif", "tiff", "heic", "heif"]) {
+ assert.equal(availability(`assets/image.${extension.toUpperCase()}?box=ordinary#preview`, "ordinary").ai, true);
+ }
+ for (const extension of ["svg", "avif", "ico", "pdf", "png.exe"]) {
+ assert.deepEqual(availability(`assets/image.${extension}`, "ordinary"), {text: true, local: true, ai: false});
+ }
+});
+
+test("shared image menus hide unavailable recognition and its separator while retaining text actions", () => {
+ const menuSource = readFileSync("src/menus/protyle.ts", "utf8");
+ const idPosition = menuSource.indexOf('id: "ocr",', menuSource.indexOf("export const imgMenu"));
+ const start = menuSource.lastIndexOf("new MenuItem(", idPosition) + "new MenuItem(".length;
+ const end = menuSource.indexOf("}).element);", start) + 1;
+ const getMenu = new Function("window", "ocrAvailability", "isDisabledFeature",
+ `return (${menuSource.slice(start, end)});`);
+ const visibleItems = (path: string, notebookId: string, disabled = false) => {
+ const menu = getMenu({siyuan: {languages: {}}}, availability(path, notebookId), () => disabled);
+ return menu.ignore ? [] : menu.submenu.filter((item: {ignore?: boolean}) => !item.ignore)
+ .map((item: {id: string}) => item.id);
+ };
+ assert.deepEqual(visibleItems("https://example.com/image.png", "ordinary"), ["ocrResult", "copyOCRText"]);
+ assert.deepEqual(visibleItems("assets/image.png?box=encrypted", "ordinary"), []);
+ assert.deepEqual(visibleItems("assets/image.png", "encrypted"), []);
+ assert.deepEqual(visibleItems("assets/image.svg", "ordinary"), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR"]);
+ assert.deepEqual(visibleItems("assets/image.heic", "ordinary"), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR", "reAIOCR"]);
+ assert.deepEqual(visibleItems("assets/image.png", "ordinary", true), ["ocrResult", "copyOCRText", "separator_reOCR", "reOCR"]);
+});
diff --git a/app/src/asset/imageOCRAvailability.ts b/app/src/asset/imageOCRAvailability.ts
new file mode 100644
index 0000000000..9413ff7d60
--- /dev/null
+++ b/app/src/asset/imageOCRAvailability.ts
@@ -0,0 +1,11 @@
+import {isEncryptedBox} from "../util/pathName";
+
+export const getImageOCRAvailability = (path: string, notebookId: string) => {
+ const reference = (path || "").split("#", 1)[0];
+ const [pathname, query = ""] = reference.split("?", 2);
+ const boxId = new URLSearchParams(query).get("box")?.trim();
+ const text = !isEncryptedBox(notebookId) && !isEncryptedBox(boxId);
+ const local = text && pathname.startsWith("assets/");
+ const ai = local && /\.(png|jpe?g|gif|webp|bmp|tiff?|heic|heif)$/i.test(pathname);
+ return {text, local, ai};
+};
diff --git a/app/src/menus/protyle.ts b/app/src/menus/protyle.ts
index b0f7e5ea1a..d1acfb0c37 100644
--- a/app/src/menus/protyle.ts
+++ b/app/src/menus/protyle.ts
@@ -88,6 +88,7 @@ import {getZoomFocusScrollAttr, shouldFocusAfterZoom} from "../protyle/util/focu
import {scrollCenter} from "../util/highlightById";
import {copyImageOCRText, openImageOCR} from "../asset/imageOCR";
import {reImageAIOCR} from "../asset/imageAIOCR";
+import {getImageOCRAvailability} from "../asset/imageOCRAvailability";
import {
getSemanticInlineVisibleText,
normalizeSemanticInlineElement,
@@ -1366,6 +1367,7 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
}).element);
window.siyuan.menus.menu.append(new MenuItem({id: "separator_2", type: "separator"}).element);
const imagePath = imgElement.getAttribute("data-src");
+ const ocrAvailability = getImageOCRAvailability(imagePath, protyle.notebookId);
if (imagePath.startsWith("assets/")) {
window.siyuan.menus.menu.append(new MenuItem({
id: "rename",
@@ -1379,6 +1381,7 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
window.siyuan.menus.menu.append(new MenuItem({
id: "ocr",
label: "OCR",
+ ignore: !ocrAvailability.text,
submenu: [{
id: "ocrResult",
icon: "iconEdit",
@@ -1395,15 +1398,17 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
}
}, {
id: "separator_reOCR",
- type: "separator"
+ type: "separator",
+ ignore: !ocrAvailability.local,
}, {
id: "reOCR",
iconHTML: "",
label: window.siyuan.languages.reOCR,
+ ignore: !ocrAvailability.local,
click() {
const path = imgElement.getAttribute("data-src");
fetchPost("/api/asset/ocr", {
- path: imgElement.getAttribute("src"),
+ path,
}, () => {
invalidateImageOCRStatus(path);
});
@@ -1412,7 +1417,7 @@ export const imgMenu = (protyle: IProtyle, range: Range, assetElement: HTMLEleme
id: "reAIOCR",
icon: "iconSparkles",
label: window.siyuan.languages.reAIOCR,
- ignore: isDisabledFeature("ai"),
+ ignore: isDisabledFeature("ai") || !ocrAvailability.ai,
click() {
void reImageAIOCR(imgElement.getAttribute("data-src"));
}
diff --git a/kernel/api/contract_ocr_ai_test.go b/kernel/api/contract_ocr_ai_test.go
index bdbb9357ef..f0066a7ec1 100644
--- a/kernel/api/contract_ocr_ai_test.go
+++ b/kernel/api/contract_ocr_ai_test.go
@@ -20,8 +20,11 @@ import (
"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/heif"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/image/bmp"
+ "golang.org/x/image/tiff"
)
const aiOCRSuccess = `{"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":"first column\r\nsecond line"}}]}`
@@ -283,3 +286,118 @@ func TestAPIContractAIOCREmptyTextAndOriginalResolution(t *testing.T) {
t.Fatal("long image was downscaled before OCR")
}
}
+
+func TestAPIContractAIOCRConvertedFormats(t *testing.T) {
+ for _, extension := range []string{"bmp", "tif", "tiff", "heic", "heif"} {
+ t.Run(extension, func(t *testing.T) {
+ var received []byte
+ engine := setupAIOCRContract(t, func(w http.ResponseWriter, r *http.Request) {
+ received, _ = io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, aiOCRSuccess)
+ })
+ var source bytes.Buffer
+ img := image.NewRGBA(image.Rect(0, 0, 4096, 16))
+ img.Set(2, 3, color.RGBA{R: 255, A: 255})
+ width, height, mimeType := 4096, 16, "image/png"
+ var err error
+ switch extension {
+ case "bmp":
+ err = bmp.Encode(&source, img)
+ case "tif", "tiff":
+ err = tiff.Encode(&source, img, nil)
+ default:
+ var data []byte
+ data, err = os.ReadFile("../heif/testdata/basic.heic")
+ if err == nil {
+ source.Write(data)
+ width, height, err = heif.ImageSize(data)
+ }
+ mimeType = "image/jpeg"
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := "assets/converted." + extension
+ filename := filepath.Join(util.DataDir, filepath.FromSlash(path))
+ if err = os.WriteFile(filename, source.Bytes(), 0600); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ response := requestAIOCR(t, engine, path+"#preview")
+ if response.Code != 0 || response.Data.Text != "first column\nsecond line" || util.GetAssetText(path) != response.Data.Text {
+ t.Fatalf("converted OCR failed: %+v", response)
+ }
+ var request struct {
+ Messages []struct {
+ Content json.RawMessage `json:"content"`
+ } `json:"messages"`
+ }
+ if err = json.Unmarshal(received, &request); err != nil || len(request.Messages) != 2 {
+ t.Fatalf("invalid model request: %s", received)
+ }
+ var parts []struct {
+ ImageURL struct {
+ URL string `json:"url"`
+ } `json:"image_url"`
+ }
+ if err = json.Unmarshal(request.Messages[1].Content, &parts); err != nil || len(parts) != 1 {
+ t.Fatalf("invalid image parts: %s", received)
+ }
+ prefix := "data:" + mimeType + ";base64,"
+ if !strings.HasPrefix(parts[0].ImageURL.URL, prefix) {
+ t.Fatalf("unexpected converted MIME: %s", parts[0].ImageURL.URL[:min(80, len(parts[0].ImageURL.URL))])
+ }
+ data, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(parts[0].ImageURL.URL, prefix))
+ if err != nil {
+ t.Fatal(err)
+ }
+ config, _, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil || config.Width != width || config.Height != height {
+ t.Fatalf("conversion changed resolution: %+v, %v", config, err)
+ }
+ if extension == "bmp" || extension == "tif" || extension == "tiff" {
+ decoded, err := png.Decode(bytes.NewReader(data))
+ if err != nil || color.NRGBAModel.Convert(decoded.At(2, 3)) != (color.NRGBA{R: 255, A: 255}) {
+ t.Fatal("bitmap conversion lost source pixels")
+ }
+ }
+ unchanged, err := os.ReadFile(filename)
+ if err != nil || !bytes.Equal(unchanged, source.Bytes()) {
+ t.Fatal("conversion changed source asset")
+ }
+ })
+ }
+}
+
+func TestAPIContractAIOCRInvalidConversions(t *testing.T) {
+ calls := 0
+ engine := setupAIOCRContract(t, func(http.ResponseWriter, *http.Request) { calls++ })
+ var oversized bytes.Buffer
+ if err := tiff.Encode(&oversized, image.NewGray(image.Rect(0, 0, 8000, 5001)), &tiff.Options{Compression: tiff.Deflate}); err != nil {
+ t.Fatal(err)
+ }
+ for _, test := range []struct {
+ name string
+ data []byte
+ }{
+ {"broken.bmp", []byte{'B', 'M', 0, 0}},
+ {"broken.tiff", []byte{'I', 'I', 42, 0, 8, 0, 0, 0}},
+ {"broken.heic", append([]byte{0, 0, 0, 24}, []byte("ftypheic\x00\x00\x00\x00heicmif1")...)},
+ {"image.svg", []byte(`<svg xmlns="http://www.w3.org/2000/svg"/>`)},
+ {"oversized.tiff", oversized.Bytes()},
+ {"oversized.bmp", bytes.Repeat([]byte{'B'}, 20*1024*1024+1)},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ path := "assets/" + test.name
+ if err := os.WriteFile(filepath.Join(util.DataDir, filepath.FromSlash(path)), test.data, 0600); err != nil {
+ t.Fatal(err)
+ }
+ util.SetAssetText(path, "previous text")
+ t.Cleanup(func() { util.RemoveAssetText(path) })
+ if response := requestAIOCR(t, engine, path); response.Code == 0 || calls != 0 || util.GetAssetText(path) != "previous text" {
+ t.Fatalf("invalid conversion reached model or changed OCR: %+v, calls=%d", response, calls)
+ }
+ })
+ }
+}
diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.go
index e189e9f2c1..34e0d03b5b 100644
--- a/kernel/apicontract/contracts.go
+++ b/kernel/apicontract/contracts.go
@@ -872,6 +872,8 @@ var AssetOCR = define[AssetPathRequest, AssetOCRData]("ocr", "/api/asset/ocr", J
// AIOCR 仅手动调用已启用的智能体模型识别本地 assets/ 图片,不使用会话、工具或后台自动识别。
// path 保留 box 查询参数以隔离笔记本资源;拒绝加密资源和外部图片地址。
+// 支持 PNG、JPEG、GIF、WebP,并将 BMP、TIFF 转为 PNG、HEIC/HEIF 转为 JPEG;其他格式返回错误。
+// 保留原图分辨率,原始文件和发送图片均限制为 20 MiB、发送图片限制为四千万像素;HEIF 遵循预览解码限制。
// 支持现有 AI 生成协议,受 AI 功能开关、管理员权限和只读模式限制。
// 请求上限为两分钟,提供商配置的更短超时仍生效;模型不支持图片时返回错误,不降级为纯文本请求。
// 成功将完整文本(含换行和空白,图片无文字时可为空)保存到现有 OCR 存储并更新索引。
diff --git a/kernel/heif/cache.go b/kernel/heif/cache.go
index 55ea7723a5..b26897cb08 100644
--- a/kernel/heif/cache.go
+++ b/kernel/heif/cache.go
@@ -126,7 +126,7 @@ func GetOrCreate(ctx context.Context, source []byte, options Options) (Result, e
return Result{Path: cachePath, ETag: etag}, nil
}
- data, err := convert(ctx, source, options.Mode)
+ data, err := Convert(ctx, source, options.Mode)
if err != nil {
return Result{}, err
}
diff --git a/kernel/heif/cache_test.go b/kernel/heif/cache_test.go
index c4b07878f7..da2402c4e5 100644
--- a/kernel/heif/cache_test.go
+++ b/kernel/heif/cache_test.go
@@ -127,7 +127,7 @@ func TestConvertStillImages(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- preview, err := convert(context.Background(), source, ModePreview)
+ preview, err := Convert(context.Background(), source, ModePreview)
if err != nil {
t.Fatal(err)
}
diff --git a/kernel/heif/convert.go b/kernel/heif/convert.go
index e0e78a224c..3b9879dcb0 100644
--- a/kernel/heif/convert.go
+++ b/kernel/heif/convert.go
@@ -98,7 +98,8 @@ const (
ModeThumbnail Mode = "thumb"
)
-func convert(ctx context.Context, source []byte, mode Mode) ([]byte, error) {
+// Convert 将 HEIF 转换为 JPEG,复用预览的尺寸、内存和并发限制,不写入缓存。
+func Convert(ctx context.Context, source []byte, mode Mode) ([]byte, error) {
if len(source) == 0 {
return nil, errors.New("empty HEIF image")
}
diff --git a/kernel/model/ocr_ai.go b/kernel/model/ocr_ai.go
index 600588d6ab..a3f575e2d3 100644
--- a/kernel/model/ocr_ai.go
+++ b/kernel/model/ocr_ai.go
@@ -1,17 +1,25 @@
package model
import (
+ "bytes"
"context"
"encoding/base64"
"errors"
"fmt"
+ "image"
+ "image/png"
"io"
"os"
"strings"
"time"
+ "github.com/disintegration/imaging"
+ "github.com/gabriel-vasile/mimetype"
"github.com/sashabaranov/go-openai"
+ "github.com/siyuan-note/siyuan/kernel/heif"
"github.com/siyuan-note/siyuan/kernel/util"
+ _ "golang.org/x/image/bmp"
+ _ "golang.org/x/image/tiff"
)
// AIOCRAsset 使用智能体模型单次识别本地图片,完整响应通过校验后才保存和更新索引。
@@ -55,7 +63,7 @@ func AIOCRAsset(ctx context.Context, path string) (string, error) {
return "", err
}
// 保留原图分辨率,避免长截图中的小字在缩放后丢失;仍限制文件体积和总像素。
- image, err := util.PrepareModelImage(data, documentImageMaxBytes, documentImageMaxPixels, 0)
+ image, err := prepareAIOCRImage(ctx, data)
if err != nil {
return "", err
}
@@ -100,3 +108,42 @@ func AIOCRAsset(ctx context.Context, path string) (string, error) {
SetOCRAssetText(path, text)
return text, nil
}
+
+// prepareAIOCRImage 仅转换模型不接受但内核可解码的位图,保留分辨率并校验发送体积。
+func prepareAIOCRImage(ctx context.Context, data []byte) (util.PreparedImage, error) {
+ if err := ctx.Err(); err != nil {
+ return util.PreparedImage{}, err
+ }
+ if len(data) > documentImageMaxBytes {
+ return util.PreparedImage{}, fmt.Errorf("image exceeds size limit: %d bytes", documentImageMaxBytes)
+ }
+ switch mimeType := mimetype.Detect(data).String(); mimeType {
+ case "image/bmp", "image/tiff":
+ config, _, err := image.DecodeConfig(bytes.NewReader(data))
+ if err != nil {
+ return util.PreparedImage{}, err
+ }
+ if config.Width < 1 || config.Height < 1 || config.Width > documentImageMaxPixels/config.Height {
+ return util.PreparedImage{}, fmt.Errorf("image exceeds pixel limit: %d", documentImageMaxPixels)
+ }
+ decoded, err := imaging.Decode(bytes.NewReader(data), imaging.AutoOrientation(true))
+ if err != nil {
+ return util.PreparedImage{}, err
+ }
+ var output bytes.Buffer
+ if err = png.Encode(&output, decoded); err != nil {
+ return util.PreparedImage{}, err
+ }
+ data = output.Bytes()
+ case "image/heic", "image/heif", "image/heic-sequence", "image/heif-sequence":
+ var err error
+ data, err = heif.Convert(ctx, data, heif.ModePreview)
+ if err != nil {
+ return util.PreparedImage{}, err
+ }
+ }
+ if err := ctx.Err(); err != nil {
+ return util.PreparedImage{}, err
+ }
+ return util.PrepareModelImage(data, documentImageMaxBytes, documentImageMaxPixels, 0)
+}