Google cloud -speech api return null result - php

I work with Google cloud speech API. When I run my script there is a call to the API and a response. The operation info returns data, but the result is empty.
Here is my code (where file url, file name, key url, project name and bucket name I deleted the real data):
function __construct(){
$file_url='file path.mp3';
$filename='file name.mp3';
/** Create google client **/
$client = new Google_Client();
$key='path to google key';
putenv($key);
$client->useApplicationDefaultCredentials();
/** Create storage **/
$str_config = array(
'projectId' => 'project id'
);
$storage = new StorageClient($str_config);
$bucket_name='bucket name';
$bucket=$storage->bucket($bucket_name);
$object = $bucket->object($filename);
/** Create Speech **/
$config = array(
'projectId' => 'project id',
'languageCode' => 'en-US'
);
$options = array(
"encoding"=>'LINEAR16',
"languageCode"=>"en-US",
'sampleRateHertz' => 16000
)
;
$speech = new Google\Cloud\Speech\SpeechClient($config);
$operation = $speech->beginRecognizeOperation(
$object,
$options
);
$backoff = new ExponentialBackoff(100);
$backoff->execute(function () use ($operation) {
print('Waiting for operation to complete' . PHP_EOL);
$operation->reload();
if (!$operation->isComplete()) {
throw new Exception('Job has not yet completed', 500);
}
});
if ($operation->isComplete()) {
if (empty($results = $operation->results())) {
$results = $operation->info();
}
var_dump($results, $operatimon->results());
}
}
The result i get call:
Array
(
[0] => Array
(
[name] => some name
[metadata] => Array
(
[#type]=> type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeMetadata
[progressPercent] => 100
[startTime] => 2017-07-16T19:15:58.768490Z
[lastUpdateTime] => 2017-07-16T19:15:59.999625Z
)
[done] => 1
[response] => Array
(
[#type]=> type.googleapis.com/google.cloud.speech.v1.LongRunningRecognizeResponse
[totalBilledTime] => 15s
)
)
[1] => Array
(
)
)
I tried several file type whit several encodings, can't find the right combination. Or maybe there is another problem. Pleas Help.

Solved it by using the ffmpeg library to encode the audio to flac whit mono channel.

For anyone else encountering this problem, the issue could lie in your audio file not matching the encoding you've entered in your option array.
Check this resource:
https://cloud.google.com/speech-to-text/docs/reference/rest/v1beta1/RecognitionConfig#AudioEncoding
Just like the accepted answer, by changing from "LINEAR16" to "FLAC" and converting my audio file to FLAC, it worked for me.

Related

how to get value of contentBytes from microsoft graph sdk data response in php

My code is
$expand="microsoft.graph.itemattachment/item";
$requestUrl = '/me/messages/'.$message->getId().'/attachments/?$expand= '.$expand;
$docDatas = $userClient->createCollectionRequest('GET', $requestUrl)
->setReturnType(Model\Message::class)
->setPageSize(1)
->getPage();
And want to get the outlook email attachment
Please help my
we get responses like this
Microsoft\Graph\Model\Message Object
(
[_propDict:protected] => Array
(
[#odata.type] => #microsoft.graph.fileAttachment
[#odata.mediaContentType] => application/pdf
[id] => AAMkADE2M2FjZjMyLTY2YjAtNDQwZi1hMzc3LTI2MjYwNmQ0NTJhYwBGAAAAAAB13byROi0bTImrZtPU6w6LBwAIBVrWv6bqRZ6zXuSjdaiOAAAAAAEMAAAIBVrWv6bqRZ6zXuSjdaiOAAUI9pGdAAABEgAQABzAnt_evzNMiFTD_ANAZno=
[lastModifiedDateTime] => 2022-06-28T05:54:14Z
[name] => test.pdf
[contentType] => application/pdf
[size] => 66087
[isInline] =>
[contentId] => 6D16B02E2C840A419B9F0FEBD656E618#namprd13.prod.outlook.com
[contentLocation] =>
[contentBytes] => JVBERi0xLjQKJe...
)
)
I want to get value contentBytes but how?
Again get error
enter image description here
You could either extend Message with a CustomMessage class and than have a specific getter for that property if you'll use it extensively.
My assumption was that you use msgraph-sdk-php library.
Other, simpler solution would be to just:
$expand="microsoft.graph.itemattachment/item";
$requestUrl = '/me/messages/'.$message->getId().'/attachments/?$expand= '.$expand;
$docDatas = $userClient->createCollectionRequest('GET', $requestUrl)
->setReturnType(Model\Message::class)
->setPageSize(1)
->getPage();
$properties = $docDatas->getProperties();
$contentBytes = $properties["contentBytes"];
Message extends OutlookMessage which extends Microsoft\Graph\Model\Entity. You can find getProperties method in that class.
use GuzzleHttp\Psr7\Stream;
use Microsoft\Graph\Model\Message;
use Microsoft\Graph\Model\Attachment;
$filename = 'my_file.jpg';
$filepath = '/path/to/file/my_file.jpg';
$filetype = mime_content_type($filepath);
$stream = Stream(fopen($filepath, 'r+'));
$file_attachement = new FileAttachment();
$file_attachement->setODataType('#microsoft.graph.fileAttachment');
$file_attachement->setName($filename);
$file_attachement->setContentType($filetype);
$file_attachement->setContentBytes(base64_encode($stream));
$message = new Message();
$message->setAttachments(array($file_attachement));

Fitbit API response handling in PHP

I am using a PHP library (https://github.com/djchen/oauth2-fitbit) to retreive a users Fitbit data via Oauth2. I am getting the data correctly but I am not sure how to grab a specific item from the multidimensional array response.
I am using code below but doesnt work
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Full PHP code
$provider = new djchen\OAuth2\Client\Provider\Fitbit([
'clientId' => 'xxx',
'clientSecret' => 'xxx',
'redirectUri' => 'http://xxx-env.us-east-1.elasticbeanstalk.com/a/fitbitapi'
]);
// start the session
session_start();
// If we don't have an authorization code then get one
if (!isset($_GET['code'])) {
// Fetch the authorization URL from the provider; this returns the
// urlAuthorize option and generates and applies any necessary parameters
// (e.g. state).
$authorizationUrl = $provider->getAuthorizationUrl();
// Get the state generated for you and store it to the session.
$_SESSION['oauth2state'] = $provider->getState();
// Redirect the user to the authorization URL.
header('Location: ' . $authorizationUrl);
exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
// Try to get an access token using the authorization code grant.
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// We have an access token, which we may use in authenticated
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
// The provider provides a way to get an authenticated API request for
// the service, using the access token; it returns an object conforming
// to Psr\Http\Message\RequestInterface.
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
var_dump($response['encodedId'][0]);
Response data
eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NjAzNzgxOTYsInNjb3BlcyI6InJ3ZWkgcnBybyByaHIgcmxvYyByc2xlIHJzZXQgcmFjdCByc29jIiwic3ViIjoiNEg4NU5WIiwiYXVkIjoiMjI3UUNXIiwiaXNzIjoiRml0Yml0IiwidHlwIjoiYWNjZXNzX3Rva2VuIiwiaWF0IjoxNDYwMzc0NTk2fQ.NN9OOx--3YLvwai0hl0ZRJ4MNWXlaMwcEJ_xxxxxb2382a930144c3a76e69567dcbf0d9834c574919fff8c268b378e635735f1bbf 1460378196 not expired array ( 'encodedId' => '4545NV', 'displayName'
=> 'dan', )...
I am using the same PHP library for FitBit API integration. The response you have pasted with the question is the data that is coming because of the following part of your code:
// requests against the service provider's API.
echo $accessToken->getToken() . "\n";
echo $accessToken->getRefreshToken() . "\n";
echo $accessToken->getExpires() . "\n";
echo ($accessToken->hasExpired() ? 'expired' : 'not expired') . "\n";
// Using the access token, we may look up details about the
// resource owner.
$resourceOwner = $provider->getResourceOwner($accessToken);
var_export($resourceOwner->toArray());
When you try to get the user profile from FitBit, you make the below request :
$request = $provider->getAuthenticatedRequest(
'GET',
'https://api.fitbit.com/1/user/-/profile.json',
$accessToken
);
// Make the authenticated API request and get the response.
$response = $provider->getResponse($request);
The $response comes in the below format and you can see there that "encodeId" is not the direct key there. Below is the example of var_dump($response); -
Array(
[user] => Array
(
[age] => 27
[avatar] => https://static0.fitbit.com/images/profile/defaultProfile_100_male.gif
[avatar150] => https://static0.fitbit.com/images/profile/defaultProfile_150_male.gif
[averageDailySteps] => 3165
[corporate] =>
[dateOfBirth] => 1991-04-02
[displayName] => Avtar
[distanceUnit] => METRIC
[encodedId] => 478ZBH
[features] => Array
(
[exerciseGoal] => 1
)
[foodsLocale] => en_GB
[fullName] => Avtar Gaur
[gender] => MALE
[glucoseUnit] => METRIC
[height] => 181
[heightUnit] => METRIC
[locale] => en_IN
[memberSince] => 2016-01-17
[offsetFromUTCMillis] => 19800000
[startDayOfWeek] => MONDAY
[strideLengthRunning] => 94.2
[strideLengthRunningType] => default
[strideLengthWalking] => 75.1
[strideLengthWalkingType] => default
[timezone] => Asia/Colombo
[topBadges] => Array
(
[0] => Array
(
)
[1] => Array
(
)
[2] => Array
(
)
)
[waterUnit] => METRIC
[waterUnitName] => ml
[weight] => 80
[weightUnit] => METRIC
)
)
In order to access anything in there you need to access it in this manner -
$encodedId = $response['user']['encodedId];
I hope this was helpful to you. You can ask more questions related to fitbit API as I have got it all working, including the Fitbit Subscriver API and Notifications.

No permission to use Datastream error mesage (Royal Mail Shipping API)

I am using the Royal Mail Shipping API to 'Create a Shipment Request' & to create 'Printed Labels'.
The Printed Labels requests can be done a number of ways, I want to get this printed label in a PNG format which is easily done using the API by passing 'PNG' as a parameter. However for some reason I get the following error when I var_dump the response errors:
[errorCode] => E1184
[errorDescription] => No permission to use Datastream
My code is as follows: -
public function PrintLabel($shipmentNumber, $order_tracking_id, $outputFormat = 'PDF')
{
$time = gmdate('Y-m-d\TH:i:s');
$request = array(
'integrationHeader' => array(
'dateTime' => $time,
'version' => '2',
'identification' => array(
'applicationId' => $this->api_application_id,
'transactionId' => $order_tracking_id
)
),
'shipmentNumber' => $shipmentNumber,
'outputFormat' => $outputFormat, // PDF, DS, DSPDF, PNG, DSPNG
);
$type = 'printLabel';
$response = $this->makeRequest($type, $request);
return $response->label;
} // ef
$rm = new RoyalMailLabelRequest();
$response = $rm->PrintLabel('TTT000358756GB', '276831601444829801', 'PNG');
echo $response;
Can anyone suggest why I am getting this 'no permission to use datastream error'?
Royal Mail disable PNG label generation by default and I had to request for this to be turned on.

Upload a Product Image to Shopify via PHP API

I am trying to upload a Product Image to Shopify via POST-ing a Base64 image to the API with OhShopify PHP library fork.
I have other code which successfully creates the product, but this snippet below returns NULL and I can't pinpoint why.
This code runs seemingly successfully 'makes it' and creates a new ShopifyClient object, but the var_dump on the $response['src'] returns NULL and the image never makes it. Am I missing something?
<?php
define('SHOPIFY_API_KEY', 'abc');
define('SHOPIFY_SECRET', '123');
define('SHOPIFY_SCOPE', 'write_content,write_products,write_orders');
include_once('lib/ohShopify/shopify.php');
// Check for shopify authentication
if (isset($_SESSION['shop']) && isset($_SESSION['token'])){
$shopifyClient = new ShopifyClient($_SESSION['shop'], $_SESSION['token'], SHOPIFY_API_KEY, SHOPIFY_SECRET);
echo 'made it';
} else{
echo 'token and shop not set up';
}
$testBase64 = "loooooooooooooong string of text";
try {
$theImages = array
(
"image"=>array
(
"position" => 1,
"attachment" => $testBase64
)
);
$response = $shopifyClient->call('POST', '/admin/products/#326021139/images.json', $theImages);
var_dump($response['src']);
} catch (ShopifyApiException $ex) {
var_dump($ex);
}
?>
The images array is 1 more array :
$image = file_get_contents("Images/test.jpg");
$base64 = base64_encode($image);
$products_array = array
(
'product' => array
(
'title' => $_POST['title'],
'body_html' => $_POST['body_html'],
'vendor' => $_POST['vendor'],
'product_type' => $_POST['type'],
'images' => array(
array(
'filename' => 'test.jpg',
'attachment' => $base64
)
)
)
);
If you base64 encode your image, it also works from local files.
The only thing you did wrong was the extra array at images:
$image = file_get_contents("Images/test.jpg");
$base64 = base64_encode($image);
$products_array = array
(
'product' => array
(
'title' => $_POST['title'],
'body_html' => $_POST['body_html'],
'vendor' => $_POST['vendor'],
'product_type' => $_POST['type'],
'images' => array(
array(
'filename' => 'test.jpg',
'attachment' => $base64
)
)
)
);
Stack Overflow suffers with all the drive-by zealots down voting posts/questions without a statement as to their reasons. If you have a reason, then please pontificate rather then being an anonymous coward.
For those having the same issue or question, I ultimately could NOT get this to work but came up with a solution that I would initially take the base64 encoded image, save it as a file on server, then pass the URL of the file to a Product creation API call.
Essentially:
file_put_contents( 'img_uploads/'.$filename, base64_decode($encoded_img) );
...
try {
// Create a new product
$product = array
(
"product"=>array
(
"title"=>$title,
"body_html"=>$body_html,
"vendor"=>$vendor,
"product_type"=>$productType,
"variants"=>array ("price"=>$price),
"images"=>array ("src"=>$image)
)
);
$response = $shopifyClient->call('POST', '/admin/products.json', $product);

Posting photo via Facebook graph no longer working

I'm trying to post a photo using the php-sdk - all was working for months successfully but all of the sudden no dice.
Other functions are still working with the same code base (ie: posting messages to wall) - its just the posting of photos that broke on my side.
try {
$data = $facebook->api('/me/photos', 'post', $args);
} catch (FacebookApiException $e) {
print_r($e);}
Is dumping:
FacebookApiException Object ( [result:protected] => Array ( [error_code] => 3 [error] => Array ( [message] => No URL set! [type] => CurlException ) ) [message:protected] => No URL set! [string:private] => [code:protected] => 3 [file:protected] => /locationofmy/base_facebook.php [line:protected] => 818 [trace:private] => Array ( [0] => Array [..............]
From the FB php-sdk lines 818:
if ($result === false) {
$e = new FacebookApiException(array(
'error_code' => curl_errno($ch),
'error' => array(
'message' => curl_error($ch),
'type' => 'CurlException',
),
));
curl_close($ch);
throw $e;
}
curl_close($ch);
return $result;
}
This was working for a long time - has something changed on Facebooks side?
EDIT: php-sdk version: 3.1.1
EDIT 2:
$tag = array(
'tag_uid' => 'acct_num',
'x' => 0,
'y' => 0
);
$tags[] = $tag;
$args = array(
'message' => $item_description,
'image' => '#' . realpath($temp_path . $tempFile),
'tags' => $tags,
);
Probably that the file doesnt exist, or the file system can't serve it anymore. Can you confirm "$temp_path . $tempFile" - the error is no URL, usually that means no real path to image. I suspect, that the images are missing and/or your servers filled up and no local images are saving. (Yes, this has happened to me before!)
Try changing the image to source. I believe this should fix your issue.
The Facebook API requires a source field but I did not see anything about an image field.
You may also have to pass the actual file contents instead of the real_path (based on the example). Or, alternatively, pass an external URL (based on my understanding of the documentation).
Source: https://developers.facebook.com/docs/reference/api/photo/
Example: https://developers.facebook.com/blog/post/498/

Categories