Skip to content

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

:bug: Preserve OCR asset identity and bundle native runtime dependencies https://github.com/siyuan-note/siyuan/issues/19984

Daniel1c826f60e29c
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 01f63c9df3..f4042cb521 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -65,6 +65,13 @@ The optional global `--home-dir <path>` flag sets the base directory for user co
Use `--workspace` for notebook data and `--wd` for application resources independently. For example, after creating an empty `/work/siyuan-workspace` directory: `./SiYuan-Kernel serve --mode=dev --home-dir=/work/siyuan-home --workspace=/work/siyuan-workspace --wd=/work/siyuan/app`. When starting the server without an explicit workspace or a registered workspace in the selected profile, the default workspace remains under the selected home directory using the platform's existing layout (`SiYuan` on Windows/Linux, `Library/Application Support/SiYuan` on macOS). When `--home-dir` is set on Windows, `USERPROFILE` does not override it. These options do not change the mobile app's sandbox paths.
+### Desktop OCR packaging prerequisites
+
+Desktop packaging runs `scripts/prepare-ocr.py` to prepare the pinned models and native runtime. Run `python scripts/prepare-ocr.py --runtime windows-amd64 --check-only` or `python3 scripts/prepare-ocr.py --runtime linux-arm64 --build-worker --check-only` to check native prerequisites without downloading assets or compiling anything.
+
+* Windows: the release builder must have redistribution rights under its Visual Studio license and the matching x64/ARM64 **release** CRT files from `VC/Redist/MSVC`. The script discovers installed Visual Studio through `vswhere` or `VCToolsRedistDir`. Set `SIYUAN_OCR_VC_REDIST_DIR` to `VC/Redist/MSVC/<version>` (containing `x64` and/or `arm64`) or the target's `Microsoft.VC*.CRT` directory for a custom location or cross-host packaging. Use official Visual Studio redist files, not DLLs copied from `System32`, debug runtimes, or third-party DLL download sites. The preparation step checks architecture and required exports, bundles the transitive CRT dependencies beside ONNX Runtime, and records their SHA-256 digests and licensing notice. Keep this app-local runtime updated when preparing releases. See Microsoft's [redistribution terms](https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution#visual-c-runtime-files). It does not install system-wide runtimes or require elevation on end-user machines
+* Linux: the OCR worker needs a **glibc** compiler even when the kernel uses a musl toolchain. Install native `gcc` and the appropriate cross compiler before running `scripts/linux-build.sh`. On Debian/Ubuntu, AMD64-to-ARM64 builds need `gcc-aarch64-linux-gnu`; ARM64-to-AMD64 builds need `gcc-x86-64-linux-gnu`. Both can be installed with `sudo apt-get install gcc gcc-aarch64-linux-gnu gcc-x86-64-linux-gnu`. Optional `SIYUAN_OCR_CC_AMD64` and `SIYUAN_OCR_CC_ARM64` overrides select target-specific compiler commands; the script verifies their target triples and does not reuse the kernel's musl `CC`
+
### iOS
* `cd kernel`
diff --git a/.github/CONTRIBUTING.zh-CN.md b/.github/CONTRIBUTING.zh-CN.md
index 8c7a53fce1..dc76127418 100644
--- a/.github/CONTRIBUTING.zh-CN.md
+++ b/.github/CONTRIBUTING.zh-CN.md
@@ -65,6 +65,13 @@ NPM 镜像:
笔记数据目录由 `--workspace` 指定,应用资源目录由 `--wd` 指定,三者可以独立使用。例如,先创建空目录 `/work/siyuan-workspace`,再执行:`./SiYuan-Kernel serve --mode=dev --home-dir=/work/siyuan-home --workspace=/work/siyuan-workspace --wd=/work/siyuan/app`。启动服务时未显式指定工作空间且所选配置中没有已注册工作空间,默认工作空间沿用各平台的目录布局,位于所选主目录下:Windows/Linux 为 `SiYuan`,macOS 为 `Library/Application Support/SiYuan`。Windows 上显式指定 `--home-dir` 后,`USERPROFILE` 不再覆盖该选择。这些选项不改变移动端应用的沙箱路径。
+### 桌面端 OCR 打包依赖
+
+桌面端打包会运行 `scripts/prepare-ocr.py`,准备固定版本的模型和原生运行库。可以先执行 `python scripts/prepare-ocr.py --runtime windows-amd64 --check-only` 或 `python3 scripts/prepare-ocr.py --runtime linux-arm64 --build-worker --check-only` 检查原生依赖,不会下载资源或执行编译。
+
+* Windows:发布构建者须具有 Visual Studio 许可证授予的再分发权,并从 `VC/Redist/MSVC` 提供对应 x64/ARM64 架构的**发布版** CRT 文件。脚本通过 `vswhere` 或 `VCToolsRedistDir` 查找已安装的 Visual Studio。自定义位置或跨主机打包时,将 `SIYUAN_OCR_VC_REDIST_DIR` 指向含 `x64`、`arm64` 子目录的 `VC/Redist/MSVC/<version>`,也可以直接指向目标架构的 `Microsoft.VC*.CRT` 目录。仅使用官方 Visual Studio 再分发文件,不要从 `System32`、调试运行库或第三方 DLL 下载站收集文件。准备步骤会检查架构和必需的导出符号,将 CRT 的传递依赖放在 ONNX Runtime 旁,并记录 SHA-256 摘要及许可说明。发布时应及时更新这些应用本地运行库,详见 Microsoft 的[再分发条款](https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution#visual-c-runtime-files)。该方案不会安装系统级运行库,也不需要最终用户提权
+* Linux:即使内核采用 musl 工具链,OCR 辅助进程仍需要 **glibc** 编译器。运行 `scripts/linux-build.sh` 前须准备本机 `gcc` 和对应的交叉编译器。在 Debian/Ubuntu 上,AMD64 主机构建 ARM64 需要 `gcc-aarch64-linux-gnu`,ARM64 主机构建 AMD64 需要 `gcc-x86-64-linux-gnu`;可执行 `sudo apt-get install gcc gcc-aarch64-linux-gnu gcc-x86-64-linux-gnu` 安装。可选环境变量 `SIYUAN_OCR_CC_AMD64`、`SIYUAN_OCR_CC_ARM64` 分别指定目标架构的编译器命令,脚本会校验目标三元组,不会复用内核的 musl `CC`
+
### iOS
* `cd kernel`
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index b424c4f4c3..bb5e755ef8 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -22,6 +22,7 @@ The component list is informational and does not replace the license terms. Copy
|---|---|---|---|---|
| Electron | 42.7.1 | MIT | [upstream](https://github.com/electron/electron) | Desktop runtime; Electron also ships LICENSES.chromium.html for Chromium and its dependencies |
| ONNX Runtime | 1.24.3 (Windows, Linux, Apple Silicon, Android, HarmonyOS), 1.23.2 (Intel macOS), 1.24.2 (iOS) | MIT | [upstream](https://github.com/microsoft/onnxruntime) | Native CPU OCR runtime; license and dependency notices in app/stage/ocr/ONNXRUNTIME-LICENSE and ONNXRUNTIME-THIRD-PARTY-NOTICES.txt; desktop libraries also include their corresponding notices |
+| Microsoft Visual C++ Runtime | 14.x from the release builder's licensed Visual Studio redist | Microsoft Visual Studio Software License Terms | [redistribution terms](https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution#visual-c-runtime-files) | Windows OCR runtime directories include unmodified app-local CRT DLLs, MICROSOFT-VC-RUNTIME-NOTICE.txt, and vc-runtime-files.json with the exact file digests |
| PaddleOCR PP-OCRv6 Tiny and Small ONNX models | Pinned revisions in scripts/ocr-assets.json | Apache-2.0 | [official models](https://huggingface.co/collections/PaddlePaddle/pp-ocrv6) | app/stage/ocr/models/; license text in app/stage/ocr/PADDLEOCR-LICENSE |
| DOMPurify | 3.3.3 | Apache-2.0 OR MPL-2.0 | [upstream](https://github.com/cure53/DOMPurify) | app/stage/protyle/js/protyle-html.js |
| html-to-image | 1.11.13 | MIT | [upstream](https://github.com/bubkoo/html-to-image) | app/stage/protyle/js/html-to-image.min.js |
diff --git a/kernel/api/contract_ocr_test.go b/kernel/api/contract_ocr_test.go
index 83fc97ea99..a45aa94fc4 100644
--- a/kernel/api/contract_ocr_test.go
+++ b/kernel/api/contract_ocr_test.go
@@ -65,6 +65,61 @@ func TestAPIContractOCREncryptedAssetAliases(t *testing.T) {
}
}
+func TestAPIContractOCRNotebookIsolation(t *testing.T) {
+ assets := setupAssetContractWorkspace(t)
+ const name = "ocr-notebook-contract.png"
+ const path = "assets/" + name
+ const firstBox = "20261001021001-abcdefg"
+ const secondBox = "20261001021002-abcdefg"
+ boxConfig, err := json.Marshal(conf.NewBoxConf())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, boxID := range []string{firstBox, secondBox} {
+ for name, content := range map[string][]byte{".siyuan/conf.json": boxConfig, path: []byte(boxID)} {
+ filename := filepath.Join(util.DataDir, boxID, filepath.FromSlash(name))
+ if err = os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filename, content, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if err = os.WriteFile(filepath.Join(assets, name), []byte("global image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ engine := gin.New()
+ engine.POST("/api/asset/setImageOCRText", setImageOCRText)
+ engine.POST("/api/asset/getImageOCRText", getImageOCRText)
+ results := map[string]string{path: "global OCR", path + "?box=" + firstBox: "first notebook OCR", path + "?box=" + secondBox: "second notebook OCR"}
+ for reference, text := range results {
+ reference := reference
+ t.Cleanup(func() { util.RemoveAssetText(reference) })
+ body, _ := json.Marshal(map[string]string{"path": reference + "#preview", "text": text})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/setImageOCRText", bytes.NewReader(body)))
+ requireAPIContract(t, "POST", "/api/asset/setImageOCRText", recorder)
+ var response struct{ Code int }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 {
+ t.Fatalf("set OCR: %s, %v", recorder.Body.String(), err)
+ }
+ }
+ for reference, want := range results {
+ body, _ := json.Marshal(map[string]string{"path": reference + "#different-preview"})
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest("POST", "/api/asset/getImageOCRText", bytes.NewReader(body)))
+ requireAPIContract(t, "POST", "/api/asset/getImageOCRText", recorder)
+ var response struct {
+ Code int
+ Data apicontract.AssetTextData
+ }
+ if err = json.Unmarshal(recorder.Body.Bytes(), &response); err != nil || response.Code != 0 || response.Data.Text != want {
+ t.Fatalf("get OCR for %s: %s, %v", reference, recorder.Body.String(), err)
+ }
+ }
+}
+
func TestAPIContractOCRPermissions(t *testing.T) {
setupAssetContractWorkspace(t)
previousReadOnly := util.ReadOnly
diff --git a/kernel/model/ocr.go b/kernel/model/ocr.go
index a152beb395..709ee593a5 100644
--- a/kernel/model/ocr.go
+++ b/kernel/model/ocr.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "net/url"
"os"
"path/filepath"
"runtime"
@@ -134,10 +135,13 @@ func OCRAsset(ctx context.Context, path string) ([]map[string]string, error) {
if err != nil {
return nil, err
}
- canonical, _, err := assetPathAndBox(path, "")
+ canonical, boxID, err := assetPathAndBox(path, "")
if err != nil {
return nil, err
}
+ if boxID != "" {
+ canonical += "?box=" + url.QueryEscape(boxID)
+ }
SetOCRAssetText(canonical, util.GetOcrJsonText(rows))
return rows, nil
}
diff --git a/kernel/model/ocr_index_test.go b/kernel/model/ocr_index_test.go
index 315537a0d9..fde4207c7e 100644
--- a/kernel/model/ocr_index_test.go
+++ b/kernel/model/ocr_index_test.go
@@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"errors"
+ "fmt"
"os"
"os/exec"
"path/filepath"
@@ -27,11 +28,13 @@ type ocrFixtureProvider struct {
rows []map[string]string
err error
called bool
+ path string
}
func (*ocrFixtureProvider) Available() bool { return true }
-func (p *ocrFixtureProvider) Recognize(context.Context, string) ([]map[string]string, error) {
+func (p *ocrFixtureProvider) Recognize(_ context.Context, path string) ([]map[string]string, error) {
p.called = true
+ p.path = path
return p.rows, p.err
}
@@ -195,4 +198,110 @@ func TestOCRResultReindexesWithoutTesseract(t *testing.T) {
if err != nil || !bytes.Equal(after, ciphertext) {
t.Fatal("encrypted OCR changed source ciphertext")
}
+ testOCRNotebookIsolation(t, provider, fixture.box.ID)
+}
+
+func testOCRNotebookIsolation(t *testing.T, provider *ocrFixtureProvider, firstBox string) {
+ t.Helper()
+ const secondBox = "20261001020300-abcdefg"
+ box := &Box{ID: secondBox}
+ if err := box.SaveConf(conf.NewBoxConf()); err != nil {
+ t.Fatal(err)
+ }
+ const path = "assets/ocr-notebook-isolation.png"
+ first, second := path+"?box="+firstBox, path+"?box="+secondBox
+ for _, boxID := range []string{"", firstBox, secondBox} {
+ filename := filepath.Join(util.DataDir, boxID, filepath.FromSlash(path))
+ if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filename, []byte("fixture "+boxID), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ util.SetAssetText(path, "globalocrkeyword")
+ for _, reference := range []string{path, first, second} {
+ defer util.RemoveAssetText(reference)
+ }
+ documents := []struct {
+ box, reference, want string
+ }{
+ {firstBox, path, "globalocrkeyword"},
+ {firstBox, path + "?width=100&box=" + firstBox + "#preview", "firstocrkeyword"},
+ {secondBox, second, "secondocrkeyword"},
+ {secondBox, first + "&width=200", "firstocrkeyword"},
+ }
+ for i, document := range documents {
+ rootID := fmt.Sprintf("2026100102010%d-abcdefg", i)
+ paragraphID := fmt.Sprintf("2026100102020%d-abcdefg", i)
+ tree := treenode.NewTree(document.box, "/"+rootID+".sy", "/Scoped OCR", "Scoped OCR")
+ paragraph := treenode.NewParagraph(paragraphID)
+ parsed := parse.Parse("ocr", []byte("![fixture]("+document.reference+")"), util.NewLute().ParseOptions)
+ image := parsed.Root.FirstChild.FirstChild
+ image.Unlink()
+ paragraph.AppendChild(image)
+ tree.Root.AppendChild(paragraph)
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ Conf.OCR.Provider = "paddleocr"
+ for _, test := range []struct{ reference, box, text string }{
+ {" " + first + "&width=100#preview", firstBox, "firstocrkeyword"},
+ {second, secondBox, "secondocrkeyword"},
+ } {
+ provider.rows = []map[string]string{{"text": test.text, "conf": "99"}}
+ if _, err := OCRAsset(context.Background(), test.reference); err != nil {
+ t.Fatal(err)
+ }
+ if provider.path != filepath.Join(util.DataDir, test.box, filepath.FromSlash(path)) {
+ t.Fatalf("OCR recognized the wrong notebook asset: %s", provider.path)
+ }
+ }
+ sql.FlushQueue()
+ check := func() {
+ t.Helper()
+ for i, document := range documents {
+ paragraphID := fmt.Sprintf("2026100102020%d-abcdefg", i)
+ block := sql.GetBlock(paragraphID)
+ if block == nil || !strings.Contains(block.Content, document.want) {
+ t.Fatalf("scoped OCR was not indexed for %s: %+v", document.reference, block)
+ }
+ for _, unwanted := range []string{"globalocrkeyword", "firstocrkeyword", "secondocrkeyword", "changedocrkeyword"} {
+ if unwanted != document.want && strings.Contains(block.Content, unwanted) {
+ t.Fatalf("OCR leaked between notebook resources: %+v", block)
+ }
+ }
+ }
+ }
+ check()
+ SetOCRAssetText(first+"#edited", "changedocrkeyword")
+ documents[1].want, documents[3].want = "changedocrkeyword", "changedocrkeyword"
+ sql.FlushQueue()
+ check()
+ for keyword, count := range map[string]int{"firstocrkeyword": 0, "changedocrkeyword": 2, "secondocrkeyword": 1} {
+ matches, err := sql.QueryNoLimitArgs("SELECT id FROM blocks_fts WHERE blocks_fts MATCH ?", keyword)
+ if err != nil || len(matches) != count {
+ t.Fatalf("unexpected scoped OCR full-text results for %s: %v, %v", keyword, matches, err)
+ }
+ }
+ provider.err = errors.New("scoped recognition failed")
+ if _, err := OCRAsset(context.Background(), first); err == nil {
+ t.Fatal("failed notebook recognition returned success")
+ }
+ provider.err = nil
+ util.SaveAssetsTexts()
+ for _, reference := range []string{path, first, second} {
+ util.RemoveAssetText(reference)
+ }
+ util.LoadAssetsTexts()
+ secondText := util.GetOcrJsonText([]map[string]string{{"text": "secondocrkeyword", "conf": "99"}})
+ for reference, want := range map[string]string{path: "globalocrkeyword", first: "changedocrkeyword", second: secondText} {
+ if got := util.GetAssetText(reference); got != want {
+ t.Fatalf("scoped OCR result did not survive reload for %s: %q", reference, got)
+ }
+ }
}
diff --git a/kernel/sql/ocr.go b/kernel/sql/ocr.go
index 7588a24c8e..167175c970 100644
--- a/kernel/sql/ocr.go
+++ b/kernel/sql/ocr.go
@@ -1,7 +1,11 @@
package sql
+import "strings"
+
// QueryOCRAssetDocuments 返回普通笔记本中引用资源的文档,用于刷新包含 OCR 文本的块索引。
func QueryOCRAssetDocuments(path string) ([]Asset, error) {
+ // 资源索引不保存查询参数,由调用方继续按完整 OCR 资源身份筛选文档中的图片。
+ path = strings.SplitN(path, "?", 2)[0]
rows, err := query("SELECT DISTINCT root_id, box FROM assets WHERE path = ? OR instr(path, ?) = 1 OR instr(path, ?) = 1", path, path+"?", path+"#")
if err != nil {
return nil, err
diff --git a/kernel/util/ocr.go b/kernel/util/ocr.go
index 82d06a3fd7..f67c927344 100644
--- a/kernel/util/ocr.go
+++ b/kernel/util/ocr.go
@@ -21,6 +21,7 @@ import (
"context"
"errors"
"fmt"
+ "net/url"
"os"
"os/exec"
"path/filepath"
@@ -47,6 +48,7 @@ var (
TesseractLangs []string
assetsTexts = map[string]string{}
+ assetsTextAliases = map[string][]string{}
assetsTextsLock = sync.Mutex{}
assetsTextsChanged = atomic.Bool{}
)
@@ -94,8 +96,15 @@ func LoadAssetsTexts() {
logging.LogErrorf("unmarshal assets texts failed: %s", err)
return
}
+ aliases := map[string][]string{}
+ for reference := range loaded {
+ if key := OCRAssetKey(reference); key != reference {
+ aliases[key] = append(aliases[key], reference)
+ }
+ }
assetsTextsLock.Lock()
assetsTexts = loaded
+ assetsTextAliases = aliases
assetsTextsLock.Unlock()
debug.FreeOSMemory()
@@ -175,16 +184,30 @@ func GetAssetText(asset string) (ret string) {
}
func RemoveAssetText(asset string) {
+ key := OCRAssetKey(asset)
assetsTextsLock.Lock()
delete(assetsTexts, asset)
- delete(assetsTexts, OCRAssetKey(asset))
+ delete(assetsTexts, key)
+ // 同时移除旧版本保存的完整查询参数别名,避免删除规范键后重新读到旧结果。
+ for _, reference := range assetsTextAliases[key] {
+ delete(assetsTexts, reference)
+ }
+ delete(assetsTextAliases, key)
assetsTextsLock.Unlock()
assetsTextsChanged.Store(true)
}
-// OCRAssetKey 使同一图片的查询参数和片段引用共享识别结果。
+// OCRAssetKey 保留本地资源的笔记本身份,只合并显示参数和片段;外部地址保留完整查询参数。
func OCRAssetKey(asset string) string {
- if index := strings.IndexAny(asset, "?#"); index >= 0 {
+ asset = strings.SplitN(asset, "#", 2)[0]
+ if index := strings.IndexByte(asset, '?'); index >= 0 && strings.HasPrefix(asset, "assets/") {
+ query, err := url.ParseQuery(asset[index+1:])
+ if err != nil {
+ return asset
+ }
+ if boxID := strings.TrimSpace(query.Get("box")); boxID != "" {
+ return asset[:index] + "?box=" + url.QueryEscape(boxID)
+ }
return asset[:index]
}
return asset
diff --git a/kernel/util/ocr_test.go b/kernel/util/ocr_test.go
index d0616957d2..254800d2f2 100644
--- a/kernel/util/ocr_test.go
+++ b/kernel/util/ocr_test.go
@@ -1,6 +1,7 @@
package util
import (
+ "encoding/json"
"os"
"path/filepath"
"testing"
@@ -17,6 +18,95 @@ func TestOCRTextReferenceVariants(t *testing.T) {
}
}
+func TestOCRAssetKeyPreservesResourceIdentity(t *testing.T) {
+ const path = "assets/ocr-identity-test.png"
+ const box = "20261001020000-abcdefg"
+ for _, test := range []struct{ reference, key string }{
+ {path + "?page=1#fragment", path},
+ {path + "?page=1&box=" + box + "#fragment", path + "?box=" + box},
+ {path + "?box=%20" + box + "%20&width=100", path + "?box=" + box},
+ {path + "?box=first&box=second", path + "?box=first"},
+ {path + "?box=%invalid#fragment", path + "?box=%invalid"},
+ {"https://example.com/image?id=first#fragment", "https://example.com/image?id=first"},
+ {"https://example.com/image?id=second", "https://example.com/image?id=second"},
+ } {
+ if got := OCRAssetKey(test.reference); got != test.key {
+ t.Errorf("OCRAssetKey(%q) = %q, want %q", test.reference, got, test.key)
+ }
+ }
+}
+
+func TestOCRTextNotebookIsolation(t *testing.T) {
+ const path = "assets/ocr-notebook-isolation-test.png"
+ first := path + "?box=20261001020001-abcdefg"
+ second := path + "?box=20261001020002-abcdefg"
+ for _, reference := range []string{path, first, second} {
+ defer RemoveAssetText(reference)
+ }
+ SetAssetText(path, "global result")
+ if ExistsAssetText(first) || GetAssetText(first) != "" {
+ t.Fatal("notebook reference inherited a global OCR result")
+ }
+ SetAssetText(first+"&width=100#fragment", "first notebook")
+ SetAssetText(second, "second notebook")
+ for reference, want := range map[string]string{path: "global result", first: "first notebook", second: "second notebook"} {
+ if !ExistsAssetText(reference) || GetAssetText(reference) != want {
+ t.Fatalf("OCR result for %s is not isolated: %q", reference, GetAssetText(reference))
+ }
+ }
+ RemoveAssetText(first + "&width=200")
+ if ExistsAssetText(first) || GetAssetText(second) != "second notebook" || GetAssetText(path) != "global result" {
+ t.Fatal("removing one notebook result changed another resource")
+ }
+}
+
+func TestOCRTextPreservesLegacyScopedEntries(t *testing.T) {
+ const reference = "assets/ocr-legacy-scoped-test.png?width=100&box=20261001020003-abcdefg"
+ assetsTextsLock.Lock()
+ previousTexts, previousAliases := assetsTexts, assetsTextAliases
+ assetsTextsLock.Unlock()
+ previousDir, previousChanged := DataDir, assetsTextsChanged.Load()
+ defer func() {
+ assetsTextsLock.Lock()
+ assetsTexts, assetsTextAliases = previousTexts, previousAliases
+ assetsTextsLock.Unlock()
+ DataDir = previousDir
+ assetsTextsChanged.Store(previousChanged)
+ }()
+ DataDir = t.TempDir()
+ global := "assets/ocr-legacy-scoped-test.png"
+ other := global + "?box=20261001020006-abcdefg"
+ loaded := map[string]string{reference: "legacy notebook result", global: "global result", other: "other notebook result"}
+ data, err := json.Marshal(loaded)
+ if err != nil {
+ t.Fatal(err)
+ }
+ filename := filepath.Join(DataDir, "assets", "ocr-texts.json")
+ if err = os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filename, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ LoadAssetsTexts()
+ if !ExistsAssetText(reference) || GetAssetText(reference) != "legacy notebook result" {
+ t.Fatal("legacy exact-key OCR result is no longer readable")
+ }
+ SetAssetText(reference, "updated notebook result")
+ if GetAssetText(reference) != "updated notebook result" {
+ t.Fatal("canonical notebook result did not supersede its legacy alias")
+ }
+ RemoveAssetText(OCRAssetKey(reference))
+ SaveAssetsTexts()
+ LoadAssetsTexts()
+ if ExistsAssetText(reference) || GetAssetText(reference) != "" {
+ t.Fatal("deleted notebook OCR result reappeared through a legacy alias")
+ }
+ if GetAssetText(global) != "global result" || GetAssetText(other) != "other notebook result" {
+ t.Fatal("deleting a legacy alias changed another resource")
+ }
+}
+
func TestOCRCleanupRetainsNotebookAssets(t *testing.T) {
previous := DataDir
DataDir = t.TempDir()
@@ -33,6 +123,30 @@ func TestOCRCleanupRetainsNotebookAssets(t *testing.T) {
}
}
+func TestOCRCleanupUsesNotebookIdentity(t *testing.T) {
+ previous := DataDir
+ DataDir = t.TempDir()
+ defer func() { DataDir = previous }()
+ const path = "assets/ocr-cleanup-scoped-test.png"
+ first := path + "?box=20261001020004-abcdefg"
+ second := path + "?box=20261001020005-abcdefg"
+ filename := filepath.Join(DataDir, filepath.FromSlash(path))
+ if err := os.MkdirAll(filepath.Dir(filename), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filename, []byte("global image"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ for _, reference := range []string{path, first, second} {
+ SetAssetText(reference, "result")
+ defer RemoveAssetText(reference)
+ }
+ CleanNotExistAssetsTexts(func(reference string) bool { return reference == first })
+ if !ExistsAssetText(path) || !ExistsAssetText(first) || ExistsAssetText(second) {
+ t.Fatal("OCR cleanup confused scoped resources with a same-named global asset")
+ }
+}
+
func TestOCRCorruptCachePreservesSourceAndMemory(t *testing.T) {
previous := DataDir
DataDir = t.TempDir()
diff --git a/scripts/generate-third-party-notices.py b/scripts/generate-third-party-notices.py
index d7350e0bc5..99d7f66157 100644
--- a/scripts/generate-third-party-notices.py
+++ b/scripts/generate-third-party-notices.py
@@ -42,6 +42,27 @@ BUNDLED_COMPONENTS = [
"https://github.com/electron/electron",
"Desktop runtime; Electron also ships LICENSES.chromium.html for Chromium and its dependencies",
),
+ (
+ "ONNX Runtime",
+ "1.24.3 (Windows, Linux, Apple Silicon, Android, HarmonyOS), 1.23.2 (Intel macOS), 1.24.2 (iOS)",
+ "MIT",
+ "https://github.com/microsoft/onnxruntime",
+ "Native CPU OCR runtime; license and dependency notices in app/stage/ocr/ONNXRUNTIME-LICENSE and ONNXRUNTIME-THIRD-PARTY-NOTICES.txt; desktop libraries also include their corresponding notices",
+ ),
+ (
+ "Microsoft Visual C++ Runtime",
+ "14.x from the release builder's licensed Visual Studio redist",
+ "Microsoft Visual Studio Software License Terms",
+ "https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution#visual-c-runtime-files",
+ "Windows OCR runtime directories include unmodified app-local CRT DLLs, MICROSOFT-VC-RUNTIME-NOTICE.txt, and vc-runtime-files.json with the exact file digests",
+ ),
+ (
+ "PaddleOCR PP-OCRv6 Tiny and Small ONNX models",
+ "Pinned revisions in scripts/ocr-assets.json",
+ "Apache-2.0",
+ "https://huggingface.co/collections/PaddlePaddle/pp-ocrv6",
+ "app/stage/ocr/models/; license text in app/stage/ocr/PADDLEOCR-LICENSE",
+ ),
(
"DOMPurify",
"3.3.3",
diff --git a/scripts/linux-build.sh b/scripts/linux-build.sh
index ea05868a32..b152e87973 100755
--- a/scripts/linux-build.sh
+++ b/scripts/linux-build.sh
@@ -46,6 +46,14 @@ while [[ $# -gt 0 ]]; do
esac
done
+echo 'Checking OCR worker toolchains (glibc)'
+if [[ "$TARGET" == 'amd64' || "$TARGET" == 'all' ]]; then
+ python3 "$PROJECT_ROOT/scripts/prepare-ocr.py" --runtime linux-amd64 --build-worker --check-only
+fi
+if [[ "$TARGET" == 'arm64' || "$TARGET" == 'all' ]]; then
+ python3 "$PROJECT_ROOT/scripts/prepare-ocr.py" --runtime linux-arm64 --build-worker --check-only
+fi
+
echo 'Cleaning Builds'
rm -rf "$PROJECT_ROOT/app/build" 2>/dev/null || true
rm -rf "$PROJECT_ROOT/app/kernel-linux" 2>/dev/null || true
diff --git a/scripts/ocr-vc-runtime-notice.txt b/scripts/ocr-vc-runtime-notice.txt
new file mode 100644
index 0000000000..7e2d704a98
--- /dev/null
+++ b/scripts/ocr-vc-runtime-notice.txt
@@ -0,0 +1,19 @@
+Microsoft Visual C++ Runtime
+Copyright (c) Microsoft Corporation. All rights reserved.
+
+The Windows OCR runtime includes unmodified Microsoft Visual C++ runtime DLLs
+from the release builder's licensed Visual Studio VC/Redist/MSVC directory.
+The SHA-256 digest of each bundled DLL is recorded in vc-runtime-files.json.
+
+These files are proprietary Microsoft software, not covered by the ONNX Runtime
+MIT license or SiYuan's AGPL license. Redistribution is subject to the applicable
+Microsoft Visual Studio Software License Terms and its Distributable Code list:
+https://visualstudio.microsoft.com/license-terms/
+https://learn.microsoft.com/en-us/visualstudio/releases/2022/redistribution
+
+App-local deployment information:
+https://learn.microsoft.com/en-us/cpp/windows/redistributing-visual-cpp-files
+
+The release builder is responsible for having the required redistribution
+rights and keeping these app-local runtime files updated. No Microsoft runtime
+installer is run, and no system-wide runtime files are changed by this package.
diff --git a/scripts/prepare-ocr.py b/scripts/prepare-ocr.py
index 6f9269a2dc..e92f0e6640 100644
--- a/scripts/prepare-ocr.py
+++ b/scripts/prepare-ocr.py
@@ -7,7 +7,11 @@ import hashlib
import json
import os
from pathlib import Path
+import platform
+import re
+import shlex
import shutil
+import struct
import subprocess
import tarfile
import tempfile
@@ -20,6 +24,172 @@ MANIFEST = json.loads(Path(__file__).with_name("ocr-assets.json").read_text(enco
STAGE = ROOT / "app/stage/ocr"
+class WindowsDLL:
+ """读取 PE 导入和导出,不执行待打包的原生代码。"""
+
+ def __init__(self, path, target):
+ self.path, self.data = path, path.read_bytes()
+ pe = self.unpack("<I", 0x3c)[0]
+ if self.data[:2] != b"MZ" or self.data[pe:pe + 4] != b"PE\0\0":
+ raise ValueError(f"Invalid Windows DLL: {path}")
+ machine, sections = self.unpack("<HH", pe + 4)
+ optional_size, flags = self.unpack("<HH", pe + 20)
+ optional = pe + 24
+ if machine != {"windows-amd64": 0x8664, "windows-arm64": 0xaa64}[target] or not flags & 0x2000:
+ raise ValueError(f"Windows DLL architecture does not match {target}: {path}")
+ if self.unpack("<H", optional)[0] != 0x20b or optional_size < 224:
+ raise ValueError(f"Unsupported Windows DLL header: {path}")
+ if any(self.unpack("<II", optional + 112 + 13 * 8)):
+ raise ValueError(f"Delay-loaded Windows DLL dependencies require packaging review: {path}")
+ self.sections = [self.unpack("<IIII", optional + optional_size + index * 40 + 8)
+ for index in range(sections)]
+ self.exports = set()
+ exports, export_size = self.unpack("<II", optional + 112)
+ if exports:
+ base, count, names, functions, pointers, ordinals = self.unpack("<IIIIII", self.offset(exports) + 16)
+ for index in range(count):
+ function = self.unpack("<I", self.offset(functions) + index * 4)[0]
+ if exports <= function < exports + export_size:
+ raise ValueError(f"Forwarded Windows DLL exports require packaging review: {path}")
+ if function:
+ self.exports.add(base + index)
+ for index in range(names):
+ ordinal = self.unpack("<H", self.offset(ordinals) + index * 2)[0]
+ if base + ordinal in self.exports:
+ self.exports.add(self.string(self.unpack("<I", self.offset(pointers) + index * 4)[0]))
+ self.imports = {}
+ imports, size = self.unpack("<II", optional + 120)
+ for index in range(size // 20 if imports else 0):
+ lookup, _, _, name, address = self.unpack("<IIIII", self.offset(imports) + index * 20)
+ if not name:
+ break
+ symbols = set()
+ offset = self.offset(lookup or address)
+ while True:
+ value = self.unpack("<Q", offset)[0]
+ if not value:
+ break
+ symbols.add(value & 0xffff if value & (1 << 63) else self.string(value + 2))
+ offset += 8
+ self.imports[self.string(name).lower()] = symbols
+
+ def unpack(self, format, offset):
+ try:
+ return struct.unpack_from(format, self.data, offset)
+ except struct.error as error:
+ raise ValueError(f"Truncated Windows DLL: {self.path}") from error
+
+ def offset(self, address):
+ for _, virtual, size, raw in self.sections:
+ if virtual <= address < virtual + size:
+ return raw + address - virtual
+ raise ValueError(f"Invalid Windows DLL address: {self.path}")
+
+ def string(self, address):
+ offset = self.offset(address)
+ end = self.data.find(b"\0", offset)
+ if end < 0:
+ raise ValueError(f"Invalid Windows DLL string: {self.path}")
+ return self.data[offset:end].decode("ascii")
+
+
+def windows_crt_directory(target):
+ architecture = "x64" if target == "windows-amd64" else "arm64"
+ override = os.environ.get("SIYUAN_OCR_VC_REDIST_DIR")
+ roots = [Path(override)] if override else []
+ if not override:
+ if os.environ.get("VCToolsRedistDir"):
+ roots.append(Path(os.environ["VCToolsRedistDir"]))
+ vswhere = Path(os.environ.get("ProgramFiles(x86)", "C:/Program Files (x86)")) / "Microsoft Visual Studio/Installer/vswhere.exe"
+ if os.name == "nt" and vswhere.is_file():
+ locations = subprocess.check_output([str(vswhere), "-all", "-products", "*", "-property", "installationPath", "-utf8"], encoding="utf-8")
+ roots.extend(Path(location) / "VC/Redist/MSVC" for location in locations.splitlines() if location)
+ required = {"msvcp140.dll", "msvcp140_1.dll", "vcruntime140.dll"}
+ if architecture == "x64":
+ required.add("vcruntime140_1.dll")
+ errors = []
+ for root in roots:
+ candidates = ([root] if re.fullmatch(r"Microsoft\.VC\d+\.CRT", root.name, re.I) else
+ list(root.glob(f"{architecture}/Microsoft.VC*.CRT")) + list(root.glob(f"*/{architecture}/Microsoft.VC*.CRT")))
+ candidates.sort(key=lambda path: tuple(int(value) for value in re.findall(r"\d+", path.parent.parent.name)), reverse=True)
+ for directory in candidates:
+ if not directory.is_dir() or "debug_nonredist" in {part.lower() for part in directory.parts}:
+ continue
+ files = {path.name.lower(): path for path in directory.iterdir() if path.is_file()}
+ if not required <= files.keys():
+ continue
+ try:
+ for name in required:
+ WindowsDLL(files[name], target)
+ return directory
+ except ValueError as error:
+ errors.append(str(error))
+ raise RuntimeError(f"Missing {architecture} Visual C++ CRT from a licensed Visual Studio installation. "
+ "Set SIYUAN_OCR_VC_REDIST_DIR to VC/Redist/MSVC/<version> or its Microsoft.VC*.CRT directory. "
+ + "; ".join(errors))
+
+
+def prepare_windows_crt(target, directory, source):
+ # 从已许可的 Visual Studio Redist 目录选择完整依赖闭包,不从系统目录收集 DLL。
+ files = {path.name.lower(): path for path in source.iterdir() if path.is_file()}
+ selected, parsed = {}, {}
+ pending = [WindowsDLL(path, target) for path in directory.glob("onnxruntime*.dll")]
+ while pending:
+ library = pending.pop()
+ for name, symbols in library.imports.items():
+ if not re.fullmatch(r"(?:msvcp|vcruntime|concrt)\d[^/\\]*\.dll", name):
+ continue
+ if name not in files:
+ raise RuntimeError(f"Missing Visual C++ dependency {name} required by {library.path.name}")
+ if name not in parsed:
+ parsed[name] = WindowsDLL(files[name], target)
+ dependency = parsed[name]
+ if not symbols <= dependency.exports:
+ raise RuntimeError(f"Visual C++ dependency {name} is too old for {library.path.name}: missing exports")
+ if name not in selected:
+ selected[name] = files[name]
+ pending.append(dependency)
+ if not selected:
+ raise RuntimeError("ONNX Runtime has no recognized Visual C++ dependencies")
+ for path in directory.iterdir():
+ if path.is_file() and re.fullmatch(r"(?:msvcp|vcruntime|concrt)\d[^/\\]*\.dll", path.name, re.I) and path.name.lower() not in selected:
+ path.unlink()
+ for name, path in selected.items():
+ shutil.copyfile(path, directory / name)
+ shutil.copyfile(ROOT / "scripts/ocr-vc-runtime-notice.txt", directory / "MICROSOFT-VC-RUNTIME-NOTICE.txt")
+ (directory / "vc-runtime-files.json").write_text(json.dumps({name: digest(directory / name) for name in sorted(selected)}, indent=2) + "\n", encoding="utf-8")
+
+
+def linux_worker_environment(target):
+ architecture = target.split("-", 1)[1]
+ triples = {"amd64": "x86_64-linux-gnu", "arm64": "aarch64-linux-gnu"}
+ host = {"x86_64": "amd64", "amd64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get(platform.machine().lower())
+ variable = "SIYUAN_OCR_CC_" + architecture.upper()
+ compiler = os.environ.get(variable) or ("gcc" if host == architecture and platform.system() == "Linux" else triples[architecture] + "-gcc")
+ command = shlex.split(compiler)
+ if not command or not shutil.which(command[0]):
+ package = {"amd64": "gcc-x86-64-linux-gnu", "arm64": "gcc-aarch64-linux-gnu"}[architecture]
+ raise RuntimeError(f"Missing OCR compiler {compiler}. Install gcc/{package} or set {variable} to a glibc target compiler")
+ triple = subprocess.check_output(command + ["-dumpmachine"], encoding="utf-8").strip()
+ if triple.split("-", 1)[0] != triples[architecture].split("-", 1)[0] or "-linux-gnu" not in triple:
+ raise RuntimeError(f"OCR compiler {compiler} targets {triple}; {target} requires {triples[architecture]} (glibc)")
+ macros = subprocess.check_output(command + ["-dM", "-E", "-x", "c", "-"], input="#include <features.h>\n", encoding="utf-8")
+ if not re.search(r"^#define __GLIBC__ \d+$", macros, re.M):
+ raise RuntimeError(f"OCR compiler {compiler} does not use glibc headers; musl wrappers cannot load the bundled runtime")
+ environment = os.environ.copy()
+ # 内核可使用 musl 静态链接;识别辅助进程必须匹配随包分发的 glibc 原生运行库。
+ environment.update(GOOS="linux", GOARCH=architecture, CGO_ENABLED="1", CC=shlex.join(command))
+ return environment
+
+
+def runtime_prerequisites(target, build_worker):
+ if target.startswith("windows-"):
+ return windows_crt_directory(target)
+ if target.startswith("linux-") and build_worker:
+ return linux_worker_environment(target)
+ return None
+
+
def digest(path, algorithm="sha256"):
value = hashlib.new(algorithm)
with path.open("rb") as stream:
@@ -90,7 +260,9 @@ def download_ranges(entry, destination):
future.result()
-def prepare_runtime(target, build_worker):
+def prepare_runtime(target, build_worker, prerequisites=None):
+ if prerequisites is None:
+ prerequisites = runtime_prerequisites(target, build_worker)
entry = MANIFEST["runtime"][target]
cache = Path(tempfile.gettempdir()) / "siyuan-ocr-assets" / entry["url"].rsplit("/", 1)[1]
download(entry, cache)
@@ -119,25 +291,30 @@ def prepare_runtime(target, build_worker):
if member.name.rsplit("/", 1)[-1] in ("LICENSE", "ThirdPartyNotices.txt"):
with archive.extractfile(member) as source, (directory / member.name.rsplit("/", 1)[-1]).open("wb") as destination:
shutil.copyfileobj(source, destination)
+ if target.startswith("windows-"):
+ prepare_windows_crt(target, directory, prerequisites)
if target.startswith("linux-") and build_worker:
- architecture = target.split("-", 1)[1]
- environment = os.environ.copy()
- environment.update(GOOS="linux", GOARCH=architecture, CGO_ENABLED="1")
- environment["CC"] = "aarch64-linux-gnu-gcc" if architecture == "arm64" and os.uname().machine != "aarch64" else "gcc"
- subprocess.run(["go", "build", "-trimpath", "-ldflags=-s -w", "-o", str(directory / "siyuan-ocr"), "./ocr/cmd/ocr-worker"], cwd=ROOT / "kernel", env=environment, check=True)
+ subprocess.run(["go", "build", "-trimpath", "-ldflags=-s -w", "-o", str(directory / "siyuan-ocr"), "./ocr/cmd/ocr-worker"], cwd=ROOT / "kernel", env=prerequisites, check=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--runtime", choices=["none", *MANIFEST.get("runtime", {})], default="none")
parser.add_argument("--build-worker", action="store_true")
+ parser.add_argument("--check-only", action="store_true", help="Check native packaging prerequisites without downloads or builds")
args = parser.parse_args()
+ if args.check_only and args.runtime == "none":
+ parser.error("--check-only requires --runtime")
+ prerequisites = runtime_prerequisites(args.runtime, args.build_worker)
+ if args.check_only:
+ print(f"OCR prerequisites ready: {args.runtime}")
+ return
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
futures = [pool.submit(download, entry, STAGE / "models" / entry["path"]) for entry in MANIFEST["models"]]
for future in futures:
future.result()
if args.runtime != "none":
- prepare_runtime(args.runtime, args.build_worker)
+ prepare_runtime(args.runtime, args.build_worker, prerequisites)
print(f"OCR resources ready: {args.runtime}")
diff --git a/scripts/test_prepare_ocr.py b/scripts/test_prepare_ocr.py
index 69827f2001..36d84e02bd 100644
--- a/scripts/test_prepare_ocr.py
+++ b/scripts/test_prepare_ocr.py
@@ -3,7 +3,11 @@
import hashlib
import importlib.util
import io
+import json
+import os
from pathlib import Path
+import struct
+import sys
import tarfile
import tempfile
import unittest
@@ -15,6 +19,46 @@ prepare = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(prepare)
+def windows_dll(machine=0x8664, imports=None, exports=()):
+ """生成只含导入、导出表的 PE 测试夹具,不包含可执行代码。"""
+ data = bytearray(16384)
+ data[:2] = b"MZ"
+ struct.pack_into("<I", data, 0x3c, 0x80)
+ data[0x80:0x84] = b"PE\0\0"
+ struct.pack_into("<HH", data, 0x84, machine, 1)
+ struct.pack_into("<HH", data, 0x94, 240, 0x2000)
+ optional = 0x98
+ struct.pack_into("<H", data, optional, 0x20b)
+ struct.pack_into("<IIII", data, optional + 240 + 8, 15872, 0x1000, 15872, 0x200)
+ cursor = 0x400
+
+ def allocate(value):
+ nonlocal cursor
+ offset = cursor
+ data[offset:offset + len(value)] = value
+ cursor += (len(value) + 7) // 8 * 8
+ return offset, offset + 0xe00
+
+ if exports:
+ header, address = allocate(bytes(40))
+ struct.pack_into("<II", data, optional + 112, address, 40)
+ _, functions = allocate(struct.pack("<" + "I" * len(exports), *([0x1100] * len(exports))))
+ names = [allocate(name.encode() + b"\0")[1] for name in exports]
+ _, pointers = allocate(struct.pack("<" + "I" * len(names), *names))
+ _, ordinals = allocate(struct.pack("<" + "H" * len(names), *range(len(names))))
+ struct.pack_into("<IIIIII", data, header + 16, 1, len(names), len(names), functions, pointers, ordinals)
+ if imports:
+ header, address = allocate(bytes((len(imports) + 1) * 20))
+ struct.pack_into("<II", data, optional + 120, address, (len(imports) + 1) * 20)
+ for index, (name, symbols) in enumerate(imports.items()):
+ _, name_address = allocate(name.encode() + b"\0")
+ thunks = [(1 << 63) | symbol if isinstance(symbol, int) else allocate(b"\0\0" + symbol.encode() + b"\0")[1]
+ for symbol in symbols]
+ _, lookup = allocate(struct.pack("<" + "Q" * (len(thunks) + 1), *thunks, 0))
+ struct.pack_into("<IIIII", data, header + index * 20, lookup, 0, 0, name_address, lookup)
+ return bytes(data)
+
+
class ResourceTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
@@ -39,15 +83,123 @@ class ResourceTests(unittest.TestCase):
def test_windows_runtime_copies_only_libraries_and_licenses(self):
archive = self.root / "runtime.zip"
+ source = self.crt_source()
+ native = windows_dll(imports={"MSVCP140.dll": ["cpp"], "VCRUNTIME140_1.dll": ["unwind"]})
with zipfile.ZipFile(archive, "w") as output:
- for name, content in {"ort/lib/onnxruntime.dll": b"native", "ort/lib/onnxruntime_providers_shared.dll": b"provider", "ort/LICENSE": b"license", "../outside": b"unsafe"}.items():
+ for name, content in {"ort/lib/onnxruntime.dll": native, "ort/lib/onnxruntime_providers_shared.dll": windows_dll(), "ort/LICENSE": b"license", "../outside": b"unsafe"}.items():
output.writestr(name, content)
- self.extract(archive, "windows-amd64", "onnxruntime.dll")
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(source.parent.parent)}):
+ self.extract(archive, "windows-amd64", "onnxruntime.dll")
destination = self.root / "stage/runtime/windows-amd64"
- self.assertEqual((destination / "onnxruntime.dll").read_bytes(), b"native")
- self.assertEqual((destination / "onnxruntime_providers_shared.dll").read_bytes(), b"provider")
+ self.assertEqual((destination / "onnxruntime.dll").read_bytes(), native)
+ self.assertEqual((destination / "onnxruntime_providers_shared.dll").read_bytes(), windows_dll())
+ self.assertTrue((destination / "MICROSOFT-VC-RUNTIME-NOTICE.txt").is_file())
+ hashes = json.loads((destination / "vc-runtime-files.json").read_text())
+ self.assertEqual(set(hashes), {"msvcp140.dll", "msvcp140_1.dll", "vcruntime140.dll", "vcruntime140_1.dll"})
+ for name, digest in hashes.items():
+ self.assertEqual((destination / name).read_bytes(), (source / name).read_bytes())
+ self.assertEqual(digest, prepare.digest(source / name))
+ self.assertFalse((destination / "unused.dll").exists())
self.assertFalse((self.root / "outside").exists())
+ def crt_source(self, architecture="x64", machine=0x8664, version="14.44.35211"):
+ source = self.root / "redist" / version / architecture / "Microsoft.VC143.CRT"
+ source.mkdir(parents=True)
+ files = {
+ "msvcp140.dll": windows_dll(machine, {"VCRUNTIME140.dll": ["runtime"], "MSVCP140_1.dll": ["dot"]}, ["cpp"]),
+ "msvcp140_1.dll": windows_dll(machine, exports=["dot"]),
+ "vcruntime140.dll": windows_dll(machine, exports=["runtime"]),
+ "vcruntime140_1.dll": windows_dll(machine, exports=["unwind"]),
+ "unused.dll": b"not a runtime",
+ }
+ for name, content in files.items():
+ (source / name).write_bytes(content)
+ return source
+
+ def test_windows_crt_directory_supports_both_architectures_and_versions(self):
+ older = self.crt_source(version="14.9.999")
+ x64 = self.crt_source(version="14.44.35211")
+ arm64 = self.crt_source("arm64", 0xaa64)
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(self.root / "redist")}):
+ self.assertEqual(prepare.windows_crt_directory("windows-amd64"), x64)
+ self.assertEqual(prepare.windows_crt_directory("windows-arm64"), arm64)
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(older)}):
+ self.assertEqual(prepare.windows_crt_directory("windows-amd64"), older)
+ with self.assertRaisesRegex(RuntimeError, "architecture"):
+ prepare.windows_crt_directory("windows-arm64")
+
+ def test_windows_crt_vctools_discovery_and_arm64_dependency_closure(self):
+ source = self.crt_source("arm64", 0xaa64)
+ with patch.dict(os.environ, {"VCToolsRedistDir": str(source.parent.parent)}, clear=True):
+ self.assertEqual(prepare.windows_crt_directory("windows-arm64"), source)
+ destination = self.root / "arm64-runtime"
+ destination.mkdir()
+ (destination / "onnxruntime.dll").write_bytes(windows_dll(0xaa64, {"MSVCP140.dll": ["cpp"]}))
+ (destination / "msvcp140_2.dll").write_bytes(b"stale generated dependency")
+ prepare.prepare_windows_crt("windows-arm64", destination, source)
+ self.assertEqual({path.name for path in destination.glob("*.dll")},
+ {"onnxruntime.dll", "msvcp140.dll", "msvcp140_1.dll", "vcruntime140.dll"})
+ self.assertFalse((destination / "vcruntime140_1.dll").exists())
+
+ def test_windows_crt_missing_core_file_and_debug_directory_are_rejected(self):
+ source = self.crt_source()
+ (source / "vcruntime140.dll").unlink()
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(source)}):
+ with self.assertRaisesRegex(RuntimeError, "Missing x64 Visual C\\+\\+ CRT"):
+ prepare.windows_crt_directory("windows-amd64")
+ debug = self.root / "debug_nonredist" / source.name
+ debug.mkdir(parents=True)
+ for name in ("msvcp140.dll", "msvcp140_1.dll", "vcruntime140.dll", "vcruntime140_1.dll"):
+ (debug / name).write_bytes(windows_dll())
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(debug)}):
+ with self.assertRaises(RuntimeError):
+ prepare.windows_crt_directory("windows-amd64")
+
+ def test_windows_crt_rejects_missing_transitive_dependency_and_old_exports(self):
+ source = self.crt_source()
+ destination = self.root / "runtime"
+ destination.mkdir()
+ (destination / "onnxruntime.dll").write_bytes(windows_dll(imports={"MSVCP140.dll": ["cpp"]}))
+ (source / "msvcp140_1.dll").unlink()
+ with self.assertRaisesRegex(RuntimeError, "Missing Visual C\\+\\+ dependency msvcp140_1.dll"):
+ prepare.prepare_windows_crt("windows-amd64", destination, source)
+ self.assertEqual(list(destination.iterdir()), [destination / "onnxruntime.dll"])
+ (source / "msvcp140_1.dll").write_bytes(windows_dll(exports=["wrong"]))
+ with self.assertRaisesRegex(RuntimeError, "too old"):
+ prepare.prepare_windows_crt("windows-amd64", destination, source)
+
+ def test_windows_dll_handles_ordinal_imports_and_rejects_bad_headers(self):
+ path = self.root / "test.dll"
+ path.write_bytes(windows_dll(imports={"MSVCP140.dll": [1]}, exports=["entry"]))
+ library = prepare.WindowsDLL(path, "windows-amd64")
+ self.assertEqual(library.imports, {"msvcp140.dll": {1}})
+ self.assertEqual(library.exports, {1, "entry"})
+ for data in (b"", b"not a PE file", windows_dll()[:200]):
+ path.write_bytes(data)
+ with self.assertRaises(ValueError):
+ prepare.WindowsDLL(path, "windows-amd64")
+
+ def test_windows_dll_rejects_unhandled_delay_imports_and_forwarders(self):
+ path = self.root / "unsupported.dll"
+ data = bytearray(windows_dll())
+ struct.pack_into("<II", data, 0x98 + 112 + 13 * 8, 0x1200, 32)
+ path.write_bytes(data)
+ with self.assertRaisesRegex(ValueError, "Delay-loaded"):
+ prepare.WindowsDLL(path, "windows-amd64")
+ data = bytearray(windows_dll(exports=["forwarded"]))
+ export_address = struct.unpack_from("<I", data, 0x98 + 112)[0]
+ function_table = struct.unpack_from("<I", data, export_address - 0xe00 + 28)[0]
+ struct.pack_into("<I", data, function_table - 0xe00, export_address + 1)
+ path.write_bytes(data)
+ with self.assertRaisesRegex(ValueError, "Forwarded"):
+ prepare.WindowsDLL(path, "windows-amd64")
+
+ def test_windows_missing_crt_fails_before_downloading(self):
+ with patch.dict(os.environ, {"SIYUAN_OCR_VC_REDIST_DIR": str(self.root / "missing")}), patch.object(prepare, "download") as download:
+ with self.assertRaisesRegex(RuntimeError, "licensed Visual Studio"):
+ prepare.prepare_runtime("windows-amd64", False)
+ download.assert_not_called()
+
def test_linux_runtime_selects_regular_library_without_symlinks(self):
archive = self.root / "runtime.tgz"
with tarfile.open(archive, "w:gz") as output:
@@ -68,5 +220,67 @@ class ResourceTests(unittest.TestCase):
prepare.prepare_runtime(target, False)
+class CompilerTests(unittest.TestCase):
+ def test_selects_native_and_cross_compilers_without_inheriting_kernel_cc(self):
+ for host, target, compiler, triple in (
+ ("x86_64", "amd64", "gcc", "x86_64-linux-gnu"),
+ ("aarch64", "arm64", "gcc", "aarch64-linux-gnu"),
+ ("x86_64", "arm64", "aarch64-linux-gnu-gcc", "aarch64-linux-gnu"),
+ ("aarch64", "amd64", "x86_64-linux-gnu-gcc", "x86_64-linux-gnu"),
+ ):
+ with self.subTest(host=host, target=target), patch.dict(os.environ, {"CC": "wrong-linux-musl-gcc"}, clear=True), \
+ patch.object(prepare.platform, "machine", return_value=host), \
+ patch.object(prepare.platform, "system", return_value="Linux"), \
+ patch.object(prepare.shutil, "which", return_value="/usr/bin/compiler"), \
+ patch.object(prepare.subprocess, "check_output", side_effect=[triple, "#define __GLIBC__ 2\n"]) as probe:
+ environment = prepare.linux_worker_environment("linux-" + target)
+ self.assertEqual(environment["CC"], compiler)
+ self.assertEqual(environment["GOARCH"], target)
+ self.assertEqual(environment["CGO_ENABLED"], "1")
+ self.assertEqual(probe.call_args_list[0].args, ([compiler, "-dumpmachine"],))
+ self.assertEqual(probe.call_count, 2)
+
+ def test_explicit_compiler_supports_paths_with_spaces(self):
+ with patch.dict(os.environ, {"SIYUAN_OCR_CC_AMD64": "'/opt/cross tools/gcc'"}, clear=True), \
+ patch.object(prepare.shutil, "which", return_value="/opt/cross tools/gcc"), \
+ patch.object(prepare.subprocess, "check_output", side_effect=["x86_64-linux-gnu", "#define __GLIBC__ 2\n"]) as probe:
+ self.assertEqual(prepare.linux_worker_environment("linux-amd64")["CC"], "'/opt/cross tools/gcc'")
+ self.assertEqual(probe.call_args_list[0].args, (["/opt/cross tools/gcc", "-dumpmachine"],))
+
+ def test_rejects_musl_wrapper_reporting_a_gnu_target(self):
+ with patch.dict(os.environ, {"SIYUAN_OCR_CC_AMD64": "musl-gcc"}, clear=True), \
+ patch.object(prepare.shutil, "which", return_value="/usr/bin/musl-gcc"), \
+ patch.object(prepare.subprocess, "check_output", side_effect=["x86_64-linux-gnu", "#define _FEATURES_H 1\n"]):
+ with self.assertRaisesRegex(RuntimeError, "does not use glibc headers"):
+ prepare.linux_worker_environment("linux-amd64")
+
+ def test_rejects_missing_wrong_architecture_and_musl_compilers(self):
+ with patch.dict(os.environ, {}, clear=True), patch.object(prepare.shutil, "which", return_value=None):
+ with self.assertRaisesRegex(RuntimeError, "Missing OCR compiler"):
+ prepare.linux_worker_environment("linux-amd64")
+ for triple in ("aarch64-linux-gnu", "x86_64-linux-musl", "x86_64-apple-darwin"):
+ with self.subTest(triple=triple), patch.dict(os.environ, {}, clear=True), \
+ patch.object(prepare.shutil, "which", return_value="/usr/bin/gcc"), \
+ patch.object(prepare.subprocess, "check_output", return_value=triple):
+ with self.assertRaisesRegex(RuntimeError, "requires x86_64-linux-gnu"):
+ prepare.linux_worker_environment("linux-amd64")
+
+ def test_check_only_does_not_download_or_build(self):
+ with patch.object(sys, "argv", ["prepare-ocr.py", "--runtime", "linux-arm64", "--build-worker", "--check-only"]), \
+ patch.object(prepare, "runtime_prerequisites") as prerequisites, \
+ patch.object(prepare, "download") as download, patch.object(prepare, "prepare_runtime") as runtime:
+ prepare.main()
+ prerequisites.assert_called_once_with("linux-arm64", True)
+ download.assert_not_called()
+ runtime.assert_not_called()
+
+ def test_linux_missing_compiler_fails_before_downloading(self):
+ with patch.dict(os.environ, {}, clear=True), patch.object(prepare.shutil, "which", return_value=None), \
+ patch.object(prepare, "download") as download:
+ with self.assertRaisesRegex(RuntimeError, "Missing OCR compiler"):
+ prepare.prepare_runtime("linux-amd64", True)
+ download.assert_not_called()
+
+
if __name__ == "__main__":
unittest.main()