package xlsxtranslate import ( "archive/zip" "bytes" "context" "errors" "fmt" "regexp" "sort" "strings" "sync" "sync/atomic" "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 20. BatchSize int // BatchConcurrency is how many LLM batches may run in parallel. // Default 4. Providers rate-limit; higher values queue on the chat // client's own concurrency gate. BatchConcurrency 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 20 } func (o *Options) batchConcurrency() int { if o != nil && o.BatchConcurrency > 0 { return o.BatchConcurrency } return 4 } 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 SheetNamesRenamed int // CJK worksheet names renamed (Excel rules applied) 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, "| Sheet 名称改名 | %d 个 |\n", r.SheetNamesRenamed) 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 and workbookEntry are the canonical package paths. const ( sharedStringsEntry = "xl/sharedStrings.xml" workbookEntry = "xl/workbook.xml" ) var ( siBlockRe = regexp.MustCompile(`(?s)|>.*?)`) isBlockRe = regexp.MustCompile(`(?s)|>.*?)`) rPhRe = regexp.MustCompile(`(?s)|>.*?)`) tTagRe = regexp.MustCompile(`(?s)]*)?>(.*?)`) txBodyRe = regexp.MustCompile(`(?s)<[A-Za-z0-9]+:txBody[^>]*>.*?`) paraRe = regexp.MustCompile(`(?s)]*)?>.*?`) aTTagRe = regexp.MustCompile(`(?s)]*)?>(.*?)`) // sheetNameRe captures the name attribute value of every element: // group 1 = tag prefix through the opening quote, 2 = value, 3 = quote. sheetNameRe = regexp.MustCompile(`(]*?\bname=")([^"]*)(")`) ) // editKind distinguishes the run that carries the unit translation from the // sibling runs that are emptied (their / styling is preserved). type editKind int const ( editCarrier editKind = iota editClear // editSheetName rewrites the name="..." attribute value of a // element in workbook.xml. editSheetName ) // 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 } // 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. type scanJob struct { entry int kind scanKind 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{} var sheetJob *scanJob // workbook.xml job: units are sheet names 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 == 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: 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. Near // duplicates that differ only in whitespace collapse to one unit: // sending both in one batch makes the model answer with a single // translation for "the same string twice", which desynchronises the // positional array protocol. unitOrder := []string{} unitSeen := map[string]string{} unitCanonical := map[string]string{} // raw text -> canonical raw text for _, job := range jobs { for _, u := range job.units { key := collapseWhitespace(u) if canonical, ok := unitSeen[key]; ok { unitCanonical[u] = canonical continue } unitSeen[key] = u unitCanonical[u] = u 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) } } // Batches run with bounded parallelism: a 63 MB workbook translates // several hundred units, and serial batches would spend far longer on // LLM latency than on everything else combined. batchSize := opt.batchSize() var batches [][]string for lo := 0; lo < len(todo); lo += batchSize { hi := lo + batchSize if hi > len(todo) { hi = len(todo) } batches = append(batches, todo[lo:hi]) } batchOut := make([][]string, len(batches)) batchTokens := make([][][]string, len(batches)) batchErr := make([]error, len(batches)) report.LLMCalls = len(batches) if concurrency := opt.batchConcurrency(); concurrency <= 1 || len(batches) <= 1 { for i, batch := range batches { batchOut[i], batchTokens[i], batchErr[i] = runBatch(ctx, tr, batch) } } else { sem := make(chan struct{}, concurrency) var failed atomic.Bool runCtx, cancel := context.WithCancel(ctx) defer cancel() var wg sync.WaitGroup for i := range batches { wg.Add(1) go func(i int) { defer wg.Done() if failed.Load() { return // a sibling already failed; stop burning provider calls } // Stagger wave starts so concurrency*N streams never hit the // provider as one simultaneous burst. time.Sleep(time.Duration(i/concurrency) * 250 * time.Millisecond) sem <- struct{}{} defer func() { <-sem }() out, tokens, err := runBatch(runCtx, tr, batches[i]) batchOut[i], batchTokens[i], batchErr[i] = out, tokens, err if err != nil { failed.Store(true) cancel() } }(i) } wg.Wait() } for i := range batches { if batchErr[i] == nil { continue } // Concurrent batches: when one batch fails the sibling contexts are // cancelled, so the first error in order is often a cancellation // VICTIM, not the root cause. Prefer any non-context error. if errors.Is(batchErr[i], context.Canceled) || errors.Is(batchErr[i], context.DeadlineExceeded) { continue } return nil, report, fmt.Errorf("LLM batch %d failed: %w", i+1, batchErr[i]) } for i, batch := range batches { if batchErr[i] != nil { // Every batch failed with a context error: report the first and // say so, it means the caller cancelled or the transport dropped. return nil, report, fmt.Errorf("LLM batch %d failed: %w", i+1, batchErr[i]) } if len(batchOut[i]) != len(batch) { return nil, report, fmt.Errorf("LLM batch %d returned %d results for %d inputs", i+1, len(batchOut[i]), len(batch)) } for j, dst := range batchOut[i] { restored, miss := unmask(dst, batchTokens[i][j]) if len(miss) > 0 { report.Warnings = append(report.Warnings, fmt.Sprintf( "译文存在未能回填的占位符,请人工复核:%s", truncate(batch[j], 40))) } if opt.normalizePunctuation() { restored = normalizePunctuation(restored) } translations[batch[j]] = restored } } report.AppliedTranslations = len(translations) // ---- Pass 3: rewrite affected entries, repack in original order ---- alias := func(raw string) string { if canonical, ok := unitCanonical[raw]; ok { return canonical } return raw } type outEntry struct { idx int 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)) for i := range reader.File { data := string(entryData[i]) if job, ok := jobs[i]; ok { data = applyJob(data, job, translations, alias) } 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 }) 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 / blocks. Every block counts // towards the scanned total; blocks whose joined text contains CJK become // units with one carrier edit (first ) and one clear edit per sibling . // Phonetic 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) { 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 paragraph: its 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. // alias resolves a raw unit to its canonical unit (whitespace-variant // near duplicates share one translation). func applyJob(src string, job *scanJob, translations map[string]string, alias func(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 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: 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, "<" + e.tag + ` xml:space="preserve">` + escapeXMLText(t) + ""}) case editClear: repls = append(repls, repl{e.start, e.end, "<" + 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 } // runBatch masks one batch and hands it to the translator, returning the // translations together with the per-string placeholder tokens for unmasking. func runBatch(ctx context.Context, tr Translator, batch []string) ([]string, [][]string, error) { 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, nil, err } if len(out) != len(batch) { return nil, nil, fmt.Errorf("translator returned %d results for %d inputs", len(out), len(batch)) } return out, tokens, 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/") }