首页 > 解决方案 > 如何使用谷歌云维护的参考词汇表实现谷歌云翻译 API 来翻译前端数据?

问题描述

如何在前端实现谷歌云翻译 API,使用谷歌云存储桶中维护的参考词汇表将整个数据翻译成目标语言?

我知道以下代码片段可用于使用词汇表在后端翻译数据。

public static void translateTextWithGlossary(String projectId, String sourceLanguage, String targetLanguage,
        String text, String glossaryId) throws IOException {

    // Initialize client that will be used to send requests. This client only needs
    // to be created
    // once, and can be reused for multiple requests. After completing all of your
    // requests, call
    // the "close" method on the client to safely clean up any remaining background
    // resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
        // Supported Locations: `global`, [glossary location], or [model location]
        // Glossaries must be hosted in `us-central1`
        // Custom Models must use the same location as your model. (us-central1)
        String location = "us-central1";
        LocationName parent = LocationName.of(projectId, location);

        GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId);
        TranslateTextGlossaryConfig glossaryConfig = TranslateTextGlossaryConfig.newBuilder()
                .setGlossary(glossaryName.toString()).build();

        // Supported Mime Types:
        // https://cloud.google.com/translate/docs/supported-formats
        TranslateTextRequest request = TranslateTextRequest.newBuilder().setParent(parent.toString())
                .setMimeType("text/plain").setSourceLanguageCode(sourceLanguage)
                .setTargetLanguageCode(targetLanguage).addContents(text).setGlossaryConfig(glossaryConfig).build();

        TranslateTextResponse response = client.translateText(request);

        // Display the translation for each input text provided
        for (Translation translation : response.getGlossaryTranslationsList()) {
            System.out.printf("\n\nTranslated text: \n%s\n", translation.getTranslatedText());
        }
    }
}

标签: javascriptspring-mvcfrontendgoogle-translate

解决方案


推荐阅读