import (
"context"
"fmt"
"io"
translate "cloud.google.com/go/translate/apiv3"
"cloud.google.com/go/translate/apiv3/translatepb"
)
// batchTranslateTextWithModel translates a large volume of text in asynchronous batch mode.
func batchTranslateTextWithModel(w io.Writer, projectID string, location string, inputURI string, outputURI string, sourceLang string, targetLang string, modelID string) error {
// projectID := "my-project-id"
// location := "us-central1"
// inputURI := "gs://cloud-samples-data/text.txt"
// outputURI := "gs://YOUR_BUCKET_ID/path_to_store_results/"
// sourceLang := "en"
// targetLang := "de"
// modelID := "your-model-id"
ctx := context.Background()
client, err := translate.NewTranslationClient(ctx)
if err != nil {
return fmt.Errorf("NewTranslationClient: %w", err)
}
defer client.Close()
req := &translatepb.BatchTranslateTextRequest{
Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
SourceLanguageCode: sourceLang,
TargetLanguageCodes: []string{targetLang},
InputConfigs: []*translatepb.InputConfig{
{
Source: &translatepb.InputConfig_GcsSource{
GcsSource: &translatepb.GcsSource{InputUri: inputURI},
},
// Optional. Can be "text/plain" or "text/html".
MimeType: "text/plain",
},
},
OutputConfig: &translatepb.OutputConfig{
Destination: &translatepb.OutputConfig_GcsDestination{
GcsDestination: &translatepb.GcsDestination{
OutputUriPrefix: outputURI,
},
},
},
Models: map[string]string{
targetLang: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
},
}
// The BatchTranslateText operation is async.
op, err := client.BatchTranslateText(ctx, req)
if err != nil {
return fmt.Errorf("BatchTranslateText: %w", err)
}
fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())
resp, err := op.Wait(ctx)
if err != nil {
return fmt.Errorf("Wait: %w", err)
}
fmt.Fprintf(w, "Total characters: %v\n", resp.GetTotalCharacters())
fmt.Fprintf(w, "Translated characters: %v\n", resp.GetTranslatedCharacters())
return nil
}