Files
ai_academy/internal/xlsxtranslate/engine.go
T
runny 7d3b6804af
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s
fix(翻译bug):修复翻译超时失败!
2026-11-30 23:22:23 +08:00

611 lines
19 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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
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. 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
}
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, alias))
}
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.
// 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 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) + "</" + 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
}
// 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/")
}