This commit is contained in:
1 parent
db8472bf28
commit
c6088aeb4b
4 files changed
+334
-126
No files matched your search
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -12,6 +13,7 @@ import (
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/chat"
|
||||
"academy/internal/types"
|
||||
"academy/internal/types/interfaces"
|
||||
"academy/internal/utils"
|
||||
"academy/internal/xlsxtranslate"
|
||||
)
|
||||
@@ -28,41 +30,55 @@ var xlsxMagic = []byte{0x50, 0x4B, 0x03, 0x04}
|
||||
var legacyXLSMagicBytes = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}
|
||||
|
||||
const xlsxTranslateDescription = `Translate a Chinese engineering Excel workbook (SIP / SOP / inspection standard,
|
||||
.xlsx only) into English and deliver the translated workbook as a downloadable output file.
|
||||
.xlsx only) into English and deliver the translated workbook to the user.
|
||||
|
||||
Pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments> as file_path.
|
||||
Reference the uploaded workbook by its sandbox path (file_path, from <sandbox_attachments>) or by the
|
||||
uploaded attachment's file name (attachment_name) — pass whichever the conversation shows.
|
||||
The tool preserves the workbook exactly — merged cells, images, styles, formulas and sheet layout are
|
||||
copied byte-for-byte; only Chinese text (cell strings, inline strings and drawing text boxes) is
|
||||
translated. Part numbers, tolerances and dates are protected as placeholders and never altered.
|
||||
A verification report (residual Chinese, number/part integrity) is returned; the translated workbook
|
||||
lands in the artifact output directory for the user to download.`
|
||||
A verification report (residual Chinese, number/part integrity) is returned together with the
|
||||
translated workbook as a downloadable deliverable.`
|
||||
|
||||
// XlsxTranslateInput is the tool argument schema.
|
||||
// XlsxTranslateInput is the tool argument schema. Exactly one of file_path /
|
||||
// attachment_name is required; file_path wins when both are given.
|
||||
type XlsxTranslateInput struct {
|
||||
FilePath string `json:"file_path" jsonschema:"Absolute sandbox path of the uploaded .xlsx workbook, taken from <sandbox_attachments> (for example /workspace/input/part.xlsx)"`
|
||||
FilePath string `json:"file_path,omitempty" jsonschema:"Absolute sandbox path of the uploaded workbook when <sandbox_attachments> is present (for example /workspace/input/part.xlsx)"`
|
||||
AttachmentName string `json:"attachment_name,omitempty" jsonschema:"File name of the uploaded attachment when the conversation shows no sandbox workspace (for example part.xlsx)"`
|
||||
}
|
||||
|
||||
// sessionDirEnsurer is the slice of SessionFileStore that provisions the
|
||||
// output directory before writing.
|
||||
type sessionDirEnsurer interface {
|
||||
// SessionDirEnsurer is the slice of SessionFileStore that provisions the
|
||||
// output directory before writing. Exported because the agent service wires
|
||||
// the same store into both the sink and the ensurer slots.
|
||||
type SessionDirEnsurer interface {
|
||||
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
|
||||
}
|
||||
|
||||
// XlsxTranslateTool translates an uploaded workbook through the
|
||||
// xlsxtranslate pipeline, writing the English deliverable into the session
|
||||
// artifact output directory.
|
||||
// XlsxTranslateTool translates an uploaded workbook through the xlsxtranslate
|
||||
// pipeline and delivers the English workbook as a session deliverable.
|
||||
//
|
||||
// Delivery adapts to the session's capabilities: with a workspace sandbox the
|
||||
// output lands in the artifact output directory (collected as a downloadable
|
||||
// artifact); without one the output is saved as a session attachment through
|
||||
// the temporary-document service and linked by preview URL. The same
|
||||
// adaptation applies to reading the upload. This is why registration must NOT
|
||||
// be gated on the sandbox: a deployment without a workspace sandbox would
|
||||
// otherwise hide the tool while the agent prompt still instructs the model to
|
||||
// call it ("tool not found").
|
||||
type XlsxTranslateTool struct {
|
||||
BaseTool
|
||||
store SandboxFileSink
|
||||
ensure sessionDirEnsurer
|
||||
ensure SessionDirEnsurer
|
||||
tempDoc interfaces.TemporaryDocumentService
|
||||
model chat.Chat
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
// NewXlsxTranslateTool constructs the tool. store and model MUST NOT be nil;
|
||||
// the tool is only registered when a session sandbox exists, because the
|
||||
// deliverable is delivered through the artifact output directory.
|
||||
func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model chat.Chat) *XlsxTranslateTool {
|
||||
// NewXlsxTranslateTool constructs the tool. store/ensure may be nil when the
|
||||
// session has no workspace sandbox (the temporary-document channel is used
|
||||
// instead); tempDoc may be nil only when neither channel can exist. model
|
||||
// MUST NOT be nil.
|
||||
func NewXlsxTranslateTool(store SandboxFileSink, ensure SessionDirEnsurer, tempDoc interfaces.TemporaryDocumentService, model chat.Chat) *XlsxTranslateTool {
|
||||
return &XlsxTranslateTool{
|
||||
BaseTool: BaseTool{
|
||||
name: ToolXlsxTranslate,
|
||||
@@ -71,6 +87,7 @@ func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model
|
||||
},
|
||||
store: store,
|
||||
ensure: ensure,
|
||||
tempDoc: tempDoc,
|
||||
model: model,
|
||||
timeout: 20 * time.Minute,
|
||||
}
|
||||
@@ -82,41 +99,21 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
if err := json.Unmarshal(args, &input); err != nil {
|
||||
return &types.ToolResult{Success: false, Error: fmt.Sprintf("invalid arguments: %v", err)}, nil
|
||||
}
|
||||
filePath := strings.TrimSpace(input.FilePath)
|
||||
if filePath == "" {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: "file_path is required: pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments>"}, nil
|
||||
}
|
||||
sessionID := resolveSessionID(ctx)
|
||||
if sessionID == "" {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: "no session ID in context; xlsx_translate must run inside an agent turn"}, nil
|
||||
}
|
||||
layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store)
|
||||
if layoutErr != nil {
|
||||
return layoutErr, nil
|
||||
}
|
||||
// Same relative-path semantics as the file primitives: a bare filename
|
||||
// or workspace-relative path resolves against the workspace root.
|
||||
filePath = resolveIn(layout, filePath)
|
||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||
|
||||
lower := strings.ToLower(filePath)
|
||||
if !strings.HasSuffix(lower, ".xlsx") {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", path.Base(filePath))}, nil
|
||||
}
|
||||
|
||||
data, err := t.store.ReadSessionFile(ctx, sessionID, filePath)
|
||||
if err != nil {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("failed to read %s: %v", filePath, err)}, nil
|
||||
}
|
||||
// ---- Resolve the input workbook ----
|
||||
data, source := t.readInput(ctx, sessionID, tenantID, &input)
|
||||
if len(data) == 0 {
|
||||
return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is empty", filePath)}, nil
|
||||
return &types.ToolResult{Success: false, Error: source}, nil // source carries the error text
|
||||
}
|
||||
if len(data) > maxTranslateBytes {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("%s is %d MB, above the %d MB translation limit", path.Base(filePath), len(data)>>20, maxTranslateBytes>>20)}, nil
|
||||
Error: fmt.Sprintf("workbook is %d MB, above the %d MB translation limit", len(data)>>20, maxTranslateBytes>>20)}, nil
|
||||
}
|
||||
if bytes.HasPrefix(data, legacyXLSMagicBytes) {
|
||||
return &types.ToolResult{Success: false,
|
||||
@@ -124,43 +121,67 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
}
|
||||
if !bytes.HasPrefix(data, xlsxMagic) {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(filePath))}, nil
|
||||
Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(source))}, nil
|
||||
}
|
||||
baseName := path.Base(source)
|
||||
if !strings.HasSuffix(strings.ToLower(baseName), ".xlsx") {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", baseName)}, nil
|
||||
}
|
||||
|
||||
// ---- Translate ----
|
||||
runCtx, cancel := context.WithTimeout(ctx, t.timeout)
|
||||
defer cancel()
|
||||
translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{
|
||||
BatchSize: 40,
|
||||
}, &chatBatchTranslator{model: t.model})
|
||||
if err != nil {
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, filePath, err)
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, source, err)
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("translation failed: %v", err)}, nil
|
||||
}
|
||||
|
||||
baseName := path.Base(filePath)
|
||||
ext := path.Ext(baseName)
|
||||
outName := strings.TrimSuffix(baseName, ext) + "_EN.xlsx"
|
||||
outputDir := layoutOutputDir(layout)
|
||||
if outputDir == "" {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: "session has no artifact output directory; the sandbox workspace is unavailable"}, nil
|
||||
}
|
||||
outPath := outputDir + "/" + outName
|
||||
if t.ensure != nil {
|
||||
if err := t.ensure.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] ensure output dir failed: %v", err)
|
||||
|
||||
// ---- Deliver: sandbox artifact dir when available, attachment otherwise ----
|
||||
var deliverable string
|
||||
var outputLinks []string
|
||||
if t.store != nil {
|
||||
if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil {
|
||||
if outputDir := layoutOutputDir(layout); outputDir != "" {
|
||||
outPath := outputDir + "/" + outName
|
||||
if t.ensure != nil {
|
||||
if err := t.ensure.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] ensure output dir failed: %v", err)
|
||||
}
|
||||
}
|
||||
if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err == nil {
|
||||
deliverable = outPath
|
||||
outputLinks = sandboxOutputLinksIn(outputDir, outPath)
|
||||
} else {
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox write failed, falling back to attachment: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err != nil {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("failed to write translated workbook to %s: %v", outPath, err)}, nil
|
||||
if deliverable == "" {
|
||||
url, err := t.saveAsAttachment(ctx, tenantID, sessionID, outName, translated)
|
||||
if err != nil {
|
||||
return &types.ToolResult{Success: false,
|
||||
Error: fmt.Sprintf("translation finished but delivering the workbook failed: %v", err)}, nil
|
||||
}
|
||||
deliverable = url
|
||||
}
|
||||
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
|
||||
sessionID, filePath, outPath, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
|
||||
sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString("Translation finished. The English workbook is saved as **" + outName + "** in the output directory (available as a downloadable artifact).\n\n")
|
||||
if len(outputLinks) > 0 {
|
||||
b.WriteString("Translation finished. The English workbook **" + outName + "** is saved in the output directory (available as a downloadable artifact).\n\n")
|
||||
} else {
|
||||
b.WriteString("Translation finished. Download the English workbook **" + outName + "** here: " + deliverable + "\n\n")
|
||||
}
|
||||
b.WriteString(report.Markdown())
|
||||
if report.ResidualCJKCount > 0 {
|
||||
b.WriteString("\nNote: residual Chinese remains (see samples above) — usually oversized or untranslatable entries. Review them manually.\n")
|
||||
@@ -172,9 +193,9 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
return &types.ToolResult{
|
||||
Success: true,
|
||||
Output: b.String(),
|
||||
OutputFiles: sandboxOutputLinksIn(outputDir, outPath),
|
||||
OutputFiles: outputLinks,
|
||||
Data: map[string]interface{}{
|
||||
"output_path": outPath,
|
||||
"deliverable": deliverable,
|
||||
"translated_units": report.TranslatedUnits,
|
||||
"glossary_hits": report.GlossaryHits,
|
||||
"llm_calls": report.LLMCalls,
|
||||
@@ -186,6 +207,69 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
|
||||
}, nil
|
||||
}
|
||||
|
||||
// readInput fetches the workbook bytes: sandbox first (staged attachment),
|
||||
// temporary-document lookup second. The returned string is the resolved
|
||||
// source path/name, or the error text when no bytes could be read.
|
||||
func (t *XlsxTranslateTool) readInput(ctx context.Context, sessionID string, tenantID uint64, input *XlsxTranslateInput) ([]byte, string) {
|
||||
if t.store != nil && strings.TrimSpace(input.FilePath) != "" {
|
||||
if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil {
|
||||
clean := resolveIn(layout, input.FilePath)
|
||||
data, err := t.store.ReadSessionFile(ctx, sessionID, clean)
|
||||
if err == nil && len(data) > 0 {
|
||||
return data, clean
|
||||
}
|
||||
logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox read of %s failed (%v); trying session attachments", clean, err)
|
||||
}
|
||||
}
|
||||
if t.tempDoc == nil {
|
||||
return nil, "no input source: pass file_path when a sandbox workspace is present, or attachment_name for the uploaded attachment"
|
||||
}
|
||||
name := strings.TrimSpace(input.AttachmentName)
|
||||
if name == "" {
|
||||
name = path.Base(strings.TrimSpace(input.FilePath))
|
||||
}
|
||||
if name == "" || name == "." {
|
||||
return nil, "input required: pass file_path (sandbox path) or attachment_name (uploaded file name)"
|
||||
}
|
||||
docs, err := t.tempDoc.List(ctx, tenantID, sessionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Sprintf("failed to list session attachments: %v", err)
|
||||
}
|
||||
var doc *types.TemporaryDocument
|
||||
for i := range docs { // last match wins: the newest upload with that name
|
||||
if docs[i] != nil && docs[i].FileName == name {
|
||||
doc = docs[i]
|
||||
}
|
||||
}
|
||||
if doc == nil {
|
||||
return nil, fmt.Sprintf("no uploaded attachment named %q found in this session", name)
|
||||
}
|
||||
reader, _, err := t.tempDoc.OpenFile(ctx, tenantID, sessionID, doc.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Sprintf("failed to open attachment %q: %v", name, err)
|
||||
}
|
||||
defer reader.Close()
|
||||
data, err := io.ReadAll(reader)
|
||||
if err != nil {
|
||||
return nil, fmt.Sprintf("failed to read attachment %q: %v", name, err)
|
||||
}
|
||||
return data, doc.FileName
|
||||
}
|
||||
|
||||
// saveAsAttachment stores the translated workbook as a session attachment and
|
||||
// returns its preview URL, which streams the original bytes.
|
||||
func (t *XlsxTranslateTool) saveAsAttachment(ctx context.Context, tenantID uint64, sessionID, name string, data []byte) (string, error) {
|
||||
if t.tempDoc == nil {
|
||||
return "", fmt.Errorf("no delivery channel: session has neither a workspace sandbox nor the attachment service")
|
||||
}
|
||||
const xlsxMime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
doc, err := t.tempDoc.Create(ctx, tenantID, sessionID, name, xlsxMime, int64(len(data)), bytes.NewReader(data), types.TemporaryDocumentCreateOptions{})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "/api/v1/sessions/" + sessionID + "/attachments/" + doc.ID + "/preview", nil
|
||||
}
|
||||
|
||||
// chatBatchTranslator adapts the session chat model to the engine's
|
||||
// Translator interface: one call = one JSON array round trip.
|
||||
type chatBatchTranslator struct {
|
||||
|
||||
Reference in new issue
Block a user