首页 > 解决方案 > 无法在 Cloud Translation API v3 中创建词汇表

问题描述

我在 PHP 中使用 Cloud Translation API v3。我完成了设置过程并尝试了此处显示的简单翻译,并且成功了。然后我想测试词汇表,所以我尝试按照这里的描述添加一个。当我尝试调用该函数时:

protected function createGlossary()
    {
        $translationServiceClient = new TranslationServiceClient();
        
        $projectId = 'my-project-id';
        $glossaryId = 'my-new-glossary';
        $inputUri = 'gs://bucket/file.csv';
        
        $formattedParent = $translationServiceClient->locationName(
            $projectId,
            'us-central1'
        );
        $formattedName = $translationServiceClient->glossaryName(
            $projectId,
            'us-central1',
            $glossaryId
        );
        $languageCodesElement = 'pl';
        $languageCodesElement2 = 'en';
        $languageCodes = [$languageCodesElement, $languageCodesElement2];
        $languageCodesSet = new LanguageCodesSet();
        $languageCodesSet->setLanguageCodes($languageCodes);
        $gcsSource = (new GcsSource())
            ->setInputUri($inputUri);
        $inputConfig = (new GlossaryInputConfig())
            ->setGcsSource($gcsSource);
        $glossary = (new Glossary())
            ->setName($formattedName)
            ->setLanguageCodesSet($languageCodesSet)
            ->setInputConfig($inputConfig);

        try {
            $operationResponse = $translationServiceClient->createGlossary(
                $formattedParent,
                $glossary
            );
            $operationResponse->pollUntilComplete();
            if ($operationResponse->operationSucceeded()) {
                $response = $operationResponse->getResult();
                printf('Created Glossary.' . PHP_EOL);
                printf('Glossary name: %s' . PHP_EOL, $response->getName());
                printf('Entry count: %s' . PHP_EOL, $response->getEntryCount());
                printf(
                    'Input URI: %s' . PHP_EOL,
                    $response->getInputConfig()
                        ->getGcsSource()
                        ->getInputUri()
                );
            } else {
                $error = $operationResponse->getError();
                // handleError($error)
            }
        } finally {
            $translationServiceClient->close();
        }
    }

它返回一个错误:

Failed to build request, as the provided path (google.longrunning.Operations/GetOperation) was not found in the configuration.

它在$operationResponse->pollUntilComplete();. 存储桶中的文件仅包含一行 - test,test.

然后,当我尝试调用列出所有词汇表的函数时,它可以工作,但不会返回任何内容。

什么可能导致此问题,如何添加词汇表?

标签: phpgoogle-cloud-platformgoogle-translategoogle-translation-api

解决方案


您需要为 PHP 安装 gRPC 扩展。

信息:https ://cloud.google.com/php/grpc

为 PHP 安装 gRPC

gRPC 是一个现代的、开源的、高性能的远程过程调用框架。如果要将 PHP 客户端库用于支持 gRPC 的 API,则必须为 PHP 安装 gRPC。本教程介绍了如何安装和启用 gRPC。

为 PHP 安装 gRPC 扩展。

sudo pecl install grpc

为 PHP 启用 gRPC 扩展。

在 php.ini 文件中的任意位置添加这一行,例如 /etc/php7/cli/php.ini。你可以通过运行 php --ini 找到这个文件。

extension=grpc.so

推荐阅读