This commit is contained in:
1 parent
5583d7b74b
commit
db8472bf28
15 files changed
+2260
-2
No files matched your search
@@ -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>检查 & 包装 <OK></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, "&") || !strings.Contains(ss, "<OK>") {
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user