Cognitive Service Face api use local image - PHP - php

I am trying to upload an local image to the face API by using PHP, I use the sample code to call the api and it is fine when i am using JSON. but it get stuck when change to octet-stream. i use the below code by referencing "https://pear.php.net/manual/en/package.http.http-request2.request.php"
$image = "images/face-021.jpg";
$fp = fopen($image, 'r+');
$request->addUpload('stuff', $fp, 'custom.name', 'application/octet-stream');
and i get the below responds form the api.
stdClass Object
(
[error] => stdClass Object
(
[code] => InvalidImageSize
[message] => Image size is too small or too big.
)
)
Am i missing some step before passing the binary data to the api?
The image size is just 956 KB and the dimensions is 2448 x 2448

The Face API does not support multipart MIME payloads. You should instead send the image directly in the body of the request.
$image = 'images/face-021.jpg';
$fp = fopen($image, 'rb');
$request->setBody($fp);
$request->setHeader('Content-Type', 'application/octet-stream');
$request->setMethod(HTTP_Request2::METHOD_POST);

function microimg() {
//$GLOBALS['telegram']->ssendmessage($GLOBALS['userid'], $urlImage);
$request = new Http_Request2('https://westus.api.cognitive.microsoft.com/face/v1.0/detect');
$url1 = $request->getUrl();
$headers = array(`enter code here`
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => 'xxxxxxxxxxxxxxxxxx'
);
$request->setHeader($headers);
$parameters = array(
// Request parameters
'returnFaceId' => 'true',
'returnFaceLandmarks' => 'false',
'returnFaceAttributes' => 'age',
);
$parameters = array();
$url1->setQueryVariables($parameters);
$request->setMethod(HTTP_Request2::METHOD_POST);
//$request->setBody('{"url": "http://miladddddddddddddd.ml/fillter_image/photos/file_93.jpg" }');
$request->setBody('{"url": "'.$GLOBALS['fileurl'].'" }');
$err = $request->setBody;
try {
$response = $request->send();
echo $response->getBody();
$ed = $response->getBody();
$GLOBALS['telegram']->ssendmessage($GLOBALS['userid'],$ed);
$GLOBALS['telegram']->ssendmessage($GLOBALS['userid'], $GLOBALS['fileurl']);
} catch (HttpException $ex) {
echo $ex;
}
}
microimg($urlimg);

Related

Streaming a response in CakePHP

I want CakePHP to stream a download to the browser. The content of the stream is served via an API.
So, CakePHP makes a request to that API, gets a response with a file and must stream this response to the browser.
This is what I got so far:
public function getDownload() {
// do other things
$http = new Client([
'headers' => [
'accept' =>'application/octet-stream'
]
]);
$response = $http->get($this->url,[]);
// first try
// $stream = new CallbackStream(function () use ($response) {
// return $response;
// });
// $response = $response->withBody($stream);
// second try
// $stream = new CallbackStream($http->get($this->url,[])->getData());
// $response = $response->withBody($stream);
return $response;
}
With this setup I can download small files. The reason I need a stream is, because the API could send files up to 10GB. My guess is, that with $http->get CakePHP stores the whole response in memory. Thats why I'm getting a memory exhausted error.
I know I'm lacking a bit of understanding here. Any help is appreciated :)
Finally I found a solution:
public function getDownload($url) {
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"accept: application/octet-stream\r\n"
)
);
$context = stream_context_create($opts);
$response = new Response();
$file = fopen($url, 'r',false, $context);
$stream = new CallbackStream(function () use ($file) {
rewind($file);
fpassthru($file);
fclose($file);
});
$response = $response->withBody($stream);
return $response;
}

Fetching data from external API RapidApi to Wordpress site

I am trying to fetch data from this API:
https://rapidapi.com/apilayernet/api/rest-countries-v1?
endpoint=53aa5a08e4b0a705fcc323a6
I managed to use wp_remote_get() to make the request but I keep getting no result showing up apart from an error:
The site is experiencing technical difficulties.
I just point out thatI have used Composer to set up the Composer.json file in my XAMPP proper folder in which I have included the request:
{
"require-dev": {
"mashape/unirest-php": "3.*"
}
}
In my code I am including the parameter for the API key as below but for some reason is not working:
$request = wp_remote_get( 'https://restcountries-v1.p.rapidapi.com/all',
array(
"X-RapidAPI-Host" => "restcountries-v1.p.rapidapi.com",
"X-RapidAPI-Key" => "7fc872eb0bmsh1baf0c288235a1ep114aecjsn18f888f020c0"
) );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
echo $data;
The wp_remote_get accepts an array of options as the second argument, but you passed the headers directly.
They should be inside a nested headers array inside the options.
Method Documentation: https://codex.wordpress.org/Function_Reference/wp_remote_get
$request = wp_remote_get('https://restcountries-v1.p.rapidapi.com/all', [
'headers' => [
'X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com',
'X-RapidAPI-Key' => '<apikey>',
],
]);
if (is_wp_error($request)) {
return false; // Bail early
}
$body = wp_remote_retrieve_body($request);
$data = json_decode($body);
echo $data;
This is the method I use on all of my gets from Wordpress
$url = 'https://restcountries-v1.p.rapidapi.com/all'; //define url
$response = wp_remote_get($url, array(
'headers'=> array('X-RapidAPI-Host' => 'restcountries-v1.p.rapidapi.com', //set header
'X-RapidAPI-Key' => '<apikey>'//set api key
),
'method' => 'GET',//set method
));
$decode = json_decode($response);// decode response
echo "<pre>"; print_r($decode); die('dead');// display response on page wiothout any other information.

How can I asynchronously download files with Guzzle 6?

I am trying to asynchronously download files with Guzzle 6, but the documentation seems vague and couldn't find any useful examples.
The thing I am not sure about is - how am I supposed to save the received data?
Currently I am doing it like this:
$successHandler = function (Response $response, $index) use ($files) {
$file = fopen($files[$index], 'a');
$handle = $response->getBody();
while (!$handle->eof()) {
fwrite($file, $handle->read(2048));
}
fclose($file);
};
Is this really asynchronous?
Since if we get into one callback and start looping, how can we get the data from the other ones at the same time?
Is there a more direct way to tell, when creating a Request, where should the response be stored? (or directly passing a stream for that).
The sink option should be your friend here:
$client->request('GET', '/stream/20', [
'sink' => '/path/to/file',
]);
For reference, see http://docs.guzzlephp.org/en/latest/request-options.html#sink.
use function GuzzleHttp\Psr7\stream_for;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Client;
$tmpFile = tempnam(sys_get_temp_dir(), uniqid(strftime('%G-%m-%d')));
$resource = fopen($tmpFile, 'w');
$stream = stream_for($resource);
$client = new Client();
$options = [
RequestOptions::SINK => $stream, // the body of a response
RequestOptions::CONNECT_TIMEOUT => 10.0, // request
RequestOptions::TIMEOUT => 60.0, // response
];
$response = $client->request('GET', 'https://github.com/robots.txt', $options);
$stream->close();
fclose($resource);
if ($response->getStatusCode() === 200) {
echo file_get_contents($tmpFile); // content
}

Google Services OAuth requests returns HTTP 400 Bad Request Error

I'm trying to build a basic app where I can modify my own google calendar using Google's RESTful api, but I'm having trouble getting the oAuth token. I've chosen to do it using the Services Application oAuth flow - I don't want to have to constantly re-agree to letting my own app use my calendar, but if there's a better way to do this please let me know.
Every time I make the http request I get a Bad Request error. Any ideas/help?
Here's the code:
<?php
$payload = array(
"iss"=>"services client email",
"scope"=>"https://www.googleapis.com/auth/calendar",
"aud"=>"https://accounts.google.com/o/oauth2/token",
"iat"=>date("U"),
"exp"=>date("U")+3600
);
$key = "Simple API key";
$jwt = encode_header($payload,$key);
print_r(request_g_token($jwt));
function request_g_token($jwt)
{
$data = array(
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion' => $jwt
);
$data = http_build_query($data);
$url = "https://accounts.google.com/o/oauth2/token";
//echo $data;
$opts = array('http' =>
array(
'protocol_version' => '1.1',
'method' => 'POST',
'header' => "Host: accounts.google.com\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n",
'content' => $data
)
);
$context = stream_context_create($opts);
return (file_get_contents($url, false, $context));
}
function urlsafeb64encode($input){
return str_replace('=','',strtr(base64_encode($input),'+/','-_'));
}
function encode_header($payload, $key, $algo = 'RS256'){
$header = array('typ' => 'JWT', 'alg' => $algo);
$segments = array();
$segments[] = urlsafeb64encode(json_encode($header));
$segments[] = urlsafeb64encode(json_encode($payload));
$signing_input = implode('.',$segments);
$sig = sign_encode($signing_input,$key);
$segments[]=urlsafeb64encode($sig);
return implode('.',$segments);
}
function sign_encode($msg, $key){
return hash_hmac('sha256', $msg, $key, true);
}
?>
Any help would be greatly appreciated
UPDATE
So I went through the service process again and realized I need to use a private key, which I'm now doing. My major question is whether or not to include the "private-key.p12" part of what I downloaded from google or not. I'm still receiving a Bad Request error unfortunately...
UPDATE 2
Realized I needed to pull the key from the pk12 file, and I did so with this code:
function getKey($file){
$p12cert = array();
$fd = fopen($file, 'r');
$p12buf = fread($fd,filesize($file));
fclose($fd);
if ( openssl_pkcs12_read($p12buf, $p12cert, 'notasecret') )
{
//worked
$temp = $p12cert['pkey'];
$temp = str_replace("-----BEGIN PRIVATE KEY-----","",$temp);
$temp = str_replace("-----END PRIVATE KEY-----","",$temp);
return $temp;
}
else
{
//failed
return "failed";
}
}
However, it's still giving me a bad request error and I think it's to do with the fact that the key comes back in multiple lines. Any ideas?
For anyone experiencing this issue, I've basically come to the conclusion that google hasn't interfaced calendar with their service accounts yet, and am using a refresh token to achieve similar results without having to log in all the time.

Implementing Sketchfab API

I am trying to implement sketchfab api in my website. I got the code and access token from their website , I implemented everything but when I execute the code, I get a blank screen. What is the problem?
The first problem was with curl, I enabled it by going to php.ini file but then this blank screen problem.
<?php
$url = "https://api.sketchfab.com/v1/models";
$path = "./";
$filename = "m.3DS";
$description = "Test of the api with a simple model";
$token_api = "THE ACCESS TOKEN";
$title = "Uber Glasses";
$tags = "test collada glasses";
$private = 1;
$password = "Tr0b4dor&3";
$data = array(
"title" => $title,
"description" => $description,
"fileModel" => "#".$path.$filename,
"filenameModel" => $filename,
"tags" => $tags,
"token" => $token_api,
"private" => $private,
"password" => $password
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
$response = curl_exec($ch);
curl_close($ch);
echo $response; // I am trying to echo the response here
?>
The call to the upload api will return a json that contains the id of the model. You can use this id to generate an url and make another call to the oEmbed api. pseudo code example:
// your curl setup
$response = curl_exec($ch);
// Response
{success: true, {result: {id: 'xxxxxx'} } when upload OK
{success: false, error: 'error message'} when upload error
$id = $response['result']['id'];
$call= "https://sketchfab.com/oembed?url=https://sketchfab.com/show/" . $id;
// do another curl call with $call content
// it will return a response like below but with your model information
// Response
{
provider_url: "http://sketchfab.com",
provider_name: "Sketchfab",
thumbnail_url: "https://sketchfab.com/urls/dGUrytaktlDeNudCEGKk31oTJY/thumbnail_448.png?v=24a1cb0590851ccfeeae01a2ca1eece1",
thumbnail_width: "448",
thumbnail_height: "280",
author_name: "Klaas Nienhuis",
author_url: "https://sketchfab.com/klaasnienhuis",
title: "Maison d'artiste",
html: "<iframe frameborder="0" width="640" height="320" webkitallowfullscreen="true" mozallowfullscreen="true" src="http://sketchfab.com/embed/dGUrytaktlDeNudCEGKk31oTJY?autostart=0&transparent=0&autospin=0&controls=1&watermark=0"></iframe>",
width: 640,
height: 320,
version: "1.0",
type: "rich"
}
If you have an issue with this try in the command line to print the result of call.

Categories