fix(翻译bug):修复翻译超时失败!
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s

This commit is contained in:
runny committed 2026-11-30 23:22:23 +08:00
1 parent 74d21cb204
commit 7d3b6804af
5 files changed
+220 -15

No files matched your search

+76 -7
View File
@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt" "fmt"
"io" "io"
"path" "path"
@@ -284,17 +285,70 @@ Rules:
5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.` 5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.`
func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) { func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) {
return c.translateRecover(ctx, texts, bisectDepth(len(texts)))
}
// bisectDepth bounds the halving steps needed to reach single strings.
func bisectDepth(n int) int {
depth := 0
for n > 1 {
n /= 2
depth++
}
return depth + 1
}
// translateRecover aligns model answers with inputs. A positional JSON
// protocol fails in one deterministic way: the model merges or drops an item
// (near-duplicate strings, symbol-only entries) and returns N-1 results, so
// blind retries reproduce the same mismatch forever. On a count mismatch the
// batch is halved and each half retried; a single stubborn string degrades to
// keeping the original text, which the engine's residual scan reports.
func (c *chatBatchTranslator) translateRecover(ctx context.Context, texts []string, depth int) ([]string, error) {
out, err := c.attempt(ctx, texts)
if err == nil && len(out) == len(texts) {
return out, nil
}
if len(texts) == 1 {
if err == nil && len(out) >= 1 && strings.TrimSpace(out[0]) != "" {
return []string{out[0]}, nil
}
// Keep the original untranslated; the residual scan reports it.
return []string{texts[0]}, nil
}
if depth <= 0 {
if err != nil {
return nil, err
}
return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), len(texts))
}
mid := len(texts) / 2
left, err := c.translateRecover(ctx, texts[:mid], depth-1)
if err != nil {
return nil, err
}
right, err := c.translateRecover(ctx, texts[mid:], depth-1)
if err != nil {
return nil, err
}
return append(left, right...), nil
}
// attempt issues one streaming call. Transport and JSON-shape errors get one
// immediate retry; count mismatches are content-deterministic and returned
// (wrapped) so the caller bisects instead of repeating the same failure.
func (c *chatBatchTranslator) attempt(ctx context.Context, texts []string) ([]string, error) {
payload, err := json.Marshal(texts) payload, err := json.Marshal(texts)
if err != nil { if err != nil {
return nil, err return nil, err
} }
var lastErr error var lastErr error
for attempt := 0; attempt < 3; attempt++ { for a := 0; a < 2; a++ {
if attempt > 0 { if a > 0 {
select { select {
case <-ctx.Done(): case <-ctx.Done():
return nil, ctx.Err() return nil, ctx.Err()
case <-time.After(time.Duration(attempt) * 2 * time.Second): case <-time.After(2 * time.Second):
} }
} }
user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload) user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload)
@@ -303,9 +357,13 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
lastErr = err lastErr = err
continue continue
} }
out, err := parseTranslationArray(content, len(texts)) out, perr := parseTranslationArray(content, len(texts))
if err != nil { if perr != nil {
lastErr = err var mismatch *countMismatchError
if errors.As(perr, &mismatch) {
return mismatch.items, perr
}
lastErr = perr
continue continue
} }
return out, nil return out, nil
@@ -313,6 +371,17 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string
return nil, fmt.Errorf("translation call failed after retries: %w", lastErr) return nil, fmt.Errorf("translation call failed after retries: %w", lastErr)
} }
// countMismatchError carries the model's items so bisection can still use
// them when the counts do not line up.
type countMismatchError struct {
got, want int
items []string
}
func (e *countMismatchError) Error() string {
return fmt.Sprintf("model returned %d translations for %d inputs", e.got, e.want)
}
// translateOnce issues one streaming batch call and returns the concatenated // translateOnce issues one streaming batch call and returns the concatenated
// answer. Streaming is deliberate: long batches then fall under the chat // answer. Streaming is deliberate: long batches then fall under the chat
// client's stall-based timeout instead of a single non-stream HTTP timeout. // client's stall-based timeout instead of a single non-stream HTTP timeout.
@@ -354,7 +423,7 @@ func parseTranslationArray(content string, want int) ([]string, error) {
return nil, fmt.Errorf("model response is not a valid string array: %w", err) return nil, fmt.Errorf("model response is not a valid string array: %w", err)
} }
if len(out) != want { if len(out) != want {
return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), want) return nil, &countMismatchError{got: len(out), want: want, items: out}
} }
return out, nil return out, nil
} }
@@ -309,3 +309,84 @@ func TestXlsxTranslateToolMissingFile(t *testing.T) {
t.Fatalf("missing file should fail") t.Fatalf("missing file should fail")
} }
} }
// dropItemsChat simulates the deterministic 192 failure: for any batch larger
// than one string the model "merges" two items and returns N-1 translations.
type dropItemsChat struct{}
func (f *dropItemsChat) Chat(ctx context.Context, messages []chat.Message, opts *chat.ChatOptions) (*types.ChatResponse, error) {
resp, err := f.ChatStream(ctx, messages, opts)
if err != nil {
return nil, err
}
var content strings.Builder
for chunk := range resp {
content.WriteString(chunk.Content)
}
return &types.ChatResponse{Content: content.String()}, nil
}
func (f *dropItemsChat) ChatStream(_ context.Context, messages []chat.Message, opts *chat.ChatOptions) (<-chan types.StreamResponse, error) {
content := messages[len(messages)-1].Content
start := strings.IndexByte(content, '[')
end := strings.LastIndexByte(content, ']')
var texts []string
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
return nil, err
}
if len(texts) > 1 {
texts = texts[:len(texts)-1] // drop the last item: 19 of 20
} else if len(texts) == 1 {
texts = nil // single stubborn string: model refuses to translate it
}
out := make([]string, 0, len(texts))
for _, t := range texts {
out = append(out, replaceCJKRuns(t))
}
b, _ := json.Marshal(out)
ch := make(chan types.StreamResponse, 2)
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: string(b)}
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true}
close(ch)
return ch, nil
}
func (f *dropItemsChat) GetModelName() string { return "dropping" }
func (f *dropItemsChat) GetModelID() string { return "dropping-id" }
// TestXlsxTranslateBatchCountMismatchRecovers covers the field failure where
// the model returns N-1 translations for N inputs: bisection must realign
// instead of failing the run.
func TestXlsxTranslateBatchCountMismatchRecovers(t *testing.T) {
texts := make([]string, 20)
for i := range texts {
texts[i] = fmt.Sprintf("检验项目 %d", i+1)
}
tr := &chatBatchTranslator{model: &dropItemsChat{}}
out, err := tr.TranslateBatch(context.Background(), texts)
if err != nil {
t.Fatalf("TranslateBatch: %v", err)
}
if len(out) != len(texts) {
t.Fatalf("recovered %d results for %d inputs", len(out), len(texts))
}
for i := range out {
if strings.TrimSpace(out[i]) == "" {
t.Fatalf("item %d empty after recovery", i)
}
}
}
// TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal covers the terminal
// bisection case: one string the model refuses to translate must degrade to
// the original text, not fail the run.
func TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal(t *testing.T) {
tr := &chatBatchTranslator{model: &dropItemsChat{}}
out, err := tr.TranslateBatch(context.Background(), []string{"顽固文本"})
if err != nil {
t.Fatalf("TranslateBatch: %v", err)
}
if out[0] != "顽固文本" {
t.Fatalf("single item altered: %q", out[0])
}
}
+7
View File
@@ -141,6 +141,13 @@ func trimSpaceASCII(s string) string {
return strings.Trim(s, " \t\n\r") return strings.Trim(s, " \t\n\r")
} }
// collapseWhitespace trims and collapses every whitespace run (including
// full-width spaces) to a single ASCII space. Used as the dedupe key so
// layout-padded variants of one term share a single translation unit.
func collapseWhitespace(s string) string {
return strings.Join(strings.Fields(s), " ")
}
// 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 {
+25 -8
View File
@@ -238,15 +238,24 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
} }
} }
// Deduplicate across entries, preserving first-seen order. // 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{} unitOrder := []string{}
unitSeen := map[string]struct{}{} unitSeen := map[string]string{}
unitCanonical := map[string]string{} // raw text -> canonical raw text
for _, job := range jobs { for _, job := range jobs {
for _, u := range job.units { for _, u := range job.units {
if _, ok := unitSeen[u]; !ok { key := collapseWhitespace(u)
unitSeen[u] = struct{}{} if canonical, ok := unitSeen[key]; ok {
unitOrder = append(unitOrder, u) 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. // Oversized units are skipped rather than risking a broken LLM call.
@@ -366,6 +375,12 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
report.AppliedTranslations = len(translations) report.AppliedTranslations = len(translations)
// ---- Pass 3: rewrite affected entries, repack in original order ---- // ---- 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 { type outEntry struct {
idx int idx int
data []byte data []byte
@@ -374,7 +389,7 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([
for i := range reader.File { for i := range reader.File {
data := entryData[i] data := entryData[i]
if job, ok := jobs[i]; ok { if job, ok := jobs[i]; ok {
data = []byte(applyJob(string(data), job, translations)) data = []byte(applyJob(string(data), job, translations, alias))
} }
out = append(out, outEntry{idx: i, data: data}) out = append(out, outEntry{idx: i, data: data})
} }
@@ -518,7 +533,9 @@ func scanDrawing(src string) (*scanJob, int) {
// applyJob rewrites one entry with the resolved translations. Bytes outside // applyJob rewrites one entry with the resolved translations. Bytes outside
// the recorded edits — styles, geometry, image references — are untouched. // the recorded edits — styles, geometry, image references — are untouched.
func applyJob(src string, job *scanJob, translations map[string]string) string { // 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 { type repl struct {
start, end int start, end int
text string text string
@@ -527,7 +544,7 @@ func applyJob(src string, job *scanJob, translations map[string]string) string {
for _, e := range job.edits { for _, e := range job.edits {
switch e.kind { switch e.kind {
case editCarrier: case editCarrier:
t, ok := translations[job.units[e.unitIdx]] t, ok := translations[alias(job.units[e.unitIdx])]
if !ok { if !ok {
continue // oversized/skipped unit: keep the original bytes continue // oversized/skipped unit: keep the original bytes
} }
+31
View File
@@ -440,3 +440,34 @@ func min(a, b int) int {
} }
return b return b
} }
// TestTranslateCollapsesWhitespaceVariants covers the positional-protocol
// desync: whitespace-padded variants of one term must collapse into a single
// translation unit, or a batch containing both loses an answer (19 of 20).
func TestTranslateCollapsesWhitespaceVariants(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>` +
`<si><t>客 戶</t></si>` +
`<si><t>客户资料清单</t></si>` +
`</sst>`))
zw.Close()
tr := &fakeTranslator{}
out, report, err := Translate(context.Background(), buf.Bytes(), nil, tr)
if err != nil {
t.Fatalf("Translate: %v", err)
}
if report.TranslatedUnits != 2 {
t.Fatalf("expected 2 canonical units after whitespace collapse, got %d", report.TranslatedUnits)
}
ss := string(zipEntry(t, out, "xl/sharedStrings.xml"))
if hasCJK(ss) {
t.Fatalf("variants left untranslated:\n%s", ss)
}
if strings.Count(ss, "Customer") != 2 {
t.Fatalf("both whitespace variants should carry the glossary translation:\n%s", ss)
}
}