CloudSight Response Speed - php

I am experimenting with the Cloudsight API (Image recognition) and am seeing speed issues in response time. Their website advertises a 6-12 second response time, but I am routinely seeing responses taking up to and well over 20 seconds.
I would like to know if this is something on CloudSights end and that is just the response time, or if my code is causing these delays by being unoptimized or doing unnecessary work.
The following is my PHP code, it works fully, I can upload an image and read/display the response. My HTML code is a simple form that calls this PHP file.
<?php
$filename = $_FILES['fileToUpload']['name'];
$filedata = $_FILES['fileToUpload']['tmp_name'];
$filesize = $_FILES['fileToUpload']['size'];
$filetype = $_FILES['fileToUpload']['type'];
/*$tmpfile = $_FILES['fileToUpload']['tmp_name'];
$filename = basename($_FILES['fileToUpload']['name']);*/
$ch = curl_init("https://api.cloudsightapi.com/image_requests");
//$ch = curl_init("http://requestb.in/131zwlo1");
$postFields = [
"image_request[locale]" => "en-US",
"image_request[language]" => "en-US",
"image_request[image]" => "#$filedata".";filename=#$filename".";type=#$filetype"
];
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: CloudSight [key]", "Content-Type:multipart/form-data"));
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
$token = $result['token'];
$status = $result['status'];
sleep(3);
while($status == "not completed"){
sleep(1);
$cht = curl_init("http://api.cloudsightapi.com/image_responses/$token");
curl_setopt($cht, CURLOPT_RETURNTRANSFER, true);
curl_setopt($cht, CURLOPT_HTTPHEADER, array("Authorization: CloudSight 6-j8FTD-h1ZtnlYgacdSEQ"));
$result = curl_exec($cht);
curl_close($cht);
$result = json_decode($result, true);
$status = $result['status'];
};
$name = $result['name'];
$reason = $result['reason'];
if($name != ""){
echo "\nName: $name";
};
if($reason != ""){
echo "\nReason Skipped: $reason";
};
?>

Related

How to use AZURE face recognition Rest API?

I am using Face API with curl in PHP. But I am having issue when matching images.
I am able to generate faceId's but when matching I get different results than expected. I have two images belonges to same person but API indicates that these images are different. But when using Microsoft demo to compare images I get right result.
Here is microsoft demo link:
https://azure.microsoft.com/en-in/services/cognitive-services/face/#demo
Here are My images url
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
Here is my code
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$headers = ["Ocp-Apim-Subscription-Key: ********* ","Content-Type:application/json" ];
/* Getting faceId */
foreach($images as $data)
{
/* First step is to detect face */
$request_url='https://nexever.cognitiveservices.azure.com/face/v1.0/detect?detectionModel=detection_03&returnFaceId=true&returnFaceLandmarks=false';
/* Image to get faceid */
$detect = array('url' => $data);
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($detect)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl);
$curlErrno = curl_errno($curl);
if ($curlErrno) { $curlError = curl_error($curl);throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl);
$strResponse = json_decode($strResponse , true);
print_r($strResponse);
array_push($faceid , $strResponse[0]['faceId']);
}
// comparing by face ID
/* Match face url */
$request_url = 'https://nexever.cognitiveservices.azure.com/face/v1.0/verify';
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
$curl = curl_init(); curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, $request_url); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($match)); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($curl); $curlErrno = curl_errno($curl);
if ($curlErrno) {$curlError = curl_error($curl); throw new Exception($curlError); }
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return json_decode($strResponse, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
I have successfully got face id but unable to match. If I try some other images of same person it matches sometimes. The problem is result is not accurate.
but on microsoft demo it is working fine.
Pls try to use specify request param: recognitionModel=recognition_04 when you detect faces as official doc recommanded:
I modified your code as below, it works for me perfectly:
<?php
function compare($image1, $image2)
{
$faceid = array();
$images = array($image1 , $image2);
$faceAPIName = "nexever";
$apikey = "<your api key>";
$faceidAPIHost = "https://$faceAPIName.cognitiveservices.azure.com";
foreach($images as $data)
{
$detect = array('url' => $data);
$result = do_post("$faceidAPIHost/face/v1.0/detect?recognitionModel=recognition_04&detectionModel=detection_03",json_encode($detect),$apikey);
array_push($faceid , $result[0]['faceId']);
}
$request_url = "$faceidAPIHost/face/v1.0/verify";
/* Face ID to compare */
print_r($faceid);
$match = array("faceId1"=>$faceid[0], "faceId2"=>$faceid[1],"maxNumOfCandidatesReturned" =>10,"mode"=> "matchFace");
return do_post($request_url,json_encode($match),$apikey);
}
function do_post($url, $params,$key) {
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\nOcp-Apim-Subscription-Key: $key",
'method' => 'POST',
'content' => $params
)
);
$result = file_get_contents($url, false, stream_context_create($options));
return json_decode($result, true);
}
$img1 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/1645715403_1.jpg";
$img2 = "http://nexever.in/LibTravelSuperAdmin/images/temporary/3.png";
$ret = compare($img1, $img2);
//print_r($ret);
if(isset($ret['isIdentical']))
{
if($ret['isIdentical'] == 1)
{
echo "Same Person ";
}
else if($ret['isIdentical'] == 0)
{
echo "Different Person ";
}
}
?>
Result of your code:

How to get json for soundcloud without type

I get JSON from the Soundcloud API by using code in section【A】.
But I want to get it without using $type, like in code【B】.
In other words, I want to get that information by only giving $target.
What should I do?
$r = soundcloud_responce();
var_dump( $r );
function soundcloud_responce(){
$client_id = 'xxx';
$type = 'tracks';
$q = 'words';
// code【A】
// If I have $type, So this process ok.
$url = "https://api.soundcloud.com/";
$url .= $type;
$url .= "?client_id=$client_id";
$url .= "&q=$q";
// code【B】
// I want to do same process with $target but without $type
$target = "https://soundcloud.com/accountname/trackname";
$target = str_replace('https://soundcloud.com/', '', $target);
$url = "https://api.soundcloud.com/";
$url .= $target;
$url .= "?client_id=$client_id";
// curl
$ch = curl_init();
$headers = [
'Accept: application/json',
'Content-Type: application/json',
];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
$json = json_decode($res);
curl_close($ch);
return $json;
}
(Add 2020-02-21-09:38 #Tokyo)
I tried this code【C】but this also failed.
// code【C】
// I tried with oembed but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = 'http://soundcloud.com/oembed?format=json&url='.$target;
(Add 2020-02-21-10:12 #Tokyo)
I tried this code【D】but this also failed.
// code【D】
// I tried with resolve but this also failed.
$target = "https://soundcloud.com/accountname/trackname";
$url = "https://api.soundcloud.com/resolve?url=$target&client_id=$client_id";
I tried this code【E】this is successful!
Thank you for giving me good advice, #showdev.
// code【E】
// this is successful!
$target = "https://soundcloud.com/accountname/trackname";
$target = urlencode($target);
$url = "https://api.soundcloud.com/resolve.json?url=$target&client_id=$client_id";

PHP - Fortnite API show me "Invalid authentication credentials"?

I would like to make a small Fortnite API, but I always get an error in the JSON file.
{"message":"Invalid authentication credentials"}
My PHP Code:
$ch = curl_init();
//pc, xbl, psn
curl_setopt($ch, CURLOPT_URL, "https://api.fortnitetracker.com/v1/profile/pc/MyName");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'TRN-Api-Key: My-API-Code'
));
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);
$fp = fopen("myStats.json", "w");
fwrite($fp, $response);
fclose($fp);
$data = json_decode(file_get_contents("myStats.json"));
$solo = $data->stats->p2;//solos data
$duos = $data->stats->p10;//duos data
$squads = $data->stats->p9;//squads data
$matches = $data->recentMatches;//match data
$sesh1 = $matches[0]->id->valueInt;
$solo_wins = $solo->top1->valueInt;
$duos_wins = $duos->top1->valueInt;
$squads_wins = $squads->top1->valueInt;
$solo_matches = $solo->matches->valueInt;
$duos_matches = $duos->matches->valueInt;
$squads_matches = $squads->matches->valueInt;
$solo_kd = $solo->kd->valueDec;
$duos_kd = $duos->kd->valueDec;
$squads_kd = $squads->kd->valueDec;
$solo_games = $solo->matches->valueInt;
$duos_games = $duos->matches->valueInt;
$squads_games = $squads->matches->valueInt;
$solo_kills = $solo->kills->valueInt;
$duos_kills = $duos->kills->valueInt;
$squads_kills = $squads->kills->valueInt;
$total_matches = ($solo_matches+$duos_matches+$squads_matches);
$total_wins = ($solo_wins+$duos_wins+$squads_wins);
$total_kills = ($solo_kills+$duos_kills+$squads_kills);
$total_kd = (round($total_kills/($total_matches-$total_wins),2));
echo 'Total Matches: '.$total_matches.'<br>';
echo 'Total Wins: '.$total_wins.'<br>';
echo 'Total Kills: '.$total_kills.'<br>';
echo 'Total KD: '.$total_kd.'<br>';
echo $sesh1;
?>
I entered the correct API code. Why is this message written in a JSON file and not my wins? It's so crazy because it should work.
What returns on line 11? You are using var_dump($response);
Could you write die(); under that line and provide us the return that it gives?
There might be something wrong on how you handle the headers. I can't check for sure right now as I am not home. But I might be able to test this out later.

pushcrew - send notification with PHP curl

This is the code:
$title = 'Du hast neue Nachricht';
$message = 'Besuch meine Website';
$url = 'https://www.bla.com';
$subscriberId = 'xxx51a002dec08a1690fcbe6e';
$apiToken = 'xxxe0b282d9c886456de0e294ad';
$curlUrl = 'https://pushcrew.com/api/v1/send/individual/';
//set POST variables
$fields = array(
'title' => $title,
'message' => $message,
'url' => $url,
'subscriber_id' => $subscriberId
);
$httpHeadersArray = Array();
$httpHeadersArray[] = 'Authorization: key='.$apiToken;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
//execute post
$result = curl_exec($ch);
$resultArray = json_decode($result, true);
if($resultArray['status'] == 'success') {
echo $resultArray['request_id']; //ID of Notification Request
}
else if($resultArray['status'] == 'failure')
{
echo 'fail';
}
else
{
echo 'dono';
}
echo '<pre>';
var_dump($result);
echo '</pre>';
And I get:
dono
string(36) "{"message":"You are not authorized"}"
And nothing in the console and no other errors. The apitoken is 100% correct. What could be the trouble here? Do I have to wait till pushcrew decide to allow my website or something?
Ignore this: I must add some more text to ask this question..
There is typo here:
curl_setopt($ch, CURLOPT_HTTPSHEADER, $httpHeadersArray);
Correct is with
CURLOPT_HTTPHEADER
(without the S)

Json_decode throws "Trying to get property of non-object"

I'm trying to use the simple weather API, but somehow it doesn't recognize it as an object whatever I do. This is my code:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ".$city."will be: ". $jsonobj->forecast->max_c;
and this is the data I'm trying to reach with $jsonojb->forecast->max_c:
{
"error" : 0,
"error_message" : "-",
"forecast":[
{"date":"2016-12-02",
"avg_c":8,
"min_c":5,
"max_c":11,
"avg_f":46,
"min_f":41,
"max_f":52,
(...)
but it doesn't work. What am I doing wrong guys?
forecast is an array, so you have to use like this:
$forecast = $jsonobj->forecast;
$forecast[0]->max_c;
You can try out this code:
$url = "https://www.amdoren.com/api/weather.php?api_key=za8LEJ8F9mcHK8SvLxdM98rM9mNFjW&lat=40.7127837&lon=-74.0059413";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($curl);
$jsonobj = json_decode($curl_response);
$msg = "Temperature in ". $city . " will be: ". $jsonobj->forecast[0]->max_c;
echo $msg;
Hope it helps!
The "forecast" is an array, you have to add [0] to get the first one and then you will be able to get your "max_c".
Also, your API does not give you the city. You would have to use the Google Geocoding API to convert the lon,lat into a City Name.
$api_key = "za8LEJ8F9mcHK8SvLxdM98rM9mNFjW";
$lon = -74.0059413;
$lat = 40.7127837;
$url = "https://www.amdoren.com/api/weather.php?api_key=".$api_key."&lat=".$lat."&lon=".$lon."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
$max_c = $response['forecast'][0]['max_c'];
// Your API doesn't return the city name.
$city = "City Name";
$msg = "Temperature in ".$city."will be: ". $max_c;
echo $msg;
To get your City Name, here's the function you can use. You will need to replace the API KEY.
// Geocode
function geocode($lat,$lon){
$details_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=".$lat.",".$lon."&key=YOUR_API_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $details_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
// If Status Code is ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED or INVALID_REQUEST
if ($response['status'] != 'OK') {
return null;
}
$formatted_address = $response['results'][0]['formatted_address'];
$geometry = $response['results'][0]['geometry'];
$longitude = $geometry['location']['lat'];
$latitude = $geometry['location']['lng'];
$array = array(
'lat' => $geometry['location']['lng'],
'lon' => $geometry['location']['lat'],
'location_type' => $geometry['location_type'],
'formatted_address' => $formatted_address
);
return $array;
}

Categories