在未在Google环境中运行的JAVA代码中,人们如何使用经过训练的翻译模型?

时间:2019-06-13 20:35:36

标签: translation automl google-translation-api

我认为我似乎缺少明显的东西。我们已经使用Google翻译API已有一段时间了,现在我们想“升级”到经过定制训练的模型,而不是默认的nmt。

我们已经上传了文本,对其进行了培训,现在有了模型。在Google控制台的“预测”标签中,效果很好。那么,现在呢?

这是我们今天使用的代码:

        translate = TranslateOptions
            .newBuilder()
            .setCredentials(ServiceAccountCredentials.fromStream(googleCredentials))
            .build()
            .getService();

                translate.translate(
                    text,
                    TranslateOption.sourceLanguage(fromLng),
                    TranslateOption.targetLanguage(toLng),
                    TranslateOption.model(model));

其中的模型是“ nmt”(或“基础”)...我应该能够放入训练完成时创建的新训练的模型代码吗?当我尝试时,它返回400错误并显示消息:

   "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "message" : "Invalid Value",
    "reason" : "invalid"
  } ],
  "message" : "Invalid Value"

尝试使用此处记录的不同代码:https://cloud.google.com/translate/docs/quickstart-client-libraries-v3 会产生其他错误,例如:“信息:无法检测我们是否在Google Compute Engine上运行。”

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

我们去了...寻找下一个这样做的人:

<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-automl</artifactId>
    <version>0.97.0-beta</version>
</dependency>

代码:

private PredictionServiceClient predictionClient; 
private ModelName modelName; 

public GoogleTranslationServiceTrained(final byte[] googleCredentials) throws IOException {
    super();

    PredictionServiceSettings settings = PredictionServiceSettings
            .newBuilder()
            .setCredentialsProvider(new CredentialsProvider() {
                @Override
                public Credentials getCredentials() throws IOException {
                    return ServiceAccountCredentials.fromStream(new ByteArrayInputStream(googleCredentials));
                }
            }).build();

    // Instantiate client for prediction service.
    predictionClient = PredictionServiceClient.create(settings);

    // Get the full path of the model.
    modelName = ModelName.of("xxxx", "us-central1", "yyy");
}

public String getRemoteTranslate(String text) {
    TextSnippet textSnippet = TextSnippet.newBuilder().setContent(text).build();

    // Set the payload by giving the content of the file.
    ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();

    // Additional parameters that can be provided for prediction
    Map<String, String> params = new HashMap<>();

    PredictResponse response = predictionClient.predict(modelName, payload, params);
    TextSnippet translatedContent = response.getPayload(0).getTranslation().getTranslatedContent();

    return StringEscapeUtils.unescapeHtml4(translatedContent.getContent());

}