400 调用者的项目与父项目不匹配

400 Caller's project doesn't match parent project

我有这段代码,基本上使用云翻译 API 将文本从一种语言翻译成另一种语言。问题是这段代码总是抛出错误:“调用者的项目与父项目不匹配”。可能是什么问题?

translation_separator = "translated_text: "
language_separator = "detected_language_code: "
translate_client = translate.TranslationServiceClient()
# parent = translate_client.location_path(
        #     self.translate_project_id, self.translate_location
        # )
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = (
                os.getcwd()
                + "/translator_credentials.json"
        )

        # Text can also be a sequence of strings, in which case this method
        # will return a sequence of results for each text.
try:
            result = str(
                translate_client.translate_text(
                    request={
                        "contents": [text],
                        "target_language_code": self.target_language_code,
                        "parent": f'projects/{self.translate_project_id}/'
                                  f'locations/{self.translate_location}',
                        "model": self.translate_model
                    }
                )
            )
            print(result)
except Exception as e:
            print("error here>>>>>", e)

您的问题似乎与您在应用程序中使用的身份验证方法有关,请遵循 guide for authention methods with the translate API. If you are trying to pass the credentials using code, you can explicitly point to your service account file in code with:

def explicit():
    from google.cloud import storage

    # Explicitly use service account credentials by specifying the private key
    # file.
    storage_client = storage.Client.from_service_account_json(
        'service_account.json')
        

此外,还有一个 codelab 用于开始使用 API 和 Python 进行翻译,这是 运行 的一个很好的逐步入门指南将 API 翻译成 Python.

如果问题仍然存在,您可以尝试为 Google 支持创建 Public Issue Tracker