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

+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")
}
}