Creating Client for Amazon Comprehend with AWS for PHP

0

I recently updated from version 1 of the AWS SDK for PHP to version 3 of the AWS SDK so that I could start testing scripts using the Comprehend and Textract applications. I was able to connect through version 3 and utilize S3 using the "new S3Client()" command. There's extensive documentation regarding functions for Comprehend and Textract, but I can't figure out what the similar new client string is for each service. I've tried:
$cc = new comprehendClient();
$cc = new AWSComprehend();
$cc = new createComprehend();
and more and none of these have worked. If anyone can recommend a fix that would be really helpful. Likewise, if there's an online code repository I should look at that would be helpful. I see plenty of code samples for S3, but none for other applications (at least with SDK for PHP). Thanks!

zbdev
質問済み 5年前955ビュー
4回答
0
承認された回答

In the below code, enter in your access key and secret key
Note: it is bad practice to hardcode access key and secret key in code, but do it here just to show that it works.
Link: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_hardcoded.html
Also, in your original code, you used single quotes around the

    'key' => '$access_key',
    'secret' => '$secret_key'

You need to remove the single quotes because that causes the text within single quotes to appear "as is". i.e. the code will see '$access_key' instead of the value assigned to the variable $access_key. So changed to:

    'key' => "$access_key",
    'secret' => "$secret_key"

Try the code below (after changing the access key/secret key).

<?php

  chdir("C:\aws_v3");
  require 'aws-autoloader.php';
  use Aws\Comprehend\ComprehendClient;

  $access_key = "<enter your access key here"; 
  $secret_key = "<enter your secret key here";

  $client = new ComprehendClient([
  'region' => 'us-east-1',
    'version' => 'latest',
    'credentials' => [
    'key' => "$access_key",
    'secret' => "$secret_key"
    ] 
   ]);


  $result = $client->detectSentiment([
    'LanguageCode' => 'en',
    'Text' => 'It was such a wonderful day full of laughter and smiles',
    ]);

    print($result);
?>

Those changes should get you further. If you still are getting the 'cURL error 28' error, let me know..
-randy

回答済み 5年前
profile picture
エキスパート
レビュー済み 1ヶ月前
0

Hi,
Here is an example of Comprehend using the AWS SDK for PHP version 3.

<?php
   require '/root/vendor/autoload.php';
   use Aws\Comprehend\ComprehendClient;

   $client = new ComprehendClient([
       'region' => 'us-east-1',
       'version' => '2017-11-27'
    ]);

   $result = $client->detectSentiment([
      'LanguageCode' => 'en',
      'Text' => 'It was such a wonderful day full of laughter and smiles',
]);

  print($result);
?>

And this is the output:

[root@ip-172-31-88-126 work]# php test.php
Model Data
----------
Data can be retrieved from the model object using the get() method of the
model (e.g., `$result->get($key)`) or "accessing the result like an
associative array (e.g. `$result['key']`). You can also execute JMESPath
expressions on the result data using the search() method.

{
    "Sentiment": "POSITIVE",
    "SentimentScore": {
        "Positive": 0.9989492297172546,
        "Negative": 1.9858167433994822e-5,
        "Neutral": 0.0005906018195673823,
        "Mixed": 0.0004403026250656694
    },
    "@metadata": {
        "statusCode": 200,
        "effectiveUri": "https:\/\/comprehend.us-east-1.amazonaws.com",
        "headers": {
            "x-amzn-requestid": "1c39a68f-078e-4c46-be8b-4890ac395499",
            "content-type": "application\/x-amz-json-1.1",
            "content-length": "166",
            "date": "Sat, 31 Aug 2019 03:42:38 GMT"
        },
        "transferStats": {
            "http": [
                []
            ]
        }
    }
}

I used the following links to help build the above code:
Link: https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.Comprehend.ComprehendClient.html
Link: https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-comprehend-2017-11-27.html
Link: https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/s3-examples-creating-buckets.html

Hope this helps!
-randy

回答済み 5年前
0

Thanks Randy. This was helpful - making progress but not quite there yet. I had to make some slight changes and used a different require statement and also added to credentials into the new client initialization statement (Initialization 2 in the code below). When I include this, I get the following message:

"Fatal error: Uncaught exception 'Aws\Comprehend\Exception\ComprehendException' with message 'Error executing "DetectSentiment" on "https://comprehend.us-east-1.amazonaws.com"; AWS HTTP error: Client error: POST https://comprehend.us-east-1.amazonaws.com resulted in a 400 Bad Request response: {"__type":"UnrecognizedClientException","message":"The security token included in the request is invalid."} UnrecognizedClientException (client): The security token included in the request is invalid. - {"__type":"UnrecognizedClientException","message":"The security token included in the request is invalid."}' exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: POST https://comprehend.us-east-1.amazonaws.com resulted in a 400 Bad Request response: {"__type":"UnrecognizedClientException","message":"The security token included in the request is invalid."} ' in C:\aws_v3\GuzzleHttp\Exception\RequestException.php:113 Stack trace: #0"/

I think this likely means that I still have to tweak the connection string. The other error I get when I use the initialization string you provided (Initialization 1 below) involves cURL:

Uncaught exception 'GuzzleHttp\Exception\ConnectException' with message 'cURL error 28: Connection timed out after 1000 milliseconds (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in C:\aws_v3\GuzzleHttp\Handler\CurlFactory.php:185 Stack trace: #0

My guess is that the first error / initialization string is closer to what I'll ultimately need to get past this. I've tried some other function calls with Amazon Textract and I'm running into the same pair of errors. Let me know if you have any other thoughts. Thanks!

Code:

<?php chdir("C:\aws_v3"); //require '/root/vendor/autoload.php'; require 'aws-autoloader.php'; use Aws\Comprehend\ComprehendClient; //Initialization 1 $client = new ComprehendClient(\[ 'region' => 'us-east-1', 'version' => 'latest' ]); //Initialization2 /* $access_key = "ACCESS_KEY"; $secret_key = "SECRET_KEY"; $client = new ComprehendClient(\[ 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => \[ 'key' => '$access_key', 'secret' => '$secret_key' ] ]); */ $result = $client->detectSentiment(\[ 'LanguageCode' => 'en', 'Text' => 'It was such a wonderful day full of laughter and smiles', ]); print($result); ?>
zbdev
回答済み 5年前
0

This works. Just had to change the single apostrophe to quotes around the access key / secret key and it did the trick! I applied similar changes on the new client code for Textract and that did the trick as well.

Thanks again!

zbdev
回答済み 5年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ