2.预览翻译文件时无法预览图片! 3.上传文件都要存到知识库中!可被问答 4.在SIP翻译专家agent下上传文件后默认给提示文案可直接发送
This commit is contained in:
1 parent
8c3d0ee31c
commit
90b843b4e8
9 files changed
+308
-75
No files matched your search
@@ -220,7 +220,10 @@ builtin_agents:
|
|||||||
temperature: 0.3
|
temperature: 0.3
|
||||||
max_completion_tokens: 8192
|
max_completion_tokens: 8192
|
||||||
max_iterations: 15
|
max_iterations: 15
|
||||||
kb_selection_mode: "none"
|
# Selected KBs are also the filing target: uploads and translations are
|
||||||
|
# ingested there so they stay searchable by Q&A. Pick the KB in the
|
||||||
|
# agent editor after deployment.
|
||||||
|
kb_selection_mode: "selected"
|
||||||
retrieve_kb_only_when_mentioned: false
|
retrieve_kb_only_when_mentioned: false
|
||||||
supported_file_types:
|
supported_file_types:
|
||||||
- "xlsx"
|
- "xlsx"
|
||||||
|
|||||||
@@ -87,6 +87,20 @@ const imageUploading = ref(false);
|
|||||||
// Attachment upload state
|
// Attachment upload state
|
||||||
const attachmentUploadRef = ref<InstanceType<typeof AttachmentUpload>>();
|
const attachmentUploadRef = ref<InstanceType<typeof AttachmentUpload>>();
|
||||||
const uploadedAttachments = ref<AttachmentFile[]>([]);
|
const uploadedAttachments = ref<AttachmentFile[]>([]);
|
||||||
|
|
||||||
|
// SIP translator agent: once its workbook attachment finishes uploading, the
|
||||||
|
// prompt tells the user they can send as-is — the agent drives the rest.
|
||||||
|
const SIP_TRANSLATOR_AGENT_ID = 'builtin-sip-translator';
|
||||||
|
const inputPlaceholder = computed(() => {
|
||||||
|
if (
|
||||||
|
selectedAgentId.value === SIP_TRANSLATOR_AGENT_ID &&
|
||||||
|
uploadedAttachments.value.length > 0 &&
|
||||||
|
uploadedAttachments.value.every(item => item.documentId && item.status !== 'failed')
|
||||||
|
) {
|
||||||
|
return '翻译文件已就绪,直接发送即可开始翻译';
|
||||||
|
}
|
||||||
|
return t('input.placeholder');
|
||||||
|
});
|
||||||
const CHAT_FILE_DROP_EVENT = 'academy:chat-file-drop';
|
const CHAT_FILE_DROP_EVENT = 'academy:chat-file-drop';
|
||||||
|
|
||||||
const isImageFile = (file: File) => {
|
const isImageFile = (file: File) => {
|
||||||
@@ -2843,7 +2857,7 @@ defineExpose({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- 实际输入框 -->
|
<!-- 实际输入框 -->
|
||||||
<t-textarea ref="textareaRef" v-model="query" :placeholder="t('input.placeholder')" name="description" :autosize="true"
|
<t-textarea ref="textareaRef" v-model="query" :placeholder="inputPlaceholder" name="description" :autosize="true"
|
||||||
@keydown="onKeydown" @input="onInput" @compositionstart="onCompositionStart" @compositionend="onCompositionEnd"
|
@keydown="onKeydown" @input="onInput" @compositionstart="onCompositionStart" @compositionend="onCompositionEnd"
|
||||||
@paste="onPaste" />
|
@paste="onPaste" />
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
"mime/multipart"
|
||||||
"path"
|
"path"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -84,6 +85,8 @@ type XlsxTranslateTool struct {
|
|||||||
tempDoc interfaces.TemporaryDocumentService
|
tempDoc interfaces.TemporaryDocumentService
|
||||||
files interfaces.FileService
|
files interfaces.FileService
|
||||||
artifacts MessageArtifactSink
|
artifacts MessageArtifactSink
|
||||||
|
knowledge interfaces.KnowledgeService
|
||||||
|
ingestKB string // knowledge base the upload and its translation are filed into; "" disables ingestion
|
||||||
model chat.Chat
|
model chat.Chat
|
||||||
timeout time.Duration
|
timeout time.Duration
|
||||||
}
|
}
|
||||||
@@ -104,6 +107,8 @@ func NewXlsxTranslateTool(
|
|||||||
tempDoc interfaces.TemporaryDocumentService,
|
tempDoc interfaces.TemporaryDocumentService,
|
||||||
files interfaces.FileService,
|
files interfaces.FileService,
|
||||||
artifacts MessageArtifactSink,
|
artifacts MessageArtifactSink,
|
||||||
|
knowledge interfaces.KnowledgeService,
|
||||||
|
ingestKB string,
|
||||||
model chat.Chat,
|
model chat.Chat,
|
||||||
) *XlsxTranslateTool {
|
) *XlsxTranslateTool {
|
||||||
return &XlsxTranslateTool{
|
return &XlsxTranslateTool{
|
||||||
@@ -117,6 +122,8 @@ func NewXlsxTranslateTool(
|
|||||||
tempDoc: tempDoc,
|
tempDoc: tempDoc,
|
||||||
files: files,
|
files: files,
|
||||||
artifacts: artifacts,
|
artifacts: artifacts,
|
||||||
|
knowledge: knowledge,
|
||||||
|
ingestKB: ingestKB,
|
||||||
model: model,
|
model: model,
|
||||||
timeout: 20 * time.Minute,
|
timeout: 20 * time.Minute,
|
||||||
}
|
}
|
||||||
@@ -203,6 +210,16 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
|||||||
}
|
}
|
||||||
deliverable = outName
|
deliverable = outName
|
||||||
}
|
}
|
||||||
|
// Requirement: uploads and their translations must be searchable. File
|
||||||
|
// both into the agent's knowledge base when one is selected; ingestion
|
||||||
|
// runs through the normal async pipeline, so failures never block
|
||||||
|
// delivering the translated workbook.
|
||||||
|
if t.ingestKB != "" && t.knowledge != nil {
|
||||||
|
if warn := t.ingestToKnowledge(ctx, tenantID, source, data, outName, translated); warn != "" {
|
||||||
|
report.Warnings = append(report.Warnings, warn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
|
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
|
||||||
sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
|
sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
|
||||||
|
|
||||||
@@ -353,6 +370,65 @@ func (t *XlsxTranslateTool) saveAsMessageArtifact(
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ingestToKnowledge files the original upload and the English translation
|
||||||
|
// into the agent's knowledge base so both stay searchable by Q&A. Failures
|
||||||
|
// are reported as a single warning line; ingestion is async and best-effort.
|
||||||
|
func (t *XlsxTranslateTool) ingestToKnowledge(
|
||||||
|
ctx context.Context, tenantID uint64, sourceName string, sourceData []byte, outName string, translated []byte,
|
||||||
|
) string {
|
||||||
|
if tenantID == 0 {
|
||||||
|
tenantID = 1
|
||||||
|
}
|
||||||
|
var warnings []string
|
||||||
|
if err := t.ingestOne(ctx, tenantID, sourceName, sourceData); err != nil {
|
||||||
|
warnings = append(warnings, fmt.Sprintf("原文件未存入知识库:%v", err))
|
||||||
|
}
|
||||||
|
if err := t.ingestOne(ctx, tenantID, outName, translated); err != nil {
|
||||||
|
warnings = append(warnings, fmt.Sprintf("翻译文件未存入知识库:%v", err))
|
||||||
|
}
|
||||||
|
if len(warnings) == 0 {
|
||||||
|
logger.Infof(ctx, "[Tool][XlsxTranslate] ingested original + translation into knowledge base %s", t.ingestKB)
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return strings.Join(warnings, ";")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ingestOne wraps the bytes in a multipart file header for the knowledge
|
||||||
|
// pipeline. The header is built from an in-memory multipart form, the same
|
||||||
|
// approach the knowledge service's own tests use.
|
||||||
|
func (t *XlsxTranslateTool) ingestOne(ctx context.Context, tenantID uint64, name string, data []byte) error {
|
||||||
|
var body bytes.Buffer
|
||||||
|
writer := multipart.NewWriter(&body)
|
||||||
|
part, err := writer.CreateFormFile("file", name)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if _, err := part.Write(data); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := writer.Close(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
reader := multipart.NewReader(&body, writer.FormDataContentType())
|
||||||
|
form, err := reader.ReadForm(int64(len(data)) + 1<<20)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
files := form.File["file"]
|
||||||
|
if len(files) == 0 {
|
||||||
|
return fmt.Errorf("multipart form has no file part")
|
||||||
|
}
|
||||||
|
channel := "agent"
|
||||||
|
_, err = t.knowledge.CreateKnowledgeFromFile(
|
||||||
|
ctx, t.ingestKB, files[0], nil, nil, name, nil, channel, nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
_ = tenantID
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// chatBatchTranslator adapts the session chat model to the engine's
|
// chatBatchTranslator adapts the session chat model to the engine's
|
||||||
// Translator interface: one call = one JSON array round trip.
|
// Translator interface: one call = one JSON array round trip.
|
||||||
type chatBatchTranslator struct {
|
type chatBatchTranslator struct {
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ func TestXlsxTranslateToolEndToEndSandbox(t *testing.T) {
|
|||||||
store := &fakeTranslateStore{files: map[string][]byte{
|
store := &fakeTranslateStore{files: map[string][]byte{
|
||||||
"/workspace/input/part.xlsx": buildToolFixture(t),
|
"/workspace/input/part.xlsx": buildToolFixture(t),
|
||||||
}}
|
}}
|
||||||
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, nil, "", &fakeTranslateChat{})
|
||||||
|
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
|
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
|
||||||
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
||||||
@@ -270,7 +270,7 @@ func TestXlsxTranslateToolWithoutSandbox(t *testing.T) {
|
|||||||
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
|
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
|
||||||
}}
|
}}
|
||||||
files := &fakeTranslateFileService{}
|
files := &fakeTranslateFileService{}
|
||||||
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, nil, "", &fakeTranslateChat{})
|
||||||
|
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "D4-A08AR12000002-A3-SIP.xlsx"})
|
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "D4-A08AR12000002-A3-SIP.xlsx"})
|
||||||
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
||||||
@@ -323,7 +323,7 @@ func TestXlsxTranslateArtifactDeliveryIsIdempotent(t *testing.T) {
|
|||||||
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
|
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
|
||||||
}}
|
}}
|
||||||
files := &fakeTranslateFileService{}
|
files := &fakeTranslateFileService{}
|
||||||
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, nil, "", &fakeTranslateChat{})
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "part.xlsx"})
|
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "part.xlsx"})
|
||||||
|
|
||||||
for i := 0; i < 2; i++ {
|
for i := 0; i < 2; i++ {
|
||||||
@@ -349,7 +349,7 @@ func TestXlsxTranslateToolSandboxReadFallsBackToAttachment(t *testing.T) {
|
|||||||
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
|
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
|
||||||
ID: "doc-1", FileName: "part.xlsx", FileType: "xlsx",
|
ID: "doc-1", FileName: "part.xlsx", FileType: "xlsx",
|
||||||
})
|
})
|
||||||
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, nil, "", &fakeTranslateChat{})
|
||||||
|
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
|
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
|
||||||
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
||||||
@@ -368,7 +368,7 @@ func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
|
|||||||
store := &fakeTranslateStore{files: map[string][]byte{
|
store := &fakeTranslateStore{files: map[string][]byte{
|
||||||
"/workspace/input/part.xls": {0xD0, 0xCF, 0x11, 0xE0},
|
"/workspace/input/part.xls": {0xD0, 0xCF, 0x11, 0xE0},
|
||||||
}}
|
}}
|
||||||
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, nil, "", &fakeTranslateChat{})
|
||||||
|
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
|
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
|
||||||
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
||||||
@@ -383,7 +383,7 @@ func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
|
|||||||
func TestXlsxTranslateToolMissingFile(t *testing.T) {
|
func TestXlsxTranslateToolMissingFile(t *testing.T) {
|
||||||
store := &fakeTranslateStore{files: map[string][]byte{}}
|
store := &fakeTranslateStore{files: map[string][]byte{}}
|
||||||
tempDoc := &fakeTranslateTempDoc{}
|
tempDoc := &fakeTranslateTempDoc{}
|
||||||
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, &fakeTranslateChat{})
|
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, nil, "", &fakeTranslateChat{})
|
||||||
|
|
||||||
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
|
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
|
||||||
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
|
||||||
|
|||||||
@@ -696,8 +696,17 @@ func (s *agentService) registerXlsxTranslateTool(
|
|||||||
}
|
}
|
||||||
// store doubles as the dir ensurer; both are nil without a sandbox. The
|
// store doubles as the dir ensurer; both are nil without a sandbox. The
|
||||||
// message service is the no-sandbox artifact sink: deliverables attach to
|
// message service is the no-sandbox artifact sink: deliverables attach to
|
||||||
// the assistant message and surface as chat artifact cards.
|
// the assistant message and surface as chat artifact cards. When the agent
|
||||||
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, s.temporaryDocuments, s.fileService, s.messageService, chatModel))
|
// has explicit knowledge bases selected, uploads and translations are
|
||||||
|
// filed into the first one so they stay searchable by Q&A.
|
||||||
|
ingestKB := ""
|
||||||
|
if config != nil && len(config.SearchTargets) > 0 && config.SearchTargets[0] != nil {
|
||||||
|
ingestKB = config.SearchTargets[0].KnowledgeBaseID
|
||||||
|
}
|
||||||
|
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(
|
||||||
|
store, store, s.temporaryDocuments, s.fileService, s.messageService,
|
||||||
|
s.knowledgeService, ingestKB, chatModel,
|
||||||
|
))
|
||||||
if store != nil {
|
if store != nil {
|
||||||
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s (sandbox delivery)", sessionID)
|
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s (sandbox delivery)", sessionID)
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -148,6 +148,41 @@ func collapseWhitespace(s string) string {
|
|||||||
return strings.Join(strings.Fields(s), " ")
|
return strings.Join(strings.Fields(s), " ")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sanitizeSheetName enforces Excel worksheet name rules on a translated
|
||||||
|
// sheet name: no : \ / ? * [ ] (or apostrophes, which would break quoted
|
||||||
|
// formula references), at most 31 runes, unique within the workbook. An
|
||||||
|
// empty translation falls back to "Sheet".
|
||||||
|
func sanitizeSheetName(name string, used map[string]struct{}) string {
|
||||||
|
var b strings.Builder
|
||||||
|
for _, r := range name {
|
||||||
|
switch r {
|
||||||
|
case ':', '\\', '/', '?', '*', '[', ']', '\'', '\u0000':
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
b.WriteRune(r)
|
||||||
|
}
|
||||||
|
out := collapseWhitespace(b.String())
|
||||||
|
if len(out) > 31 {
|
||||||
|
out = out[:31]
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(out) == "" {
|
||||||
|
out = "Sheet"
|
||||||
|
}
|
||||||
|
base := out
|
||||||
|
for i := 2; ; i++ {
|
||||||
|
if _, exists := used[out]; !exists {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
suffix := " " + itoa(i)
|
||||||
|
if len(base)+len(suffix) > 31 {
|
||||||
|
base = base[:31-len(suffix)]
|
||||||
|
}
|
||||||
|
out = base + suffix
|
||||||
|
}
|
||||||
|
used[out] = struct{}{}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
// itoa is a tiny helper so this file needs no strconv import noise.
|
// itoa is a tiny helper so this file needs no strconv import noise.
|
||||||
func itoa(i int) string {
|
func itoa(i int) string {
|
||||||
if i == 0 {
|
if i == 0 {
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ type Report struct {
|
|||||||
InlineTextCells int // worksheet inlineStr is blocks scanned
|
InlineTextCells int // worksheet inlineStr is blocks scanned
|
||||||
DrawingBodies int // txBody blocks scanned in drawings/charts
|
DrawingBodies int // txBody blocks scanned in drawings/charts
|
||||||
TranslatedUnits int // unique CJK text units queued for translation
|
TranslatedUnits int // unique CJK text units queued for translation
|
||||||
|
SheetNamesRenamed int // CJK worksheet names renamed (Excel rules applied)
|
||||||
AppliedTranslations int // unique units actually resolved
|
AppliedTranslations int // unique units actually resolved
|
||||||
GlossaryHits int // units resolved from the glossary
|
GlossaryHits int // units resolved from the glossary
|
||||||
LLMCalls int // LLM batch calls issued
|
LLMCalls int // LLM batch calls issued
|
||||||
@@ -116,6 +117,7 @@ func (r *Report) Markdown() string {
|
|||||||
r.TextCells, r.InlineTextCells, r.DrawingBodies)
|
r.TextCells, r.InlineTextCells, r.DrawingBodies)
|
||||||
fmt.Fprintf(&b, "| 翻译单元(去重后) | %d(术语库命中 %d,LLM 批次 %d 次) |\n",
|
fmt.Fprintf(&b, "| 翻译单元(去重后) | %d(术语库命中 %d,LLM 批次 %d 次) |\n",
|
||||||
r.TranslatedUnits, r.GlossaryHits, r.LLMCalls)
|
r.TranslatedUnits, r.GlossaryHits, r.LLMCalls)
|
||||||
|
fmt.Fprintf(&b, "| Sheet 名称改名 | %d 个 |\n", r.SheetNamesRenamed)
|
||||||
fmt.Fprintf(&b, "| 残留中文 | %d 处 |\n", r.ResidualCJKCount)
|
fmt.Fprintf(&b, "| 残留中文 | %d 处 |\n", r.ResidualCJKCount)
|
||||||
fmt.Fprintf(&b, "| 数字 / 料号改动 | %d / %d 处 |\n", len(r.NumberMismatches), len(r.PartMismatches))
|
fmt.Fprintf(&b, "| 数字 / 料号改动 | %d / %d 处 |\n", len(r.NumberMismatches), len(r.PartMismatches))
|
||||||
if len(r.ResidualCJKSamples) > 0 {
|
if len(r.ResidualCJKSamples) > 0 {
|
||||||
@@ -142,8 +144,11 @@ func truncate(s string, n int) string {
|
|||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
// sharedStringsEntry is the canonical path of the shared string table.
|
// sharedStringsEntry and workbookEntry are the canonical package paths.
|
||||||
const sharedStringsEntry = "xl/sharedStrings.xml"
|
const (
|
||||||
|
sharedStringsEntry = "xl/sharedStrings.xml"
|
||||||
|
workbookEntry = "xl/workbook.xml"
|
||||||
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
siBlockRe = regexp.MustCompile(`(?s)<si(?:/>|>.*?</si>)`)
|
siBlockRe = regexp.MustCompile(`(?s)<si(?:/>|>.*?</si>)`)
|
||||||
@@ -153,6 +158,9 @@ var (
|
|||||||
txBodyRe = regexp.MustCompile(`(?s)<[A-Za-z0-9]+:txBody[^>]*>.*?</[A-Za-z0-9]+:txBody>`)
|
txBodyRe = regexp.MustCompile(`(?s)<[A-Za-z0-9]+:txBody[^>]*>.*?</[A-Za-z0-9]+:txBody>`)
|
||||||
paraRe = regexp.MustCompile(`(?s)<a:p(?:\s[^>]*)?>.*?</a:p>`)
|
paraRe = regexp.MustCompile(`(?s)<a:p(?:\s[^>]*)?>.*?</a:p>`)
|
||||||
aTTagRe = regexp.MustCompile(`(?s)<a:t(?:\s[^>]*)?>(.*?)</a:t>`)
|
aTTagRe = regexp.MustCompile(`(?s)<a:t(?:\s[^>]*)?>(.*?)</a:t>`)
|
||||||
|
// sheetNameRe captures the name attribute value of every <sheet> element:
|
||||||
|
// group 1 = tag prefix through the opening quote, 2 = value, 3 = quote.
|
||||||
|
sheetNameRe = regexp.MustCompile(`(<sheet\b[^>]*?\bname=")([^"]*)(")`)
|
||||||
)
|
)
|
||||||
|
|
||||||
// editKind distinguishes the run that carries the unit translation from the
|
// editKind distinguishes the run that carries the unit translation from the
|
||||||
@@ -162,6 +170,9 @@ type editKind int
|
|||||||
const (
|
const (
|
||||||
editCarrier editKind = iota
|
editCarrier editKind = iota
|
||||||
editClear
|
editClear
|
||||||
|
// editSheetName rewrites the name="..." attribute value of a <sheet>
|
||||||
|
// element in workbook.xml.
|
||||||
|
editSheetName
|
||||||
)
|
)
|
||||||
|
|
||||||
// locatedEdit is one byte-range rewrite on an entry. tag is the element name
|
// locatedEdit is one byte-range rewrite on an entry. tag is the element name
|
||||||
@@ -173,9 +184,19 @@ type locatedEdit struct {
|
|||||||
tag string
|
tag string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// scanKind tags what an entry's units are, so pass 3 can post-process sheet
|
||||||
|
// names (Excel naming rules + quoted formula references).
|
||||||
|
type scanKind int
|
||||||
|
|
||||||
|
const (
|
||||||
|
scanText scanKind = iota
|
||||||
|
scanSheets
|
||||||
|
)
|
||||||
|
|
||||||
// scanJob holds everything to rewrite for one zip entry.
|
// scanJob holds everything to rewrite for one zip entry.
|
||||||
type scanJob struct {
|
type scanJob struct {
|
||||||
entry int
|
entry int
|
||||||
|
kind scanKind
|
||||||
units []string // translatable CJK unit texts, scan order
|
units []string // translatable CJK unit texts, scan order
|
||||||
edits []locatedEdit // byte ranges, scan order
|
edits []locatedEdit // byte ranges, scan order
|
||||||
}
|
}
|
||||||
@@ -207,6 +228,7 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
|
|||||||
// ---- Pass 1: collect translatable units per entry ----
|
// ---- Pass 1: collect translatable units per entry ----
|
||||||
entryData := make([][]byte, len(reader.File))
|
entryData := make([][]byte, len(reader.File))
|
||||||
jobs := map[int]*scanJob{}
|
jobs := map[int]*scanJob{}
|
||||||
|
var sheetJob *scanJob // workbook.xml job: units are sheet names
|
||||||
for i, f := range reader.File {
|
for i, f := range reader.File {
|
||||||
raw, err := readZip(f)
|
raw, err := readZip(f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -214,6 +236,15 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
|
|||||||
}
|
}
|
||||||
entryData[i] = raw
|
entryData[i] = raw
|
||||||
switch {
|
switch {
|
||||||
|
case f.Name == workbookEntry:
|
||||||
|
job, renamed := scanSheetNames(string(raw))
|
||||||
|
report.SheetNamesRenamed = renamed
|
||||||
|
if len(job.units) > 0 {
|
||||||
|
job.entry = i
|
||||||
|
job.kind = scanSheets
|
||||||
|
jobs[i] = job
|
||||||
|
sheetJob = job
|
||||||
|
}
|
||||||
case f.Name == sharedStringsEntry:
|
case f.Name == sharedStringsEntry:
|
||||||
job, scanned := scanStringBlocks(string(raw), siBlockRe, "t")
|
job, scanned := scanStringBlocks(string(raw), siBlockRe, "t")
|
||||||
report.TextCells += scanned
|
report.TextCells += scanned
|
||||||
@@ -385,13 +416,34 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
|
|||||||
idx int
|
idx int
|
||||||
data []byte
|
data []byte
|
||||||
}
|
}
|
||||||
|
// Sheet names: apply Excel naming rules (charset, 31-char cap, unique)
|
||||||
|
// and keep quoted formula references ('旧名'!) pointing at renamed sheets.
|
||||||
|
var renames [][2]string
|
||||||
|
if sheetJob != nil {
|
||||||
|
used := map[string]struct{}{}
|
||||||
|
for _, old := range sheetJob.units {
|
||||||
|
newName, ok := translations[old]
|
||||||
|
if !ok {
|
||||||
|
continue // oversized/skipped: keep the original sheet name
|
||||||
|
}
|
||||||
|
newName = sanitizeSheetName(newName, used)
|
||||||
|
translations[old] = newName
|
||||||
|
renames = append(renames, [2]string{old, newName})
|
||||||
|
}
|
||||||
|
report.SheetNamesRenamed = len(renames)
|
||||||
|
}
|
||||||
|
|
||||||
out := make([]outEntry, 0, len(reader.File))
|
out := make([]outEntry, 0, len(reader.File))
|
||||||
for i := range reader.File {
|
for i := range reader.File {
|
||||||
data := entryData[i]
|
data := string(entryData[i])
|
||||||
if job, ok := jobs[i]; ok {
|
if job, ok := jobs[i]; ok {
|
||||||
data = []byte(applyJob(string(data), job, translations, alias))
|
data = applyJob(data, job, translations, alias)
|
||||||
}
|
}
|
||||||
out = append(out, outEntry{idx: i, data: data})
|
for _, r := range renames {
|
||||||
|
// Quoted formula references ('旧名'!) must follow the rename.
|
||||||
|
data = strings.ReplaceAll(data, "'"+r[0]+"'!", "'"+r[1]+"'!")
|
||||||
|
}
|
||||||
|
out = append(out, outEntry{idx: i, data: []byte(data)})
|
||||||
}
|
}
|
||||||
sort.SliceStable(out, func(a, b int) bool { return out[a].idx < out[b].idx })
|
sort.SliceStable(out, func(a, b int) bool { return out[a].idx < out[b].idx })
|
||||||
|
|
||||||
@@ -426,6 +478,30 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
|
|||||||
// towards the scanned total; blocks whose joined <t> text contains CJK become
|
// 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>.
|
// units with one carrier edit (first <t>) and one clear edit per sibling <t>.
|
||||||
// Phonetic <rPh> hints are excluded from both joining and editing.
|
// Phonetic <rPh> hints are excluded from both joining and editing.
|
||||||
|
// scanSheetNames collects CJK worksheet names from workbook.xml. Each name
|
||||||
|
// becomes one unit with a single edit covering the attribute value span.
|
||||||
|
// Returns the count of names queued for renaming.
|
||||||
|
func scanSheetNames(src string) (*scanJob, int) {
|
||||||
|
job := &scanJob{}
|
||||||
|
renamed := 0
|
||||||
|
for _, loc := range sheetNameRe.FindAllStringSubmatchIndex(src, -1) {
|
||||||
|
name := unescapeXMLText(src[loc[4]:loc[5]])
|
||||||
|
if !hasCJK(name) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
unitIdx := len(job.units)
|
||||||
|
job.units = append(job.units, name)
|
||||||
|
job.edits = append(job.edits, locatedEdit{
|
||||||
|
start: loc[4],
|
||||||
|
end: loc[5],
|
||||||
|
kind: editSheetName,
|
||||||
|
unitIdx: unitIdx,
|
||||||
|
})
|
||||||
|
renamed++
|
||||||
|
}
|
||||||
|
return job, renamed
|
||||||
|
}
|
||||||
|
|
||||||
func scanStringBlocks(src string, blockRe *regexp.Regexp, tag string) (*scanJob, int) {
|
func scanStringBlocks(src string, blockRe *regexp.Regexp, tag string) (*scanJob, int) {
|
||||||
job := &scanJob{}
|
job := &scanJob{}
|
||||||
scanned := 0
|
scanned := 0
|
||||||
@@ -543,6 +619,13 @@ func applyJob(src string, job *scanJob, translations map[string]string, alias fu
|
|||||||
repls := make([]repl, 0, len(job.edits))
|
repls := make([]repl, 0, len(job.edits))
|
||||||
for _, e := range job.edits {
|
for _, e := range job.edits {
|
||||||
switch e.kind {
|
switch e.kind {
|
||||||
|
case editSheetName:
|
||||||
|
// Sheet names replace the bare attribute value, no tag wrap.
|
||||||
|
t, ok := translations[alias(job.units[e.unitIdx])]
|
||||||
|
if !ok {
|
||||||
|
continue // oversized/skipped unit: keep the original bytes
|
||||||
|
}
|
||||||
|
repls = append(repls, repl{e.start, e.end, escapeXMLText(t)})
|
||||||
case editCarrier:
|
case editCarrier:
|
||||||
t, ok := translations[alias(job.units[e.unitIdx])]
|
t, ok := translations[alias(job.units[e.unitIdx])]
|
||||||
if !ok {
|
if !ok {
|
||||||
|
|||||||
@@ -73,66 +73,74 @@ var glossary = map[string]string{
|
|||||||
"检验条件": "Inspection conditions",
|
"检验条件": "Inspection conditions",
|
||||||
"檢驗條件": "Inspection conditions",
|
"檢驗條件": "Inspection conditions",
|
||||||
// Common hardware and inspection nouns seen in the drawing text boxes
|
// Common hardware and inspection nouns seen in the drawing text boxes
|
||||||
"螺母": "NUT",
|
"螺母": "NUT",
|
||||||
"螺丝": "SCREW",
|
"螺丝": "SCREW",
|
||||||
"螺钉": "SCREW",
|
"螺钉": "SCREW",
|
||||||
"螺栓": "BOLT",
|
"螺栓": "BOLT",
|
||||||
"万向轮": "Caster",
|
"万向轮": "Caster",
|
||||||
"腳杯": "Leveling Foot",
|
"腳杯": "Leveling Foot",
|
||||||
"脚杯": "Leveling Foot",
|
"脚杯": "Leveling Foot",
|
||||||
"接地": "Grounding",
|
"接地": "Grounding",
|
||||||
"接地区域": "Grounding area",
|
"接地区域": "Grounding area",
|
||||||
"接地螺丝": "Grounding screw",
|
"接地螺丝": "Grounding screw",
|
||||||
"接地螺絲": "Grounding screw",
|
"接地螺絲": "Grounding screw",
|
||||||
"支撑件": "Support",
|
"支撑件": "Support",
|
||||||
"支撐件": "Support",
|
"支撐件": "Support",
|
||||||
"水平仪": "Spirit level",
|
"水平仪": "Spirit level",
|
||||||
"钢直尺": "Steel ruler",
|
"钢直尺": "Steel ruler",
|
||||||
"鋼直尺": "Steel ruler",
|
"鋼直尺": "Steel ruler",
|
||||||
"卷尺": "Tape measure",
|
"卷尺": "Tape measure",
|
||||||
"塞尺": "Feeler gauge",
|
"塞尺": "Feeler gauge",
|
||||||
"检具": "Inspection gauge",
|
"检具": "Inspection gauge",
|
||||||
"檢具": "Inspection gauge",
|
"檢具": "Inspection gauge",
|
||||||
"手电筒": "Flashlight",
|
"手电筒": "Flashlight",
|
||||||
"手电筒/目视/手触摸": "Flashlight/Visual/Touch by hand",
|
"手电筒/目视/手触摸": "Flashlight/Visual/Touch by hand",
|
||||||
"手触摸": "Touch by hand",
|
"手触摸": "Touch by hand",
|
||||||
"对角线": "Diagonal",
|
"对角线": "Diagonal",
|
||||||
"對角線": "Diagonal",
|
"對角線": "Diagonal",
|
||||||
"平面度": "Flatness",
|
"平面度": "Flatness",
|
||||||
"平行度": "Parallelism",
|
"平行度": "Parallelism",
|
||||||
"底板平面度": "Bottom plate flatness",
|
"底板平面度": "Bottom plate flatness",
|
||||||
"顶板平面度": "Top plate flatness",
|
"顶板平面度": "Top plate flatness",
|
||||||
"外宽": "Outer width",
|
"外宽": "Outer width",
|
||||||
"內宽": "Inner width",
|
"內宽": "Inner width",
|
||||||
"内宽": "Inner width",
|
"内宽": "Inner width",
|
||||||
"前门": "Front door",
|
"前门": "Front door",
|
||||||
"后门": "Rear door",
|
"后门": "Rear door",
|
||||||
"前門": "Front door",
|
"前門": "Front door",
|
||||||
"後門": "Rear door",
|
"後門": "Rear door",
|
||||||
"侧板": "Side panel",
|
"侧板": "Side panel",
|
||||||
"側板": "Side panel",
|
"側板": "Side panel",
|
||||||
"顶板": "Top panel",
|
"顶板": "Top panel",
|
||||||
"底板": "Bottom panel",
|
"底板": "Bottom panel",
|
||||||
"立柱": "Vertical post",
|
"立柱": "Vertical post",
|
||||||
"螺纹孔": "Threaded hole",
|
"螺纹孔": "Threaded hole",
|
||||||
"螺紋孔": "Threaded hole",
|
"螺紋孔": "Threaded hole",
|
||||||
"方孔": "Square hole",
|
"方孔": "Square hole",
|
||||||
"葫芦孔": "Keyhole",
|
"葫芦孔": "Keyhole",
|
||||||
"焊道": "Weld bead",
|
"焊道": "Weld bead",
|
||||||
"焊点": "Weld point",
|
"焊点": "Weld point",
|
||||||
"铜箔纸": "Copper foil paper",
|
"铜箔纸": "Copper foil paper",
|
||||||
"防烤胶带": "High-temperature tape",
|
"防烤胶带": "High-temperature tape",
|
||||||
"标签": "Label",
|
"标签": "Label",
|
||||||
"標籤": "Label",
|
"標籤": "Label",
|
||||||
"SN标签": "SN label",
|
"SN标签": "SN label",
|
||||||
"机柜": "Rack",
|
"机柜": "Rack",
|
||||||
"機櫃": "Rack",
|
"機櫃": "Rack",
|
||||||
"机柜本体": "Rack body",
|
"机柜本体": "Rack body",
|
||||||
"包装": "Packing",
|
"包装": "Packing",
|
||||||
"出厂检验": "Outgoing inspection",
|
"出厂检验": "Outgoing inspection",
|
||||||
"出货检验": "Outgoing inspection",
|
"出货检验": "Outgoing inspection",
|
||||||
"组装": "Assembly",
|
"组装": "Assembly",
|
||||||
"組裝": "Assembly",
|
"組裝": "Assembly",
|
||||||
|
// Worksheet (sheet tab) names — workbook sheet tabs are renamed too
|
||||||
|
"更改履历": "Revision History",
|
||||||
|
"更改記錄": "Revision History",
|
||||||
|
"前置加工": "Pre-processing",
|
||||||
|
"全检项目": "Full Inspection Items",
|
||||||
|
"全檢項目": "Full Inspection Items",
|
||||||
|
"出货包装": "Outgoing Packaging",
|
||||||
|
"出貨包裝": "Outgoing Packaging",
|
||||||
"检验": "Inspection",
|
"检验": "Inspection",
|
||||||
"檢驗": "Inspection",
|
"檢驗": "Inspection",
|
||||||
"检查": "Check",
|
"检查": "Check",
|
||||||
|
|||||||
@@ -85,6 +85,11 @@ func collectPackageTexts(reader *zip.Reader) []string {
|
|||||||
for _, loc := range re.FindAllStringIndex(string(raw), -1) {
|
for _, loc := range re.FindAllStringIndex(string(raw), -1) {
|
||||||
appendBlockText(string(raw)[loc[0]:loc[1]])
|
appendBlockText(string(raw)[loc[0]:loc[1]])
|
||||||
}
|
}
|
||||||
|
case f.Name == workbookEntry:
|
||||||
|
src := string(raw)
|
||||||
|
for _, loc := range sheetNameRe.FindAllStringSubmatchIndex(src, -1) {
|
||||||
|
texts = append(texts, unescapeXMLText(src[loc[4]:loc[5]]))
|
||||||
|
}
|
||||||
case isDrawingXML(f.Name):
|
case isDrawingXML(f.Name):
|
||||||
src := string(raw)
|
src := string(raw)
|
||||||
for _, bodyLoc := range txBodyRe.FindAllStringIndex(src, -1) {
|
for _, bodyLoc := range txBodyRe.FindAllStringIndex(src, -1) {
|
||||||
|
|||||||
Reference in new issue
Block a user