// 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") } // 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. 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 }