An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Improve text https://github.com/siyuan-note/siyuan/issues/17720
Daniele59acd47e061
diff --git a/app/src/config/tabs/aiTab.ts b/app/src/config/tabs/aiTab.tsindex b63544723d..248af94e99 100644--- a/app/src/config/tabs/aiTab.ts+++ b/app/src/config/tabs/aiTab.ts@@ -138,6 +138,11 @@ const registerAiEmbeddingGroup = (tab: SettingTabBuilder) => {desc: window.siyuan.languages.apiModelTip,mode: "input-text",});+ group.number("ai.embedding.dimensions", {+ title: window.siyuan.languages.apiDimensions,+ desc: window.siyuan.languages.apiDimensionsTip,+ min: 0,+ });group.number("ai.embedding.timeout", {title: window.siyuan.languages.apiTimeout,desc: window.siyuan.languages.apiTimeoutTip,diff --git a/app/src/types/config.d.ts b/app/src/types/config.d.tsindex 134aecfd43..ff589f80de 100644--- a/app/src/types/config.d.ts+++ b/app/src/types/config.d.ts@@ -164,6 +164,7 @@ declare namespace Config {apiKey: string;name: string;timeout: number;+ dimensions: number;}/**diff --git a/kernel/conf/ai.go b/kernel/conf/ai.goindex 7ed7723d53..ba6ff7adf7 100644--- a/kernel/conf/ai.go+++ b/kernel/conf/ai.go@@ -56,12 +56,13 @@ type Editing struct {}type Embedding struct {- ID string `json:"id"`- Enabled bool `json:"enabled"`- APIKey string `json:"apiKey"`- BaseURL string `json:"baseURL"`- Name string `json:"name"`- Timeout int `json:"timeout"`+ ID string `json:"id"`+ Enabled bool `json:"enabled"`+ APIKey string `json:"apiKey"`+ BaseURL string `json:"baseURL"`+ Name string `json:"name"`+ Timeout int `json:"timeout"`+ Dimensions int `json:"dimensions"` // 输出向量维度,仅 text-embedding-3 及以上模型支持;0 表示用模型默认值(不传该参数)}type Provider struct {@@ -359,6 +360,9 @@ func (ai *AI) Normalize() {if ai.Embedding.Timeout < 1 {ai.Embedding.Timeout = 30}+ if ai.Embedding.Dimensions < 0 {+ ai.Embedding.Dimensions = 0 // 负值非法,归零表示用模型默认维度+ }if !ast.IsNodeIDPattern(ai.Embedding.ID) {ai.Embedding.ID = ast.NewNodeID()}diff --git a/kernel/model/embedding.go b/kernel/model/embedding.goindex b59eaf6519..0d211d7e00 100644--- a/kernel/model/embedding.go+++ b/kernel/model/embedding.go@@ -326,7 +326,7 @@ func recordFailedEmbedding(blocks []map[string]any, reason string) {}func doEmbedAndStore(texts []string, blocks []map[string]any) {- vectors, err := util.BatchGetEmbeddings(texts, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingTimeout())+ vectors, err := util.BatchGetEmbeddings(texts, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingDimensions(), embeddingTimeout())if err != nil {// 任何 API 错误(含模型不存在/鉴权失败/限流/网络异常)都熔断本轮,避免连接风暴recordFailedEmbedding(blocks, err.Error())@@ -437,7 +437,7 @@ func SemanticSearchBlock(query string, boxes, paths []string, types, subTypes mareturn}- vectors, err := util.BatchGetEmbeddings([]string{query}, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingTimeout())+ vectors, err := util.BatchGetEmbeddings([]string{query}, embeddingKey(), embeddingBaseURL(), embeddingModel(), embeddingDimensions(), embeddingTimeout())if err != nil || 1 > len(vectors) {logging.LogErrorf("get query embedding failed")return@@ -733,6 +733,15 @@ func embeddingTimeout() int {return 30}+// embeddingDimensions 返回配置的输出向量维度。0 表示用模型默认维度(不传 dimensions 参数给 API),+// 仅 text-embedding-3 及以上模型支持自定义维度。文档向量与查询向量必须用相同维度,否则相似度计算会维度不匹配。+func embeddingDimensions() int {+ if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && 0 < Conf.AI.Embedding.Dimensions {+ return Conf.AI.Embedding.Dimensions+ }+ return 0+}+func embeddingModel() string {if nil != Conf.AI.Embedding && Conf.AI.Embedding.Enabled && "" != Conf.AI.Embedding.Name {return Conf.AI.Embedding.Namediff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 706361ea77..ccceed3f48 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -201,7 +201,7 @@ func getEmbeddingHTTPClient() *http.Client {return embeddingHTTPClient}-func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, timeout int) (ret [][]float32, err error) {+func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, dimensions, timeout int) (ret [][]float32, err error) {if 1 > len(texts) {return}@@ -215,8 +215,9 @@ func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, timeout idefer cancel()resp, err := client.CreateEmbeddings(ctx, openai.EmbeddingRequestStrings{- Input: texts,- Model: openai.EmbeddingModel(model),+ Input: texts,+ Model: openai.EmbeddingModel(model),+ Dimensions: dimensions, // 0 时因 omitempty 不发送,等同于用模型默认维度})if err != nil {logging.LogErrorf("create embeddings failed: %s", err)diff --git a/scripts/check-translations.py b/scripts/check-translations.pynew file mode 100644index 0000000000..3754a41852--- /dev/null+++ b/scripts/check-translations.py@@ -0,0 +1,94 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""+以 zh-CN.json 为基准,检查其他语言文件的翻译质量(精准版)。+检测规则:+ 1. MISSING_KEY: 键缺失+ 2. UNTRANSLATED: 目标值与中文原文【完全相同】(针对非 zh-CN 语言,含中文且字符串相等)+ 3. PLACEHOLDER_MISMATCH: 占位符/HTML 标签丢失(规范化后比较)+注意:日语/韩语的汉字使用是合法的,不视为错误,因此仅当整串与原文相同时才报未翻译。+"""+import json+import re+import os++LANG_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),+ "app", "appearance", "langs")+BASE = "zh-CN"+TARGETS = ["ar", "de", "en", "es", "fr", "he", "hi", "id", "it", "ja", "ko",+ "nl", "pl", "pt-BR", "ru", "sk", "th", "tr", "uk", "zh-TW"]++CN_RE = re.compile(r"[\u4e00-\u9fff]")+TRIVIAL_RE = re.compile(r"^[\s\d\W]+$", re.UNICODE)+++def load(name):+ with open(os.path.join(LANG_DIR, name + ".json"), encoding="utf-8") as f:+ return json.load(f)+++def walk(obj, prefix=""):+ out = {}+ if isinstance(obj, dict):+ for k, v in obj.items():+ key = prefix + "." + k if prefix else k+ if isinstance(v, dict):+ out.update(walk(v, key))+ else:+ out[key] = v+ return out+++def norm_placeholders(s):+ """规范化占位符比较:统一引号、忽略 URL 路径差异、忽略帮助链接域名差异"""+ s2 = s.replace('"', "'")+ s2 = re.sub(r"b3log\.org/siyuan(/[a-z]{2})?/", "b3log.org/siyuan/", s2)+ s2 = re.sub(r"b3log\.org/siyuan(\?[^\s\"']*)?", "b3log.org/siyuan", s2)+ s2 = re.sub(r"https://(ld246\.com|liuyun\.io)/article/\d+", "HELPURL", s2)+ ps = re.findall(r"\$\{[^}]+\}|\{[a-zA-Z_][a-zA-Z0-9_]*\}|%[sdf]|\d+\$[sdf]|<[^>]+>", s2)+ return sorted(ps)+++def main():+ base = load(BASE)+ bflat = walk(base)+ total = 0+ for t in TARGETS:+ tgt = load(t)+ tflat = walk(tgt)+ issues = []+ for k in bflat:+ if k not in tflat:+ issues.append((k, "MISSING_KEY", ""))+ continue+ for k, bv in bflat.items():+ if k not in tflat:+ continue+ tv = tflat[k]+ if not isinstance(bv, str) or not isinstance(tv, str):+ continue+ if TRIVIAL_RE.match(bv):+ continue+ # 完全未翻译:目标值与中文原文完全相同(仅对非 zh-CN 语言)+ if t != "zh-CN" and tv == bv and CN_RE.search(bv):+ issues.append((k, "UNTRANSLATED", bv[:80]))+ # 占位符丢失(规范化后比较)+ bp = norm_placeholders(bv)+ tp = norm_placeholders(tv)+ if bp and bp != tp:+ issues.append((k, "PLACEHOLDER_MISMATCH",+ "base=%s target=%s" % (bp, tp)))+ if issues:+ total += len(issues)+ print("=" * 70)+ print("### %s (%d issues)" % (t, len(issues)))+ print("=" * 70)+ for k, kind, detail in issues:+ print(" [%s] %s" % (kind, k))+ if detail:+ print(" -> %s" % detail[:200])+ print("\nTotal issues: %d" % total)+++if __name__ == "__main__":+ main()