feat(翻译): sip翻译
deploy-hxtesting / build-and-deploy (push) Successful in 1m18s

This commit is contained in:
runny committed 2026-11-30 20:45:34 +08:00
1 parent 5583d7b74b
commit db8472bf28
15 files changed
+2260 -2

No files matched your search

+43
View File
@@ -194,6 +194,49 @@ builtin_agents:
rerank_top_k: 5 rerank_top_k: 5
rerank_threshold: 0.3 rerank_threshold: 0.3
- id: "builtin-sip-translator"
avatar: "🌐"
is_builtin: true
i18n:
default:
name: "SIP Translator"
description: "Upload a Chinese SIP/SOP engineering Excel workbook and get the English translation with a verification report"
zh-CN:
name: "SIP 翻译专家"
description: "上传 SIP/SOP 工程图纸 Excel,自动完成中文→英文翻译,输出英文版工作簿与校验报告"
zh-TW:
name: "SIP 翻譯專家"
description: "上傳 SIP/SOP 工程圖紙 Excel,自動完成中文→英文翻譯,輸出英文版工作簿與校驗報告"
ja-JP:
name: "SIP 翻訳エキスパート"
description: "中国語の SIP/SOP 工程 Excel をアップロードすると、英語版ワークブックと検証レポートを自動生成します"
ko-KR:
name: "SIP 번역 전문가"
description: "중국어 SIP/SOP 엔지니어링 Excel을 업로드하면 영문 워크북과 검증 보고서를 자동 생성합니다"
config:
agent_mode: "smart-reasoning"
agent_type: "custom"
system_prompt_id: "sip_translator"
temperature: 0.3
max_completion_tokens: 8192
max_iterations: 15
kb_selection_mode: "none"
retrieve_kb_only_when_mentioned: false
supported_file_types:
- "xlsx"
allowed_tools:
- "xlsx_translate"
- "ask_user"
web_search_enabled: false
web_search_max_results: 0
reflection_enabled: false
multi_turn_enabled: true
embedding_top_k: 5
keyword_threshold: 0.3
vector_threshold: 0.5
rerank_top_k: 5
rerank_threshold: 0.3
- id: "builtin-wiki-researcher" - id: "builtin-wiki-researcher"
avatar: "📚" avatar: "📚"
is_builtin: true is_builtin: true
@@ -77,6 +77,33 @@ templates:
- Present an appropriate table, chart, or explanation, including assumptions and material limitations. Do not force a SQL call for a question that needs no data access. - Present an appropriate table, chart, or explanation, including assumptions and material limitations. Do not force a SQL call for a question that needs no data access.
Use only tools available in this turn; source selection and output conventions are defined by the runtime sections. Use only tools available in this turn; source selection and output conventions are defined by the runtime sections.
- id: "sip_translator"
name: "SIP Translator"
description: "System prompt for the SIP/SOP workbook translation agent (Chinese to English)"
i18n:
zh-CN:
name: "SIP 翻译专家"
description: "SIP/SOP 工程 Excel 中文→英文翻译智能体系统提示词"
en-US:
name: "SIP Translator"
description: "System prompt for the SIP/SOP workbook translation agent (Chinese to English)"
ko-KR:
name: "SIP 번역 전문가"
description: "SIP/SOP 통합 문서 번역 에이전트용 시스템 프롬프트"
ja-JP:
name: "SIP 翻訳エキスパート"
description: "SIP/SOP ワークブック翻訳エージェント用のシステムプロンプト"
mode: "sip_translator"
content: |
You are Academy SIP Translator, specialized in translating Chinese engineering Excel workbooks (SIP standard inspection procedures, SOP standard operating procedures, rack/enclosure manufacturing documents) into English.
Workflow:
- When the user uploads a .xlsx workbook, call xlsx_translate with file_path set to the uploaded file's absolute sandbox path from <sandbox_attachments>. Never ask the user to re-upload or to run any manual steps.
- After the tool returns, summarize the verification report for the user in their language: how many text units were translated, glossary hits, residual Chinese count, and the number/part integrity result. The translated workbook is delivered automatically as a downloadable output artifact named <original>_EN.xlsx — point the user to it.
- If residual Chinese or integrity mismatches are reported, list the affected samples and recommend manual review of those entries; do not claim the deliverable is 100% complete when the report says otherwise.
- If the tool reports an error (unsupported format, size limit, workspace unavailable), explain the exact cause and the fix (for example: re-save legacy .xls as .xlsx, or ask an administrator to enable the session workspace).
- Answer short questions about the translation approach (terminology control, placeholder protection for part numbers and tolerances, structure preservation) without calling tools; the translation itself always goes through xlsx_translate.
Do not read or modify the workbook with other tools. Use only tools available in this turn; source selection and output conventions are defined by the runtime sections.
- id: "wiki_researcher" - id: "wiki_researcher"
name: "Wiki Researcher" name: "Wiki Researcher"
description: "System prompt for Wiki Researcher agent with knowledge graph traversal" description: "System prompt for Wiki Researcher agent with knowledge graph traversal"
+9 -2
View File
@@ -27,8 +27,14 @@ const (
ToolDatabaseQuery = "database_query" ToolDatabaseQuery = "database_query"
ToolDataAnalysis = "data_analysis" ToolDataAnalysis = "data_analysis"
ToolDataSchema = "data_schema" ToolDataSchema = "data_schema"
ToolWebSearch = "web_search" // ToolXlsxTranslate translates a Chinese SIP/SOP engineering workbook to
ToolWebFetch = "web_fetch" // English through the xlsxtranslate pipeline and writes the English
// deliverable into the artifact output directory. Like the sandbox tools
// it only registers when the session workspace exists, because the
// deliverable is delivered through it.
ToolXlsxTranslate = "xlsx_translate"
ToolWebSearch = "web_search"
ToolWebFetch = "web_fetch"
// Unified reading: workspace access follows sandbox file capability; // Unified reading: workspace access follows sandbox file capability;
// skill resources follow SkillsEnabled and do not require a sandbox. // skill resources follow SkillsEnabled and do not require a sandbox.
// attachment:// is added whenever the session has stored attachments, // attachment:// is added whenever the session has stored attachments,
@@ -169,6 +175,7 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolWikiUpdateIssue, Label: "更新Wiki问题状态", Description: "更新特定的Wiki页面问题状态", Group: ToolGroupWikiIssue}, {Name: ToolWikiUpdateIssue, Label: "更新Wiki问题状态", Description: "更新特定的Wiki页面问题状态", Group: ToolGroupWikiIssue},
{Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析", Group: ToolGroupData}, {Name: ToolDataAnalysis, Label: "数据分析", Description: "理解数据文件并进行数据分析", Group: ToolGroupData},
{Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息", Group: ToolGroupData}, {Name: ToolDataSchema, Label: "查看数据元信息", Description: "获取表格文件的元信息", Group: ToolGroupData},
{Name: ToolXlsxTranslate, Label: "Excel翻译", Description: "对上传的 SIP/SOP 工程 Excel 执行中文→英文翻译并输出英文工作簿", Group: ToolGroupData},
} }
} }
+258
View File
@@ -0,0 +1,258 @@
package tools
import (
"bytes"
"context"
"encoding/json"
"fmt"
"path"
"strings"
"time"
"academy/internal/logger"
"academy/internal/models/chat"
"academy/internal/types"
"academy/internal/utils"
"academy/internal/xlsxtranslate"
)
// maxTranslateBytes caps one translation run. The largest known real file is
// a 63 MB bilingual SIP; the cap leaves headroom for heavier workbooks while
// still bounding memory (the package is processed in memory by design, which
// is what keeps media byte-identical).
const maxTranslateBytes = 256 << 20 // 256 MB
// xlsxMagic is the ZIP local-file header every .xlsx container starts with.
var xlsxMagic = []byte{0x50, 0x4B, 0x03, 0x04}
var legacyXLSMagicBytes = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}
const xlsxTranslateDescription = `Translate a Chinese engineering Excel workbook (SIP / SOP / inspection standard,
.xlsx only) into English and deliver the translated workbook as a downloadable output file.
Pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments> as file_path.
The tool preserves the workbook exactly — merged cells, images, styles, formulas and sheet layout are
copied byte-for-byte; only Chinese text (cell strings, inline strings and drawing text boxes) is
translated. Part numbers, tolerances and dates are protected as placeholders and never altered.
A verification report (residual Chinese, number/part integrity) is returned; the translated workbook
lands in the artifact output directory for the user to download.`
// XlsxTranslateInput is the tool argument schema.
type XlsxTranslateInput struct {
FilePath string `json:"file_path" jsonschema:"Absolute sandbox path of the uploaded .xlsx workbook, taken from <sandbox_attachments> (for example /workspace/input/part.xlsx)"`
}
// sessionDirEnsurer is the slice of SessionFileStore that provisions the
// output directory before writing.
type sessionDirEnsurer interface {
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
}
// XlsxTranslateTool translates an uploaded workbook through the
// xlsxtranslate pipeline, writing the English deliverable into the session
// artifact output directory.
type XlsxTranslateTool struct {
BaseTool
store SandboxFileSink
ensure sessionDirEnsurer
model chat.Chat
timeout time.Duration
}
// NewXlsxTranslateTool constructs the tool. store and model MUST NOT be nil;
// the tool is only registered when a session sandbox exists, because the
// deliverable is delivered through the artifact output directory.
func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model chat.Chat) *XlsxTranslateTool {
return &XlsxTranslateTool{
BaseTool: BaseTool{
name: ToolXlsxTranslate,
description: xlsxTranslateDescription,
schema: utils.GenerateSchema[XlsxTranslateInput](),
},
store: store,
ensure: ensure,
model: model,
timeout: 20 * time.Minute,
}
}
// Execute runs the translation pipeline over the requested workbook.
func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var input XlsxTranslateInput
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("invalid arguments: %v", err)}, nil
}
filePath := strings.TrimSpace(input.FilePath)
if filePath == "" {
return &types.ToolResult{Success: false,
Error: "file_path is required: pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments>"}, nil
}
sessionID := resolveSessionID(ctx)
if sessionID == "" {
return &types.ToolResult{Success: false,
Error: "no session ID in context; xlsx_translate must run inside an agent turn"}, nil
}
layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store)
if layoutErr != nil {
return layoutErr, nil
}
// Same relative-path semantics as the file primitives: a bare filename
// or workspace-relative path resolves against the workspace root.
filePath = resolveIn(layout, filePath)
lower := strings.ToLower(filePath)
if !strings.HasSuffix(lower, ".xlsx") {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", path.Base(filePath))}, nil
}
data, err := t.store.ReadSessionFile(ctx, sessionID, filePath)
if err != nil {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("failed to read %s: %v", filePath, err)}, nil
}
if len(data) == 0 {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is empty", filePath)}, nil
}
if len(data) > maxTranslateBytes {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("%s is %d MB, above the %d MB translation limit", path.Base(filePath), len(data)>>20, maxTranslateBytes>>20)}, nil
}
if bytes.HasPrefix(data, legacyXLSMagicBytes) {
return &types.ToolResult{Success: false,
Error: "this is a legacy binary .xls workbook; re-save it as .xlsx and upload again"}, nil
}
if !bytes.HasPrefix(data, xlsxMagic) {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(filePath))}, nil
}
runCtx, cancel := context.WithTimeout(ctx, t.timeout)
defer cancel()
translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{
BatchSize: 40,
}, &chatBatchTranslator{model: t.model})
if err != nil {
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, filePath, err)
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("translation failed: %v", err)}, nil
}
baseName := path.Base(filePath)
ext := path.Ext(baseName)
outName := strings.TrimSuffix(baseName, ext) + "_EN.xlsx"
outputDir := layoutOutputDir(layout)
if outputDir == "" {
return &types.ToolResult{Success: false,
Error: "session has no artifact output directory; the sandbox workspace is unavailable"}, nil
}
outPath := outputDir + "/" + outName
if t.ensure != nil {
if err := t.ensure.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
logger.Warnf(ctx, "[Tool][XlsxTranslate] ensure output dir failed: %v", err)
}
}
if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err != nil {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("failed to write translated workbook to %s: %v", outPath, err)}, nil
}
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
sessionID, filePath, outPath, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
var b strings.Builder
b.WriteString("Translation finished. The English workbook is saved as **" + outName + "** in the output directory (available as a downloadable artifact).\n\n")
b.WriteString(report.Markdown())
if report.ResidualCJKCount > 0 {
b.WriteString("\nNote: residual Chinese remains (see samples above) — usually oversized or untranslatable entries. Review them manually.\n")
}
if len(report.NumberMismatches) > 0 || len(report.PartMismatches) > 0 {
b.WriteString("\nNote: numeric/part token integrity check found differences — do not deliver without manual review.\n")
}
return &types.ToolResult{
Success: true,
Output: b.String(),
OutputFiles: sandboxOutputLinksIn(outputDir, outPath),
Data: map[string]interface{}{
"output_path": outPath,
"translated_units": report.TranslatedUnits,
"glossary_hits": report.GlossaryHits,
"llm_calls": report.LLMCalls,
"residual_cjk": report.ResidualCJKCount,
"number_mismatches": len(report.NumberMismatches),
"part_mismatches": len(report.PartMismatches),
"duration_ms": report.DurationMs,
},
}, nil
}
// chatBatchTranslator adapts the session chat model to the engine's
// Translator interface: one call = one JSON array round trip.
type chatBatchTranslator struct {
model chat.Chat
}
const translateSystemPrompt = `You are a professional translator for engineering quality documents (SIP standard inspection procedures, SOP standard operating procedures, rack/enclosure manufacturing).
Translate each Chinese string into concise, professional English as used in factory inspection documents.
Rules:
1. Keep every placeholder token exactly as written: __T0__, __T1__, ... must appear unchanged in the translation at the position of the value they replace.
2. Keep numbering prefixes (1. / 2. / 1.1 / (1)), line breaks (\n) and list structure.
3. Keep units, model names and standard references (MIL-STD-1916, IP20, M8) unchanged.
4. Use established inspection terminology: 检验=inspection, 目视=visual, 抽样=sampling, 检具=inspection gauge, 平面度=flatness, 对角线=diagonal, 接地=grounding, 料号=part number, 工单=work order.
5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.`
func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) {
payload, err := json.Marshal(texts)
if err != nil {
return nil, err
}
var lastErr error
for attempt := 0; attempt < 3; attempt++ {
if attempt > 0 {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(attempt) * 2 * time.Second):
}
}
user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload)
resp, err := c.model.Chat(ctx, []chat.Message{
{Role: "system", Content: translateSystemPrompt},
{Role: "user", Content: user},
}, &chat.ChatOptions{Temperature: 0.2, MaxCompletionTokens: 16384})
if err != nil {
lastErr = err
continue
}
out, err := parseTranslationArray(resp.Content, len(texts))
if err != nil {
lastErr = err
continue
}
return out, nil
}
return nil, fmt.Errorf("translation call failed after retries: %w", lastErr)
}
// parseTranslationArray extracts the JSON array from a model response that
// may wrap it in markdown fences or prose.
func parseTranslationArray(content string, want int) ([]string, error) {
trimmed := strings.TrimSpace(content)
trimmed = strings.TrimPrefix(trimmed, "```json")
trimmed = strings.TrimPrefix(trimmed, "```")
trimmed = strings.TrimSuffix(trimmed, "```")
trimmed = strings.TrimSpace(trimmed)
start := strings.IndexByte(trimmed, '[')
end := strings.LastIndexByte(trimmed, ']')
if start < 0 || end <= start {
return nil, fmt.Errorf("no JSON array in model response: %.120s", content)
}
var out []string
if err := json.Unmarshal([]byte(trimmed[start:end+1]), &out); err != nil {
return nil, fmt.Errorf("model response is not a valid string array: %w", err)
}
if len(out) != want {
return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), want)
}
return out, nil
}
+184
View File
@@ -0,0 +1,184 @@
package tools
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"testing"
"academy/internal/models/chat"
"academy/internal/sandbox"
"academy/internal/types"
)
// fakeTranslateStore is an in-memory SessionFileSink + dir ensurer.
type fakeTranslateStore struct {
files map[string][]byte
ensured []string
writePath string
}
func (s *fakeTranslateStore) EnsureSessionDir(_ context.Context, _, dir string) error {
s.ensured = append(s.ensured, dir)
return nil
}
func (s *fakeTranslateStore) StatSessionFile(_ context.Context, _, _ string) (*sandbox.RemoteStatEntry, error) {
return nil, fmt.Errorf("not implemented")
}
func (s *fakeTranslateStore) ReadSessionFile(_ context.Context, _, path string) ([]byte, error) {
if data, ok := s.files[path]; ok {
return data, nil
}
return nil, fmt.Errorf("no such file: %s", path)
}
func (s *fakeTranslateStore) WriteSessionWorkspaceFile(_ context.Context, _, path string, content []byte) error {
s.files[path] = content
s.writePath = path
return nil
}
// fakeTranslateChat answers every batch with the requested array translated
// deterministically: CJK runs become " EN ".
type fakeTranslateChat struct {
prompts []string
}
func (f *fakeTranslateChat) Chat(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
f.prompts = append(f.prompts, messages[len(messages)-1].Content)
start := strings.IndexByte(messages[len(messages)-1].Content, '[')
end := strings.LastIndexByte(messages[len(messages)-1].Content, ']')
var texts []string
if err := json.Unmarshal([]byte(messages[len(messages)-1].Content[start:end+1]), &texts); err != nil {
return nil, err
}
out := make([]string, 0, len(texts))
for _, t := range texts {
out = append(out, replaceCJKRuns(t))
}
b, _ := json.Marshal(out)
return &types.ChatResponse{Content: string(b)}, nil
}
func (f *fakeTranslateChat) ChatStream(_ context.Context, _ []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
return nil, fmt.Errorf("not implemented")
}
func (f *fakeTranslateChat) GetModelName() string { return "fake" }
func (f *fakeTranslateChat) GetModelID() string { return "fake-id" }
// replaceCJKRuns mirrors the engine-test stub: CJK runs become a single space.
func replaceCJKRuns(s string) string {
var b strings.Builder
inCJK := false
for _, r := range s {
if (r >= 0x3400 && r <= 0x9FFF) || (r >= 0xF900 && r <= 0xFAFF) ||
(r >= 0x3000 && r <= 0x303F) || (r >= 0xFF01 && r <= 0xFF5E) {
inCJK = true
continue
}
if inCJK {
b.WriteByte(' ')
inCJK = false
}
b.WriteRune(r)
}
if inCJK {
b.WriteByte(' ')
}
return b.String()
}
func buildToolFixture(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, f := range []struct{ name, body string }{
{"[Content_Types].xml", "<Types/>"},
{"xl/sharedStrings.xml", `<sst xmlns="x"><si><t>螺母 M8</t></si><si><t>Assembly Process</t></si></sst>`},
} {
w, _ := zw.Create(f.name)
w.Write([]byte(f.body))
}
zw.Close()
return buf.Bytes()
}
func TestXlsxTranslateToolEndToEnd(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xlsx": buildToolFixture(t),
}}
tool := NewXlsxTranslateTool(store, store, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if store.writePath != "/workspace/output/part_EN.xlsx" {
t.Fatalf("unexpected output path: %s", store.writePath)
}
if len(result.OutputFiles) != 1 || !strings.Contains(result.OutputFiles[0], "part_EN.xlsx") {
t.Fatalf("missing output link: %v", result.OutputFiles)
}
if !strings.Contains(result.Output, "part_EN.xlsx") {
t.Fatalf("output does not name the deliverable: %s", result.Output)
}
// The translated workbook must contain no CJK and keep the EN string.
r, err := zip.NewReader(bytes.NewReader(store.files[store.writePath]), int64(len(store.files[store.writePath])))
if err != nil {
t.Fatalf("output zip: %v", err)
}
var ss string
for _, f := range r.File {
if f.Name == "xl/sharedStrings.xml" {
rc, _ := f.Open()
raw, _ := io.ReadAll(rc)
rc.Close()
ss = string(raw)
}
}
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("output still contains Chinese: %s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("English string lost: %s", ss)
}
}
func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xls": {0xD0, 0xCF, 0x11, 0xE0},
}}
tool := NewXlsxTranslateTool(store, store, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
result, _ := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
if result.Success {
t.Fatalf("legacy .xls should be rejected")
}
if !strings.Contains(result.Error, ".xlsx") {
t.Fatalf("unhelpful error: %s", result.Error)
}
}
func TestXlsxTranslateToolMissingFile(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tool := NewXlsxTranslateTool(store, store, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
result, _ := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
if result.Success {
t.Fatalf("missing file should fail")
}
}
@@ -268,6 +268,7 @@ func (s *agentService) CreateAgentEngine(
// capability independently of the existing SkillsEnabled execution gate. // capability independently of the existing SkillsEnabled execution gate.
s.registerSandboxShellIfAllowed(ctx, toolRegistry, sessionID, config) s.registerSandboxShellIfAllowed(ctx, toolRegistry, sessionID, config)
s.registerSandboxFileTools(ctx, toolRegistry, sessionID, config) s.registerSandboxFileTools(ctx, toolRegistry, sessionID, config)
s.registerXlsxTranslateTool(ctx, toolRegistry, sessionID, config, chatModel)
s.registerWebPageFiles(ctx, toolRegistry, config, sessionID, assistantMessageID) s.registerWebPageFiles(ctx, toolRegistry, config, sessionID, assistantMessageID)
attachmentReader := s.registerAttachmentReader(ctx, toolRegistry, config, sessionID) attachmentReader := s.registerAttachmentReader(ctx, toolRegistry, config, sessionID)
// Advertise cached service summaries independently of @mentions. Concrete // Advertise cached service summaries independently of @mentions. Concrete
@@ -649,6 +650,50 @@ func (s *agentService) registerSandboxFileTools(
} }
} }
// registerXlsxTranslateTool registers the SIP/SOP workbook translation tool
// for agents that allow it. The tool reads the uploaded workbook through the
// session sandbox and delivers the English deliverable through the artifact
// output directory, so it follows the same sandbox capability gate as the
// file primitives: no session workspace, no translation tool.
func (s *agentService) registerXlsxTranslateTool(
ctx context.Context,
toolRegistry *tools.ToolRegistry,
sessionID string,
config *types.AgentConfig,
chatModel chat.Chat,
) {
allowed := false
for _, name := range tools.EffectiveAllowedTools(config.AllowedTools) {
if name == tools.ToolXlsxTranslate {
allowed = true
break
}
}
if !allowed {
return
}
if chatModel == nil {
logger.Infof(ctx, "xlsx_translate withheld: session has no chat model to translate with")
return
}
sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for xlsx_translate: %v", err)
return
}
if sandboxMgr == nil {
logger.Infof(ctx, "xlsx_translate withheld: session has no workspace sandbox to read attachments and deliver output")
return
}
store := sessionSandboxFileStore(sandboxMgr)
if store == nil {
logger.Infof(ctx, "xlsx_translate withheld: sandbox backend does not advertise session filesystem capability")
return
}
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, chatModel))
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s", sessionID)
}
// registerSkillFileTools registers write_skill_file / edit_skill_file for the // registerSkillFileTools registers write_skill_file / edit_skill_file for the
// built-in skill installer, and for nothing else. // built-in skill installer, and for nothing else.
// //
+4
View File
@@ -230,6 +230,10 @@ var toolHandlePolicies = map[string]toolHandlePolicy{
"read_sandbox_file": {}, "read_sandbox_file": {},
"write_sandbox_file": {}, "write_sandbox_file": {},
"edit_sandbox_file": {}, "edit_sandbox_file": {},
// xlsx_translate reads an uploaded workbook from the sandbox and reports
// translation statistics; like the sandbox tools it echoes paths and
// counts and never carries knowledge identifiers.
"xlsx_translate": {},
// Installer-only writers for the skill image tree. Same unknown-shape // Installer-only writers for the skill image tree. Same unknown-shape
// caveat: they echo paths and byte counts, never knowledge identifiers. // caveat: they echo paths and byte counts, never knowledge identifiers.
"write_skill_file": {}, "write_skill_file": {},
+4
View File
@@ -22,6 +22,9 @@ const (
BuiltinDeepResearcherID = "builtin-deep-researcher" BuiltinDeepResearcherID = "builtin-deep-researcher"
// BuiltinDataAnalystID is the ID for the built-in data analyst agent // BuiltinDataAnalystID is the ID for the built-in data analyst agent
BuiltinDataAnalystID = "builtin-data-analyst" BuiltinDataAnalystID = "builtin-data-analyst"
// BuiltinSIPTranslatorID is the ID for the built-in SIP/SOP workbook
// translation agent (Chinese -> English engineering Excel translation)
BuiltinSIPTranslatorID = "builtin-sip-translator"
// BuiltinKnowledgeGraphExpertID is the ID for the built-in knowledge graph expert agent // BuiltinKnowledgeGraphExpertID is the ID for the built-in knowledge graph expert agent
BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert" BuiltinKnowledgeGraphExpertID = "builtin-knowledge-graph-expert"
// BuiltinDocumentAssistantID is the ID for the built-in document assistant agent // BuiltinDocumentAssistantID is the ID for the built-in document assistant agent
@@ -717,6 +720,7 @@ var builtinAgentIDsOrdered = []string{
BuiltinWikiResearcherID, BuiltinWikiResearcherID,
BuiltinDeepResearcherID, BuiltinDeepResearcherID,
BuiltinDataAnalystID, BuiltinDataAnalystID,
BuiltinSIPTranslatorID,
BuiltinKnowledgeGraphExpertID, BuiltinKnowledgeGraphExpertID,
BuiltinDocumentAssistantID, BuiltinDocumentAssistantID,
} }
+180
View File
@@ -0,0 +1,180 @@
// Package xlsxtranslate implements the surgical-XML translation pipeline for
// engineering-drawing Excel workbooks (SIP/SOP): unpack the .xlsx zip,
// translate only CJK text nodes in sharedStrings and drawing text bodies,
// write the translations back in place, and hard-verify the result.
//
// The design follows the internal plan document "SIP 说明 Excel 翻译 Agent
// 可实施落地方案": deterministic work (extraction, classification, masking,
// write-back, verification) stays in code; the LLM only ever sees deduplicated
// Chinese text with structured tokens (part numbers, tolerances, dates) masked
// as placeholders.
package xlsxtranslate
import (
"regexp"
"strings"
)
// cjkIdeo matches CJK ideographs, including the Extension A block and the
// compatibility ideograph block. This is the "contains Chinese" test that
// decides whether a text unit enters the translation queue, and the residual
// scan that runs on the output package.
var cjkIdeo = regexp.MustCompile(`[\x{3400}-\x{4DBF}\x{4E00}-\x{9FFF}\x{F900}-\x{FAFF}]`)
// cjkAny additionally matches CJK punctuation and full-width forms. The hard
// verification only fails on ideographs; full-width leftovers are reported as
// warnings because some are legitimate in a Chinese source sheet.
var cjkAny = regexp.MustCompile(`[\x{3000}-\x{303F}\x{FF00}-\x{FFEF}\x{2018}-\x{201D}\x{2026}\x{00B7}]`)
// structuredToken matches the "looks like text but must never change" tokens:
// part numbers (JD4-AR1.2-RACK-JC47A), serial date numbers (46335),
// tolerances (2298.7+0/-3.2), unit-qualified values (573.5±1.0mm), page refs.
// It is applied to every text unit before it is sent to the LLM; each match is
// replaced by a __Tn__ placeholder and restored verbatim afterwards.
var structuredToken = regexp.MustCompile(`[A-Za-z0-9][A-Za-z0-9\-_/.]{2,}|\d+(?:\.\d+)?`)
// numberToken extracts plain numeric literals for the input/output equality
// check of the hard verification.
var numberToken = regexp.MustCompile(`\d+(?:\.\d+)?`)
// partToken extracts part-number style tokens (letters mixed with digits and
// separators) for the input/output equality check.
var partToken = regexp.MustCompile(`[A-Za-z]{1,6}[-_][A-Za-z0-9][A-Za-z0-9\-_/.]{1,}`)
// placeholder wraps a masked token index inside a translated string.
func placeholder(i int) string { return "__T" + itoa(i) + "__" }
var placeholderRe = regexp.MustCompile(`__T(\d+)__`)
// mask replaces every structured token in s with __Tn__ placeholders and
// returns the masked string together with the tokens in order.
func mask(s string) (string, []string) {
tokens := make([]string, 0, 4)
var b strings.Builder
last := 0
for _, loc := range structuredToken.FindAllStringIndex(s, -1) {
b.WriteString(s[last:loc[0]])
b.WriteString(placeholder(len(tokens)))
tokens = append(tokens, s[loc[0]:loc[1]])
last = loc[1]
}
b.WriteString(s[last:])
return b.String(), tokens
}
// unmask restores __Tn__ placeholders to their original tokens. Unknown or
// malformed placeholders are left as-is and reported through missing.
func unmask(s string, tokens []string) (restored string, missing []string) {
missing = nil
restored = placeholderRe.ReplaceAllStringFunc(s, func(m string) string {
idx := atoi(m[3 : len(m)-2])
if idx >= 0 && idx < len(tokens) {
return tokens[idx]
}
missing = append(missing, m)
return m
})
return restored, missing
}
// hasCJK reports whether s contains at least one CJK ideograph.
func hasCJK(s string) bool { return cjkIdeo.MatchString(s) }
// fullWidth maps full-width punctuation and full-width alphanumerics that
// leak into translated output back to their ASCII forms. Applied only to
// newly translated strings — never to untouched source content.
var fullWidth = strings.NewReplacer(
"\u3000", " ",
":", ":",
",", ",",
";", ";",
"!", "!",
"?", "?",
"(", "(",
")", ")",
"【", "[",
"】", "]",
"、", ",",
"。", ".",
"~", "~",
"-", "-",
"・", "·",
"'", "'",
"'", "'",
"\u201c", "\"",
"\u201d", "\"",
"0", "0", "1", "1", "2", "2", "3", "3", "4", "4",
"5", "5", "6", "6", "7", "7", "8", "8", "9", "9",
"A", "A", "B", "B", "C", "C", "D", "D", "E", "E", "F", "F",
"G", "G", "H", "H", "I", "I", "J", "J", "K", "K", "L", "L",
"M", "M", "N", "N", "O", "O", "P", "P", "Q", "Q", "R", "R",
"S", "S", "T", "T", "U", "U", "V", "V", "W", "W", "X", "X",
"Y", "Y", "Z", "Z",
"a", "a", "b", "b", "c", "c", "d", "d", "e", "e", "f", "f",
"g", "g", "h", "h", "i", "i", "j", "j", "k", "k", "l", "l",
"m", "m", "n", "n", "o", "o", "p", "p", "q", "q", "r", "r",
"s", "s", "t", "t", "u", "u", "v", "v", "w", "w", "x", "x",
"y", "y", "z", "z",
)
// normalizePunctuation converts full-width punctuation and alphanumerics in a
// translated string to ASCII equivalents.
func normalizePunctuation(s string) string { return fullWidth.Replace(s) }
// whitespaceKey strips every ASCII and full-width whitespace rune so glossary
// lookups tolerate layout padding such as "客 戶".
func whitespaceKey(s string) string {
var b strings.Builder
for _, r := range s {
switch r {
case ' ', '\t', '\n', '\r', '\u3000', '\u00a0':
default:
b.WriteRune(r)
}
}
return b.String()
}
// trimSpaceASCII trims surrounding ASCII whitespace only, so glossary lookup
// does not silently eat meaningful full-width padding.
func trimSpaceASCII(s string) string {
return strings.Trim(s, " \t\n\r")
}
// itoa is a tiny helper so this file needs no strconv import noise.
func itoa(i int) string {
if i == 0 {
return "0"
}
neg := i < 0
if neg {
i = -i
}
var buf [20]byte
pos := len(buf)
for i > 0 {
pos--
buf[pos] = byte('0' + i%10)
i /= 10
}
if neg {
pos--
buf[pos] = '-'
}
return string(buf[pos:])
}
// atoi parses a non-negative decimal integer, returning -1 on any error.
func atoi(s string) int {
if s == "" {
return -1
}
n := 0
for _, r := range s {
if r < '0' || r > '9' {
return -1
}
n = n*10 + int(r-'0')
}
return n
}
+510
View File
@@ -0,0 +1,510 @@
package xlsxtranslate
import (
"archive/zip"
"bytes"
"context"
"fmt"
"regexp"
"sort"
"strings"
"time"
)
// Translator translates one batch of already-masked Chinese strings and must
// return exactly len(texts) results in order. The engine owns masking,
// glossary and dedup; the implementation only talks to the LLM.
type Translator interface {
TranslateBatch(ctx context.Context, texts []string) ([]string, error)
}
// Options tunes the pipeline. Zero values select the defaults documented on
// each field.
type Options struct {
// BatchSize is the number of strings sent to the LLM per call.
// Default 40.
BatchSize int
// MaxUnitRunes caps a single translatable text unit. Longer units are
// left untranslated and reported, so one oversized cell cannot blow up
// an LLM call. Default 6000.
MaxUnitRunes int
// NormalizeOutputPunctuation converts full-width punctuation in newly
// translated strings to ASCII. Default true.
NormalizeOutputPunctuation *bool
// ExtraGlossary overrides the built-in glossary (same exact-match
// lookup semantics).
ExtraGlossary map[string]string
}
func (o *Options) batchSize() int {
if o != nil && o.BatchSize > 0 {
return o.BatchSize
}
return 40
}
func (o *Options) maxUnitRunes() int {
if o != nil && o.MaxUnitRunes > 0 {
return o.MaxUnitRunes
}
return 6000
}
func (o *Options) normalizePunctuation() bool {
if o != nil && o.NormalizeOutputPunctuation != nil {
return *o.NormalizeOutputPunctuation
}
return true
}
func (o *Options) lookupGlossary(s string) string {
if o == nil || len(o.ExtraGlossary) == 0 {
return lookupGlossary(s)
}
if v, ok := o.ExtraGlossary[s]; ok {
return v
}
if v, ok := o.ExtraGlossary[trimForGlossary(s)]; ok {
return v
}
return lookupGlossary(s)
}
func trimForGlossary(s string) string { return trimSpaceASCII(s) }
// Report summarises one translation run for the operator and the agent.
type Report struct {
ZipEntries int // zip entries in the output package (== input)
TextCells int // sharedStrings si blocks scanned
InlineTextCells int // worksheet inlineStr is blocks scanned
DrawingBodies int // txBody blocks scanned in drawings/charts
TranslatedUnits int // unique CJK text units queued for translation
AppliedTranslations int // unique units actually resolved
GlossaryHits int // units resolved from the glossary
LLMCalls int // LLM batch calls issued
RemainingCJKUnits int // unique units skipped (oversized)
ResidualCJKCount int // CJK ideographs still present in output text nodes
ResidualCJKSamples []string // up to 20 residual samples
FullWidthLeftovers int // full-width punctuation nodes left in output
NumberMismatches []string // numeric literals that changed (should be empty)
PartMismatches []string // part tokens that changed (should be empty)
Warnings []string
DurationMs int64
}
// Markdown renders the report for chat display.
func (r *Report) Markdown() string {
var b strings.Builder
fmt.Fprintf(&b, "**翻译完成**(耗时 %dms)\n\n", r.DurationMs)
b.WriteString("| 项目 | 数值 |\n|---|---|\n")
fmt.Fprintf(&b, "| zip 条目 | %d |\n", r.ZipEntries)
fmt.Fprintf(&b, "| 扫描:单元格文本 / 内联文本 / 文本框 | %d / %d / %d |\n",
r.TextCells, r.InlineTextCells, r.DrawingBodies)
fmt.Fprintf(&b, "| 翻译单元(去重后) | %d(术语库命中 %d,LLM 批次 %d 次) |\n",
r.TranslatedUnits, r.GlossaryHits, r.LLMCalls)
fmt.Fprintf(&b, "| 残留中文 | %d 处 |\n", r.ResidualCJKCount)
fmt.Fprintf(&b, "| 数字 / 料号改动 | %d / %d 处 |\n", len(r.NumberMismatches), len(r.PartMismatches))
if len(r.ResidualCJKSamples) > 0 {
b.WriteString("\n残留样例:\n")
for _, s := range r.ResidualCJKSamples {
fmt.Fprintf(&b, "- %s\n", truncate(s, 60))
}
}
if r.FullWidthLeftovers > 0 {
fmt.Fprintf(&b, "\n全角标点残留 %d 处(未影响翻译,提示性)\n", r.FullWidthLeftovers)
}
for _, w := range r.Warnings {
fmt.Fprintf(&b, "\n⚠️ %s\n", w)
}
return b.String()
}
func truncate(s string, n int) string {
s = strings.ReplaceAll(s, "\n", "\\n")
runes := []rune(s)
if len(runes) > n {
return string(runes[:n]) + "…"
}
return s
}
// sharedStringsEntry is the canonical path of the shared string table.
const sharedStringsEntry = "xl/sharedStrings.xml"
var (
siBlockRe = regexp.MustCompile(`(?s)<si(?:/>|>.*?</si>)`)
isBlockRe = regexp.MustCompile(`(?s)<is(?:/>|>.*?</is>)`)
rPhRe = regexp.MustCompile(`(?s)<rPh(?:/>|>.*?</rPh>)`)
tTagRe = regexp.MustCompile(`(?s)<t(?:\s[^>]*)?>(.*?)</t>`)
txBodyRe = regexp.MustCompile(`(?s)<[A-Za-z0-9]+:txBody[^>]*>.*?</[A-Za-z0-9]+:txBody>`)
paraRe = regexp.MustCompile(`(?s)<a:p(?:\s[^>]*)?>.*?</a:p>`)
aTTagRe = regexp.MustCompile(`(?s)<a:t(?:\s[^>]*)?>(.*?)</a:t>`)
)
// editKind distinguishes the run that carries the unit translation from the
// sibling runs that are emptied (their <rPr>/<a:rPr> styling is preserved).
type editKind int
const (
editCarrier editKind = iota
editClear
)
// locatedEdit is one byte-range rewrite on an entry. tag is the element name
// as written in the document ("t" or "a:t").
type locatedEdit struct {
start, end int
kind editKind
unitIdx int
tag string
}
// scanJob holds everything to rewrite for one zip entry.
type scanJob struct {
entry int
units []string // translatable CJK unit texts, scan order
edits []locatedEdit // byte ranges, scan order
}
// Translate runs the full pipeline over an in-memory .xlsx package and
// returns the translated package bytes together with the verification report.
//
// Passes:
// 1. collect CJK text units (sharedStrings, inlineStr sheets, drawings,
// charts) with their byte spans
// 2. resolve translations: glossary first, then deduplicated LLM batches
// 3. rewrite the affected entries and repack byte-for-byte otherwise
// 4. hard-verify the output package
func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([]byte, *Report, error) {
started := time.Now()
if tr == nil {
return nil, nil, fmt.Errorf("translator is required")
}
if opt == nil {
opt = &Options{}
}
report := &Report{ResidualCJKSamples: []string{}}
reader, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
return nil, nil, fmt.Errorf("not a valid xlsx (zip) package: %w", err)
}
// ---- Pass 1: collect translatable units per entry ----
entryData := make([][]byte, len(reader.File))
jobs := map[int]*scanJob{}
for i, f := range reader.File {
raw, err := readZip(f)
if err != nil {
return nil, nil, fmt.Errorf("read %s: %w", f.Name, err)
}
entryData[i] = raw
switch {
case f.Name == sharedStringsEntry:
job, scanned := scanStringBlocks(string(raw), siBlockRe, "t")
report.TextCells += scanned
if len(job.units) > 0 {
job.entry = i
jobs[i] = job
}
case isSheetXML(f.Name):
job, scanned := scanStringBlocks(string(raw), isBlockRe, "t")
report.InlineTextCells += scanned
if len(job.units) > 0 {
job.entry = i
jobs[i] = job
}
case isDrawingXML(f.Name):
job, bodies := scanDrawing(string(raw))
report.DrawingBodies += bodies
if len(job.units) > 0 {
job.entry = i
jobs[i] = job
}
}
}
// Deduplicate across entries, preserving first-seen order.
unitOrder := []string{}
unitSeen := map[string]struct{}{}
for _, job := range jobs {
for _, u := range job.units {
if _, ok := unitSeen[u]; !ok {
unitSeen[u] = struct{}{}
unitOrder = append(unitOrder, u)
}
}
}
// Oversized units are skipped rather than risking a broken LLM call.
unique := make([]string, 0, len(unitOrder))
for _, text := range unitOrder {
if len([]rune(text)) > opt.maxUnitRunes() {
report.RemainingCJKUnits++
report.Warnings = append(report.Warnings, fmt.Sprintf(
"文本单元超长(超过 %d 字符)未翻译,已保留原文:%s",
opt.maxUnitRunes(), truncate(text, 40)))
continue
}
unique = append(unique, text)
}
report.TranslatedUnits = len(unique)
// ---- Pass 2: resolve translations (glossary first, then LLM) ----
translations := map[string]string{}
for _, src := range unique {
if v := opt.lookupGlossary(src); v != "" {
if opt.normalizePunctuation() {
v = normalizePunctuation(v)
}
translations[src] = v
report.GlossaryHits++
}
}
todo := make([]string, 0, len(unique))
for _, src := range unique {
if _, ok := translations[src]; !ok {
todo = append(todo, src)
}
}
for lo := 0; lo < len(todo); lo += opt.batchSize() {
hi := lo + opt.batchSize()
if hi > len(todo) {
hi = len(todo)
}
batch := todo[lo:hi]
masked := make([]string, len(batch))
tokens := make([][]string, len(batch))
for i, src := range batch {
masked[i], tokens[i] = mask(src)
}
out, err := tr.TranslateBatch(ctx, masked)
if err != nil {
return nil, report, fmt.Errorf("LLM batch %d failed: %w", lo/opt.batchSize()+1, err)
}
if len(out) != len(batch) {
return nil, report, fmt.Errorf("LLM batch %d returned %d results for %d inputs",
lo/opt.batchSize()+1, len(out), len(batch))
}
report.LLMCalls++
for i, dst := range out {
restored, miss := unmask(dst, tokens[i])
if len(miss) > 0 {
report.Warnings = append(report.Warnings, fmt.Sprintf(
"译文存在未能回填的占位符,请人工复核:%s", truncate(batch[i], 40)))
}
if opt.normalizePunctuation() {
restored = normalizePunctuation(restored)
}
translations[batch[i]] = restored
}
}
report.AppliedTranslations = len(translations)
// ---- Pass 3: rewrite affected entries, repack in original order ----
type outEntry struct {
idx int
data []byte
}
out := make([]outEntry, 0, len(reader.File))
for i := range reader.File {
data := entryData[i]
if job, ok := jobs[i]; ok {
data = []byte(applyJob(string(data), job, translations))
}
out = append(out, outEntry{idx: i, data: data})
}
sort.SliceStable(out, func(a, b int) bool { return out[a].idx < out[b].idx })
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, e := range out {
src := reader.File[e.idx]
w, err := zw.CreateHeader(&zip.FileHeader{
Name: src.FileHeader.Name,
Method: src.FileHeader.Method,
Modified: src.FileHeader.Modified,
})
if err != nil {
return nil, nil, fmt.Errorf("zip create %s: %w", src.FileHeader.Name, err)
}
if _, err := w.Write(e.data); err != nil {
return nil, nil, fmt.Errorf("zip write %s: %w", src.FileHeader.Name, err)
}
}
if err := zw.Close(); err != nil {
return nil, nil, fmt.Errorf("zip close: %w", err)
}
report.ZipEntries = len(out)
// ---- Pass 4: hard verification on the OUTPUT package ----
verify(buf.Bytes(), data, report)
report.DurationMs = time.Since(started).Milliseconds()
return buf.Bytes(), report, nil
}
// scanStringBlocks finds CJK text inside <si>/<is> blocks. Every block counts
// towards the scanned total; blocks whose joined <t> text contains CJK become
// units with one carrier edit (first <t>) and one clear edit per sibling <t>.
// Phonetic <rPh> hints are excluded from both joining and editing.
func scanStringBlocks(src string, blockRe *regexp.Regexp, tag string) (*scanJob, int) {
job := &scanJob{}
scanned := 0
for _, loc := range blockRe.FindAllStringIndex(src, -1) {
scanned++
blockStart := loc[0]
block := src[loc[0]:loc[1]]
// Phonetic runs must not join into the cell text nor be edited.
type span struct{ start, end int }
var rph []span
for _, loc := range rPhRe.FindAllStringIndex(block, -1) {
rph = append(rph, span{loc[0], loc[1]})
}
inRPh := func(pos int) bool {
for _, s := range rph {
if pos >= s.start && pos < s.end {
return true
}
}
return false
}
matches := tTagRe.FindAllStringSubmatchIndex(block, -1)
var unitText strings.Builder
live := 0
for _, m := range matches {
if inRPh(m[0]) {
continue
}
unitText.WriteString(unescapeXMLText(block[m[2]:m[3]]))
live++
}
if live == 0 || !hasCJK(unitText.String()) {
continue
}
unitIdx := len(job.units)
job.units = append(job.units, unitText.String())
first := true
for _, m := range matches {
if inRPh(m[0]) {
continue
}
kind := editClear
if first {
kind = editCarrier
first = false
}
job.edits = append(job.edits, locatedEdit{
start: blockStart + m[0],
end: blockStart + m[1],
kind: kind,
unitIdx: unitIdx,
tag: tag,
})
}
}
return job, scanned
}
// scanDrawing finds CJK text inside drawing/chart text bodies. The unit is
// one <a:p> paragraph: its <a:t> runs are joined (spreadsheet text boxes
// split words across runs), translated as one, and written back to the first
// run.
func scanDrawing(src string) (*scanJob, int) {
job := &scanJob{}
bodies := 0
for _, bodyLoc := range txBodyRe.FindAllStringIndex(src, -1) {
bodies++
bodyStart := bodyLoc[0]
body := src[bodyLoc[0]:bodyLoc[1]]
for _, paraLoc := range paraRe.FindAllStringIndex(body, -1) {
paraStart := paraLoc[0]
para := body[paraLoc[0]:paraLoc[1]]
matches := aTTagRe.FindAllStringSubmatchIndex(para, -1)
if len(matches) == 0 {
continue
}
var unitText strings.Builder
for _, m := range matches {
unitText.WriteString(unescapeXMLText(para[m[2]:m[3]]))
}
if !hasCJK(unitText.String()) {
continue
}
unitIdx := len(job.units)
job.units = append(job.units, unitText.String())
first := true
for _, m := range matches {
kind := editClear
if first {
kind = editCarrier
first = false
}
job.edits = append(job.edits, locatedEdit{
start: bodyStart + paraStart + m[0],
end: bodyStart + paraStart + m[1],
kind: kind,
unitIdx: unitIdx,
tag: "a:t",
})
}
}
}
return job, bodies
}
// applyJob rewrites one entry with the resolved translations. Bytes outside
// the recorded edits — styles, geometry, image references — are untouched.
func applyJob(src string, job *scanJob, translations map[string]string) string {
type repl struct {
start, end int
text string
}
repls := make([]repl, 0, len(job.edits))
for _, e := range job.edits {
switch e.kind {
case editCarrier:
t, ok := translations[job.units[e.unitIdx]]
if !ok {
continue // oversized/skipped unit: keep the original bytes
}
repls = append(repls, repl{e.start, e.end,
"<" + e.tag + ` xml:space="preserve">` + escapeXMLText(t) + "</" + e.tag + ">"})
case editClear:
repls = append(repls, repl{e.start, e.end, "<" + e.tag + "></" + e.tag + ">"})
}
}
if len(repls) == 0 {
return src
}
sort.SliceStable(repls, func(a, b int) bool { return repls[a].start > repls[b].start })
out := src
for _, r := range repls {
out = out[:r.start] + r.text + out[r.end:]
}
return out
}
// readZip reads one entry fully.
func readZip(f *zip.File) ([]byte, error) {
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
var buf bytes.Buffer
if _, err := buf.ReadFrom(rc); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func isSheetXML(name string) bool {
return strings.HasPrefix(name, "xl/worksheets/sheet") && strings.HasSuffix(name, ".xml")
}
func isDrawingXML(name string) bool {
if strings.HasPrefix(name, "xl/drawings/drawing") && strings.HasSuffix(name, ".xml") {
return true
}
return strings.HasPrefix(name, "xl/charts/") && strings.HasSuffix(name, ".xml") &&
!strings.Contains(name, "_rels/")
}
+442
View File
@@ -0,0 +1,442 @@
package xlsxtranslate
import (
"archive/zip"
"bytes"
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// stripCJK replaces every run of CJK ideographs and CJK/full-width
// punctuation with a single space, keeping placeholders, numbers and ASCII
// text intact at their original token boundaries — the deterministic
// behaviour the real LLM is asked for by the system prompt.
func stripCJK(s string) string {
var b strings.Builder
inCJK := false
for _, r := range s {
if isCJKOrFullWidth(r) {
inCJK = true
continue
}
if inCJK {
b.WriteByte(' ')
inCJK = false
}
b.WriteRune(r)
}
if inCJK {
b.WriteByte(' ')
}
return b.String()
}
// isCJKOrFullWidth reports whether r is a CJK ideograph or a CJK punctuation
// / full-width form that a translation would replace.
func isCJKOrFullWidth(r rune) bool {
switch {
case r >= 0x3400 && r <= 0x9FFF, r >= 0xF900 && r <= 0xFAFF:
return true
case r >= 0x3000 && r <= 0x303F, r >= 0xFF01 && r <= 0xFF5E:
return true
case r >= 0x2018 && r <= 0x201D, r == 0x2026:
return true
}
return false
}
// fakeTranslator is a deterministic Translator stub.
type fakeTranslator struct {
calls int
fail error
respond func(masked string, seq int) string
}
func (f *fakeTranslator) TranslateBatch(_ context.Context, texts []string) ([]string, error) {
if f.fail != nil {
return nil, f.fail
}
out := make([]string, len(texts))
for i, m := range texts {
if f.respond != nil {
out[i] = f.respond(m, f.calls*1000+i)
} else {
out[i] = stripCJK(m)
}
}
f.calls++
return out, nil
}
const fixtureSharedStrings = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<sst xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" count="6" uniqueCount="6">
<si><t>螺母</t></si>
<si><r><rPr><b/></rPr><t>接地区域</t></r><r><t>铜箔纸取消</t></r></si>
<si><t>Assembly Process</t></si>
<si><t>底板平面度 <1.0mm</t></si>
<si><t>螺母</t></si>
<si><t>检查 &amp; 包装 &lt;OK&gt;</t></si>
</sst>`
const fixtureDrawing = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xdr:wsDr xmlns:xdr="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<xdr:twoCellAnchor>
<xdr:sp macro="" textlink="">
<xdr:txBody>
<a:bodyPr vertOverflow="clip"/>
<a:p><a:r><a:rPr lang="zh-CN"/><a:t>万向</a:t></a:r><a:r><a:t>轮</a:t></a:r></a:p>
<a:p><a:r><a:t>Caster</a:t></a:r></a:p>
</xdr:txBody>
</xdr:sp>
</xdr:twoCellAnchor>
</xdr:wsDr>`
const fixtureSheet = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>检验工具</t></is></c></row></sheetData>
</worksheet>`
// buildTestXlsx assembles a minimal but structurally faithful workbook.
func buildTestXlsx(t *testing.T) []byte {
t.Helper()
files := map[string][]byte{
"[Content_Types].xml": []byte(`<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="a"/><Default Extension="xml" ContentType="b"/></Types>`),
"_rels/.rels": []byte(`<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"/>`),
"xl/workbook.xml": []byte(`<?xml version="1.0"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheets><sheet name="AR1.2 48U 组装(CN)" sheetId="1"/></sheets></workbook>`),
"xl/sharedStrings.xml": []byte(fixtureSharedStrings),
"xl/worksheets/sheet1.xml": []byte(fixtureSheet),
"xl/drawings/drawing1.xml": []byte(fixtureDrawing),
"xl/media/image1.png": {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xDE, 0xAD, 0xBE, 0xEF},
}
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
names := []string{
"[Content_Types].xml", "_rels/.rels", "xl/workbook.xml",
"xl/sharedStrings.xml", "xl/worksheets/sheet1.xml",
"xl/drawings/drawing1.xml", "xl/media/image1.png",
}
for _, name := range names {
w, err := zw.Create(name)
if err != nil {
t.Fatalf("zip create: %v", err)
}
if _, err := w.Write(files[name]); err != nil {
t.Fatalf("zip write: %v", err)
}
}
if err := zw.Close(); err != nil {
t.Fatalf("zip close: %v", err)
}
return buf.Bytes()
}
func zipEntry(t *testing.T, data []byte, name string) []byte {
t.Helper()
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open zip: %v", err)
}
for _, f := range r.File {
if f.Name == name {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read %s: %v", name, err)
}
return raw
}
}
t.Fatalf("entry %s not found", name)
return nil
}
func TestTranslateSharedStringsDrawingsAndInline(t *testing.T) {
in := buildTestXlsx(t)
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), in, &Options{BatchSize: 2}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if tr.calls == 0 {
t.Fatalf("expected LLM batches to run")
}
// Structure: entry count and media bytes unchanged.
rIn, _ := zip.NewReader(bytes.NewReader(in), int64(len(in)))
rOut, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output not a valid zip: %v", err)
}
if len(rIn.File) != len(rOut.File) {
t.Fatalf("entry count changed: %d -> %d", len(rIn.File), len(rOut.File))
}
inMedia := zipEntry(t, in, "xl/media/image1.png")
outMedia := zipEntry(t, out, "xl/media/image1.png")
if !bytes.Equal(inMedia, outMedia) {
t.Fatalf("media bytes altered")
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if hasCJK(ss) {
t.Fatalf("sharedStrings still contains CJK:\n%s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("non-CJK shared string was altered:\n%s", ss)
}
// Both duplicate 螺母 blocks must be rewritten.
if got := strings.Count(ss, "xml:space=\"preserve\""); got != 5 {
t.Fatalf("expected 5 carrier <t> rewrites, got %d:\n%s", got, ss)
}
// Entity content round-trips: unescaped before translation, correctly
// re-escaped on write-back.
if !strings.Contains(ss, "&amp;") || !strings.Contains(ss, "&lt;OK&gt;") {
t.Fatalf("translated text not re-escaped for XML:\n%s", ss)
}
// Numbers inside a translated unit survive (placeholder protection).
if !strings.Contains(ss, "1.0mm") {
t.Fatalf("numeric token lost in translation:\n%s", ss)
}
// Rich-text sibling run cleared, style run preserved in the sibling.
if !strings.Contains(ss, "<r><rPr><b/></rPr>") {
t.Fatalf("rich text run structure dropped:\n%s", ss)
}
dw := string(zipEntry(t, out, "xl/drawings/drawing1.xml"))
if hasCJK(dw) {
t.Fatalf("drawing still contains CJK:\n%s", dw)
}
// Split runs joined into the first run's translation.
if !strings.Contains(dw, "<a:t xml:space=\"preserve\">") {
t.Fatalf("carrier a:t not written:\n%s", dw)
}
if strings.Contains(dw, ">Caster<") == false {
t.Fatalf("non-CJK paragraph altered:\n%s", dw)
}
sh := string(zipEntry(t, out, "xl/worksheets/sheet1.xml"))
if hasCJK(sh) {
t.Fatalf("inline string not translated:\n%s", sh)
}
if report.ResidualCJKCount != 0 {
t.Fatalf("residual CJK reported: %d %v", report.ResidualCJKCount, report.ResidualCJKSamples)
}
if len(report.NumberMismatches) != 0 || len(report.PartMismatches) != 0 {
t.Fatalf("integrity check failed: %v %v", report.NumberMismatches, report.PartMismatches)
}
if report.TranslatedUnits == 0 || report.GlossaryHits == 0 {
t.Fatalf("unexpected counts: units=%d glossary=%d", report.TranslatedUnits, report.GlossaryHits)
}
// 螺母 is a glossary hit; the LLM must not have been asked for it — the
// glossary value must appear verbatim.
if !strings.Contains(ss, "NUT") {
t.Fatalf("glossary hit not applied:\n%s", ss)
}
}
func TestTranslateNoCJKLeavesPackageUntouched(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, f := range []struct{ name, body string }{
{"[Content_Types].xml", "<Types/>"},
{"xl/sharedStrings.xml", `<sst xmlns="x"><si><t>Assembly Process</t></si></sst>`},
} {
w, _ := zw.Create(f.name)
w.Write([]byte(f.body))
}
zw.Close()
in := buf.Bytes()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), in, nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if tr.calls != 0 || report.TranslatedUnits != 0 {
t.Fatalf("unexpected work: calls=%d units=%d", tr.calls, report.TranslatedUnits)
}
// Repackaging may differ at the container level (compression, header
// flags), but every entry's content must be byte-identical.
inR, err := zip.NewReader(bytes.NewReader(in), int64(len(in)))
if err != nil {
t.Fatalf("input zip: %v", err)
}
outR, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
if len(inR.File) != len(outR.File) {
t.Fatalf("entry count changed: %d -> %d", len(inR.File), len(outR.File))
}
for i, f := range inR.File {
inRaw, err := readZip(f)
if err != nil {
t.Fatalf("read input %s: %v", f.Name, err)
}
outRaw, err := readZip(outR.File[i])
if err != nil {
t.Fatalf("read output %s: %v", f.Name, err)
}
if !bytes.Equal(inRaw, outRaw) {
t.Fatalf("entry %s was modified although it contains no CJK", f.Name)
}
}
}
func TestTranslateNormalizesFullWidthPunctuation(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
w.Write([]byte(`<sst xmlns="x"><si><t>重点检验:</t></si></sst>`))
zw.Close()
tr := &fakeTranslator{respond: func(masked string, _ int) string {
return "Key inspection:" // deliberately full-width from the "LLM"
}}
out, _, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if !strings.Contains(ss, "Key inspection:") || strings.Contains(ss, ":") {
t.Fatalf("full-width punctuation not normalized: %s", ss)
}
}
func TestTranslateOversizedUnitIsSkippedAndReported(t *testing.T) {
long := strings.Repeat("长", 6000)
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
fmt.Fprintf(w, `<sst xmlns="x"><si><t>%s</t></si><si><t>短文本</t></si></sst>`, long)
zw.Close()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), buf.Bytes(), &Options{MaxUnitRunes: 100}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if !strings.Contains(ss, long) {
t.Fatalf("oversized unit was modified")
}
if report.RemainingCJKUnits != 1 || report.ResidualCJKCount != 1 {
t.Fatalf("oversized unit not reported: %+v", report)
}
if !strings.Contains(ss, stripCJK("短文本")) {
t.Fatalf("short unit not translated alongside skipped unit:\n%s", truncate(ss, 200))
}
}
func TestVerifyReportsBadTranslator(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, _ := zw.Create("xl/sharedStrings.xml")
w.Write([]byte(`<sst xmlns="x"><si><t>螺母 M8 检查 573.5</t></si></sst>`))
zw.Close()
// Translator that "forgets" to translate: residual must be reported.
tr := &fakeTranslator{respond: func(m string, _ int) string { return m }}
out, report, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if report.ResidualCJKCount != 1 {
t.Fatalf("residual not detected: %+v", report)
}
_ = out
}
func TestRealSIPRegression(t *testing.T) {
root := os.Getenv("ACADEMY_REPO_ROOT")
if root == "" {
root = "../.."
}
path := filepath.Join(root, "docs", "D4-A08AR12000002-A3-SIP.xlsx")
data, err := os.ReadFile(path)
if err != nil {
t.Skipf("real SIP file not available: %v", err)
}
if len(data) < 10<<20 {
t.Fatalf("unexpectedly small SIP file: %d bytes", len(data))
}
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), data, &Options{BatchSize: 50}, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
rIn, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("input zip: %v", err)
}
rOut, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
if len(rIn.File) != len(rOut.File) {
t.Fatalf("entry count changed: %d -> %d", len(rIn.File), len(rOut.File))
}
// Every media byte must be identical.
inBytName := map[string][]byte{}
for _, f := range rIn.File {
if strings.HasPrefix(f.Name, "xl/media/") {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read media: %v", err)
}
inBytName[f.Name] = raw
}
}
for _, f := range rOut.File {
if strings.HasPrefix(f.Name, "xl/media/") {
raw, err := readZip(f)
if err != nil {
t.Fatalf("read media out: %v", err)
}
if !bytes.Equal(inBytName[f.Name], raw) {
t.Fatalf("media %s altered", f.Name)
}
}
}
// Merged-cell structure of the sheets must be untouched.
countMerges := func(d []byte) int { return strings.Count(string(d), "<mergeCell") }
for i, f := range rIn.File {
if isSheetXML(f.Name) {
rawIn, _ := readZip(f)
rawOut, err := readZip(rOut.File[i])
if err != nil {
t.Fatalf("read out sheet: %v", err)
}
if countMerges(rawIn) != countMerges(rawOut) {
t.Fatalf("%s merge count changed: %d -> %d", f.Name, countMerges(rawIn), countMerges(rawOut))
}
}
}
if report.ResidualCJKCount != 0 {
t.Fatalf("residual CJK in real SIP: %d samples=%v", report.ResidualCJKCount, report.ResidualCJKSamples)
}
if len(report.NumberMismatches) != 0 || len(report.PartMismatches) != 0 {
t.Fatalf("integrity check failed on real SIP: numbers=%v parts=%v",
report.NumberMismatches[:min(5, len(report.NumberMismatches))],
report.PartMismatches[:min(5, len(report.PartMismatches))])
}
if report.TranslatedUnits < 200 {
t.Fatalf("unexpectedly few units translated: %d", report.TranslatedUnits)
}
t.Logf("real SIP regression OK: %s", report.Markdown())
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+246
View File
@@ -0,0 +1,246 @@
package xlsxtranslate
import "strings"
// glossary holds the mandatory translation pairs. Values here were harvested
// from the shipped bilingual SIP workbook (D4-A08AR12000002-A3), where the
// English sheet has been maintained for 11 revisions — they are confirmed
// translations, not suggestions. Glossary hits short-circuit the LLM.
//
// Lookup is exact first, then trimmed, then whitespace-insensitive for short
// strings, because layout padding such as "客 戶 " is part of the
// stored text but not part of the term.
var glossary = map[string]string{
// Company and document identity
"苏州和信精密科技有限公司": "WTP TECHNOLOGY (SUZHOU) CO., LTD.",
"苏州和信精密科技有限公司 ": "WTP TECHNOLOGY (SUZHOU) CO., LTD.",
"组装检验标准": "Assembly Process SIP",
"检验标准": "Inspection Standard",
"标准": "Standard",
"SIP版次:": "SIP REV:",
"SIP版次": "SIP REV",
"版本": "Version",
"版本号": "Version No.",
"日期": "Date",
"备注": "Comments",
"新制定": "First released",
"修订页面": "Where",
"主要修订内容": "Revised content",
"修改人": "Revised",
"修订历史": "Revision History",
"履历": "History",
// Header field labels (traditional variants included on purpose — the
// source mixes simplified and traditional forms)
"客户": "Customer",
"客戶": "Customer",
"机种": "Model",
"機種": "Model",
"序号": "No.",
"序號": "No.",
"品名": "Part Name",
"页次": "Page",
"頁次": "Page",
"页码": "Page",
"制作单位": "Division",
"抽样计划": "Sampling Plan",
"抽樣計劃": "Sampling Plan",
"依MIL-STD-1916表 主抽樣表": "Per MIL-STD-1916 main sampling table",
"检验项目": "Inspection Item",
"檢驗項目": "Inspection Item",
"规格说明": "Specification",
"規格說明": "Specification",
"检验工具": "Inspection Tools",
"檢驗工具": "Inspection Tools",
"检验频率": "Inspection Frequency",
"檢驗頻率": "Inspection Frequency",
"首件": "First Piece",
"末件": "Last Piece",
"首/末件": "First/Last Piece",
"巡检": "Patrol Inspection",
"巡檢": "Patrol Inspection",
"基本信息": "Basic Information",
"结构": "Structure",
"結構": "Structure",
"尺寸": "Dimensions",
"外观": "Appearance",
"外觀": "Appearance",
"目视": "Visual",
"目視": "Visual",
"等级": "Class",
"等级面划分": "Class surface division",
"重点检验": "Key inspections",
"重點檢驗": "Key inspections",
"检验条件": "Inspection conditions",
"檢驗條件": "Inspection conditions",
// Common hardware and inspection nouns seen in the drawing text boxes
"螺母": "NUT",
"螺丝": "SCREW",
"螺钉": "SCREW",
"螺栓": "BOLT",
"万向轮": "Caster",
"腳杯": "Leveling Foot",
"脚杯": "Leveling Foot",
"接地": "Grounding",
"接地区域": "Grounding area",
"接地螺丝": "Grounding screw",
"接地螺絲": "Grounding screw",
"支撑件": "Support",
"支撐件": "Support",
"水平仪": "Spirit level",
"钢直尺": "Steel ruler",
"鋼直尺": "Steel ruler",
"卷尺": "Tape measure",
"塞尺": "Feeler gauge",
"检具": "Inspection gauge",
"檢具": "Inspection gauge",
"手电筒": "Flashlight",
"手电筒/目视/手触摸": "Flashlight/Visual/Touch by hand",
"手触摸": "Touch by hand",
"对角线": "Diagonal",
"對角線": "Diagonal",
"平面度": "Flatness",
"平行度": "Parallelism",
"底板平面度": "Bottom plate flatness",
"顶板平面度": "Top plate flatness",
"外宽": "Outer width",
"內宽": "Inner width",
"内宽": "Inner width",
"前门": "Front door",
"后门": "Rear door",
"前門": "Front door",
"後門": "Rear door",
"侧板": "Side panel",
"側板": "Side panel",
"顶板": "Top panel",
"底板": "Bottom panel",
"立柱": "Vertical post",
"螺纹孔": "Threaded hole",
"螺紋孔": "Threaded hole",
"方孔": "Square hole",
"葫芦孔": "Keyhole",
"焊道": "Weld bead",
"焊点": "Weld point",
"铜箔纸": "Copper foil paper",
"防烤胶带": "High-temperature tape",
"标签": "Label",
"標籤": "Label",
"SN标签": "SN label",
"机柜": "Rack",
"機櫃": "Rack",
"机柜本体": "Rack body",
"包装": "Packing",
"出厂检验": "Outgoing inspection",
"出货检验": "Outgoing inspection",
"组装": "Assembly",
"組裝": "Assembly",
"检验": "Inspection",
"檢驗": "Inspection",
"检查": "Check",
"客诉": "Customer complaint",
"客訴": "Customer complaint",
"异常": "Abnormal",
"異常": "Abnormal",
"变形": "Deformation",
"变形、刮伤": "Deformation or scratch",
"刮伤": "Scratch",
"划伤": "Scratch",
"生锈": "Rusty",
"生鏽": "Rusty",
"锈斑": "Rust spot",
"毛刺": "Burr",
"氧化": "Oxidation",
"脏污": "Stain",
"人员": "Operator",
"部门": "Department",
"日期 ": "Date ",
"审核": "Reviewed by",
"核准": "Approved by",
"编制": "Prepared by",
"批准": "Approved by",
"签名": "Signature",
"其他": "Others",
"其它": "Others",
"左侧": "Left side",
"右侧": "Right side",
"前面": "Front",
"后面": "Rear",
"顶部": "Top",
"底部": "Bottom",
"内部": "Inside",
"外部": "Outside",
"左侧面": "Left side panel",
"右侧面": "Right side panel",
"正面": "Front surface",
"背面": "Rear surface",
"水平距离": "Horizontal distance",
"间距": "Distance",
"間距": "Distance",
"高度": "Height",
"宽度": "Width",
"厚度": "Thickness",
"深度": "Depth",
"数量": "Quantity",
"位置": "Position",
"序号 ": "No. ",
"工单": "Work order",
"图纸": "Drawing",
"图面": "Drawing",
"图號": "Drawing No.",
"图号": "Drawing No.",
"料号": "Part number",
"料號": "Part number",
"版本进阶": "Version upgrade",
"资料": "Document",
"資料": "Document",
"照片": "Photo",
"图片": "Picture",
"图片、": "Pictures, ",
"说明": "Description",
"說明": "Description",
"要求": "Requirement",
"標準視力": "Standard vision",
"视力": "Vision",
"目視距離": "Viewing distance",
"检验角度": "Inspection angle",
"目视时间": "Viewing time",
"使用者在正常操作状态下": "in normal operation, the user",
"一直会看到的面": "surface that is always visible",
"有时会看到的面": "surface that is sometimes visible",
"较少会看到的面": "surface that is rarely visible",
"不会看到的面": "surface that is never visible",
}
// glossaryMaxLooseLookup bounds the whitespace-insensitive lookup: stripping
// all whitespace is only safe for short label-like strings.
const glossaryMaxLooseLookup = 40
// glossaryLooseIndex maps whitespace-stripped keys to values, built once.
var glossaryLooseIndex = buildLooseIndex()
func buildLooseIndex() map[string]string {
idx := make(map[string]string, len(glossary))
for k, v := range glossary {
idx[whitespaceKey(k)] = v
}
return idx
}
// lookupGlossary resolves s through the glossary: exact match, then trimmed,
// then whitespace-insensitive for short label-like strings. Returns "" on miss.
func lookupGlossary(s string) string {
if v, ok := glossary[s]; ok {
return v
}
trimmed := strings.TrimSpace(s)
if trimmed != s {
if v, ok := glossary[trimmed]; ok {
return v
}
}
if len([]rune(s)) <= glossaryMaxLooseLookup {
if v, ok := glossaryLooseIndex[whitespaceKey(s)]; ok {
return v
}
}
return ""
}
+139
View File
@@ -0,0 +1,139 @@
package xlsxtranslate
import (
"archive/zip"
"bytes"
"fmt"
"regexp"
"sort"
"strings"
)
// verify is the hard gate from the plan: residual Chinese must be zero,
// numeric/part tokens must be byte-identical to the input, and the package
// entry count must not change. Everything is reported; nothing here mutates
// the output.
func verify(outData, inData []byte, report *Report) {
outReader, err := zip.NewReader(bytes.NewReader(outData), int64(len(outData)))
if err != nil {
report.Warnings = append(report.Warnings, "输出包无法读回校验:"+err.Error())
return
}
inReader, err := zip.NewReader(bytes.NewReader(inData), int64(len(inData)))
if err != nil {
report.Warnings = append(report.Warnings, "输入包无法读回校验:"+err.Error())
return
}
if len(outReader.File) != len(inReader.File) {
report.Warnings = append(report.Warnings, fmt.Sprintf(
"zip 条目数变化:输入 %d,输出 %d", len(inReader.File), len(outReader.File)))
}
report.ZipEntries = len(outReader.File)
outTexts := collectPackageTexts(outReader)
inTexts := collectPackageTexts(inReader)
// Residual CJK ideographs in output text nodes.
for _, t := range outTexts {
if hasCJK(t) {
report.ResidualCJKCount++
if len(report.ResidualCJKSamples) < 20 {
report.ResidualCJKSamples = append(report.ResidualCJKSamples, truncate(t, 80))
}
} else if cjkAny.MatchString(t) {
report.FullWidthLeftovers++
}
}
// Numeric and part-token equality between input and output.
if diff := multisetDiff(numberToken, inTexts, outTexts); len(diff) > 0 {
report.NumberMismatches = diff
}
if diff := multisetDiff(partToken, inTexts, outTexts); len(diff) > 0 {
report.PartMismatches = diff
}
}
// collectPackageTexts gathers the logical text units of a package: shared
// strings and inline strings joined per block, drawing/chart text joined per
// paragraph — the same aggregation the write-back uses. Token-level checks
// (numbers, part numbers) must aggregate identically on both sides, because
// rich-text runs may split a number such as "1.0" into "1" + ".0" and the
// merge changes bare token counts without any data change.
func collectPackageTexts(reader *zip.Reader) []string {
var texts []string
appendBlockText := func(block string) {
var b strings.Builder
for _, m := range tTagRe.FindAllStringSubmatchIndex(block, -1) {
b.WriteString(unescapeXMLText(block[m[2]:m[3]]))
}
if b.Len() > 0 {
texts = append(texts, b.String())
}
}
for _, f := range reader.File {
raw, err := readZip(f)
if err != nil {
continue
}
switch {
case f.Name == sharedStringsEntry || isSheetXML(f.Name):
re := siBlockRe
if f.Name != sharedStringsEntry {
re = isBlockRe
}
for _, loc := range re.FindAllStringIndex(string(raw), -1) {
appendBlockText(string(raw)[loc[0]:loc[1]])
}
case isDrawingXML(f.Name):
src := string(raw)
for _, bodyLoc := range txBodyRe.FindAllStringIndex(src, -1) {
body := src[bodyLoc[0]:bodyLoc[1]]
for _, paraLoc := range paraRe.FindAllStringIndex(body, -1) {
para := body[paraLoc[0]:paraLoc[1]]
var b strings.Builder
for _, m := range aTTagRe.FindAllStringSubmatchIndex(para, -1) {
b.WriteString(unescapeXMLText(para[m[2]:m[3]]))
}
if b.Len() > 0 {
texts = append(texts, b.String())
}
}
}
}
}
return texts
}
// multisetDiff compares token multisets extracted from input versus output
// texts and returns a stable list of "token (in->out)" descriptions for every
// token whose count changed.
func multisetDiff(re *regexp.Regexp, inTexts, outTexts []string) []string {
in := map[string]int{}
out := map[string]int{}
tokens := map[string]struct{}{}
for _, t := range inTexts {
for _, tok := range re.FindAllString(t, -1) {
in[tok]++
tokens[tok] = struct{}{}
}
}
for _, t := range outTexts {
for _, tok := range re.FindAllString(t, -1) {
out[tok]++
tokens[tok] = struct{}{}
}
}
var diffs []string
for tok := range tokens {
a, b := in[tok], out[tok]
if a != b {
diffs = append(diffs, fmt.Sprintf("%s (%d->%d)", tok, a, b))
}
}
sort.Strings(diffs)
if len(diffs) > 20 {
diffs = append(diffs[:20], fmt.Sprintf("… 共 %d 项", len(diffs)))
}
return diffs
}
+91
View File
@@ -0,0 +1,91 @@
package xlsxtranslate
import (
"strconv"
"strings"
)
// escapeXMLText escapes a plain string for use inside an XML text node.
// Quotes are left unescaped: they carry no special meaning in text content
// and Excel does not escape them either.
func escapeXMLText(s string) string {
if !strings.ContainsAny(s, "&<>") {
return s
}
var b strings.Builder
b.Grow(len(s) + 16)
for _, r := range s {
switch r {
case '&':
b.WriteString("&amp;")
case '<':
b.WriteString("&lt;")
case '>':
b.WriteString("&gt;")
default:
b.WriteRune(r)
}
}
return b.String()
}
// unescapeXMLText resolves the XML entities Excel may emit inside text
// nodes: the five predefined named entities and decimal/hex character
// references. Unknown entities are passed through untouched.
func unescapeXMLText(s string) string {
if !strings.ContainsRune(s, '&') {
return s
}
var b strings.Builder
b.Grow(len(s))
for i := 0; i < len(s); {
c := s[i]
if c != '&' {
b.WriteByte(c)
i++
continue
}
semi := strings.IndexByte(s[i:], ';')
if semi < 0 {
b.WriteByte(c)
i++
continue
}
entity := s[i+1 : i+semi]
if decoded, ok := decodeEntity(entity); ok {
b.WriteString(decoded)
i += semi + 1
continue
}
b.WriteByte(c)
i++
}
return b.String()
}
func decodeEntity(entity string) (string, bool) {
switch entity {
case "amp":
return "&", true
case "lt":
return "<", true
case "gt":
return ">", true
case "quot":
return "\"", true
case "apos":
return "'", true
}
if len(entity) > 1 && entity[0] == '#' {
if len(entity) > 2 && (entity[1] == 'x' || entity[1] == 'X') {
if n, err := strconv.ParseUint(entity[2:], 16, 32); err == nil {
return string(rune(n)), true
}
return "", false
}
if n, err := strconv.ParseUint(entity[1:], 10, 32); err == nil {
return string(rune(n)), true
}
}
return "", false
}
@@ -0,0 +1,78 @@
package xlsxtranslate
import (
"os"
"testing"
"gopkg.in/yaml.v3"
)
// TestValidateBuiltinAgentYAML parses the config YAMLs with plain yaml.v3 to
// verify the new SIP translator entries are structurally valid (no internal
// packages involved, so no gojieba init on this machine).
func TestValidateBuiltinAgentYAML(t *testing.T) {
raw, err := os.ReadFile("../../config/builtin_agents.yaml")
if err != nil {
t.Fatalf("read builtin_agents.yaml: %v", err)
}
var doc struct {
BuiltinAgents []map[string]any `yaml:"builtin_agents"`
}
if err := yaml.Unmarshal(raw, &doc); err != nil {
t.Fatalf("builtin_agents.yaml does not parse: %v", err)
}
var found map[string]any
for _, a := range doc.BuiltinAgents {
if id, _ := a["id"].(string); id == "builtin-sip-translator" {
found = a
break
}
}
if found == nil {
t.Fatalf("builtin-sip-translator entry not found")
}
for _, key := range []string{"avatar", "is_builtin", "i18n", "config"} {
if _, ok := found[key]; !ok {
t.Fatalf("entry missing key %q", key)
}
}
cfg := found["config"].(map[string]any)
for _, key := range []string{"agent_mode", "agent_type", "system_prompt_id", "supported_file_types", "allowed_tools"} {
if _, ok := cfg[key]; !ok {
t.Fatalf("config missing key %q", key)
}
}
tools, _ := cfg["allowed_tools"].([]any)
toolNames := map[string]bool{}
for _, tl := range tools {
if s, ok := tl.(string); ok {
toolNames[s] = true
}
}
if !toolNames["xlsx_translate"] {
t.Fatalf("allowed_tools does not include xlsx_translate")
}
promptRaw, err := os.ReadFile("../../config/prompt_templates/agent_system_prompt.yaml")
if err != nil {
t.Fatalf("read agent_system_prompt.yaml: %v", err)
}
var tpl struct {
Templates []map[string]any `yaml:"templates"`
}
if err := yaml.Unmarshal(promptRaw, &tpl); err != nil {
t.Fatalf("agent_system_prompt.yaml does not parse: %v", err)
}
foundTpl := false
for _, tp := range tpl.Templates {
if id, _ := tp["id"].(string); id == "sip_translator" {
foundTpl = true
if content, _ := tp["content"].(string); len(content) < 100 {
t.Fatalf("sip_translator template content too short")
}
}
}
if !foundTpl {
t.Fatalf("sip_translator template not found")
}
}