Computer Vision API - v1.0 Recognize Handwritten Text returns empty response - microsoft-cognitive

I am trying to start using the computer vision API but I keep getting an empty response. My request in php (as exported by Postman) looks like this:
<?php
$request = new HttpRequest();
$request->setUrl('https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/recognizeText');
$request->setMethod(HTTP_METH_POST);
$request->setQueryData(array(
'language' => 'en',
'handwriting' => 'true'
));
$request->setHeaders(array(
'Postman-Token' => '442d04f7-49a0-4262-9d0f-666fe5240cc7',
'Cache-Control' => 'no-cache',
'Content-Type' => 'application/octet-stream',
'Ocp-Apim-Subscription-Key' => 'KEY'
));
try {
$response = $request->send();
echo $response->getBody();
} catch (HttpException $ex) {
echo $ex;
}
The above code works fine with the ocr endpoint!
The file is passed as binary using Postman.
Edit: I also tried to copy/paste the code from here: https://learn.microsoft.com/en-gb/azure/cognitive-services/computer-vision/quickstarts/php#ocr-php-example-request and if I change the ocr endpoint to recognizeText I get an empty response as well!

Unlike the other Computer Vision endpoints, RecognizeText is an asynchronous operation. Barring some issue with the image, you will get a 202 response instead of the usual 200 response. 202 responses customarily contain an empty response body. In this particular case you can find the URL where you can query for completion of the task. The documentation is here. The header you're looking for is Operation-Location.

Related

Downloading remote file using WordPress forbidden

I am trying to use WordPress' media_sideload_image with a remotely hosted image in S3 in order to save it into WordPress' media gallery.
But for whatever reason, I always get a forbidden response no matter what I try and do regarding request options for the WordPress request. Visiting the URL directly in the browser works, wget works, postman works.
Does anyone have any ideas on how to make WordPress be able to successfully download this file?
Here's the code I'm using:
$attachment_ID = media_sideload_image('https://s3.amazonaws.com/mlsgrid/images/0788b2c2-d865-496b-bad3-69ebe9c1db79.png');
And here's the WordPres error response I get:
object(WP_Error)[2090]
public 'errors' =>
array (size=1)
'http_404' =>
array (size=1)
0 => string 'Forbidden' (length=9)
public 'error_data' =>
array (size=1)
'http_404' =>
array (size=2)
'code' => int 403
'body' => string '<?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>39B59073BBC1205F</RequestId><HostId>6TwMl4cMbLXzr7jbx6ykQKaQuk0Rn5Oyc2Q3+02zmgtNoDqUvcg8VY32qGuS1ZMzgpZuLAefK3g=</HostId></Error>' (length=243)
protected 'additional_data' =>
array (size=0)
empty
Thanks!
After digging around WordPress' request functionality, it looks like it is setting a referer header on each request to be the same as the URL being fetched and I guess Amazon S3 rejects requests with a referer header set? (not sure if that is specific to the bucket I'm fetching images from or true across every single bucket).
Here's how I got it working by removing the referer header from the request, basically just filter for all S3 URLs and remove the referer request header.
// Remove referer from request headers if the URL is an S3 bucket.
add_action( 'http_api_curl', function ($ch, $parsed_args, $url) {
$s3_url = 'https://s3.amazonaws.com';
if (substr($url, 0, strlen($s3_url)) === $s3_url) {
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Referer:']);
}
}, 10, 3);

Cypress: How to access the body of a POST-request?

Is there a way in Cypress to check the body of a POST-request?
E.g.: I have entered some data in a form, then pressed "Submit".
The form-data is send via POST-request, separated by a blank line from the header-data.
I would like to check the form-data. If all data, which I have entered, are included and if they are correct.
Is that possible with Cypress?
cy.get('#login').then(function (xhr) {
const body = xhr.requestBody;
console.log(xhr);
expect(xhr.method).to.eq('POST');
});
The xhr-object doesn't have the transferred data included.
It should be possible.
describe('Capturing data sent by the form via POST method', () => {
before(() => {
Cypress.config('baseUrl', 'https://www.reddit.com');
cy.server();
cy.route({
method: 'POST',
url: '/login'
}).as('redditLogin');
});
it('should capture the login and password', () => {
cy.visit('/login');
cy.get('#loginUsername').type('username');
cy.get('#loginPassword').type('password');
cy.get('button[type="submit"]').click();
cy.wait('#redditLogin').then(xhr => {
cy.log(xhr.responseBody);
cy.log(xhr.requestBody);
expect(xhr.method).to.eq('POST');
})
});
});
This is how you can inspect your data in Chrome Developer Tool.
You should see the same thing you've seen from Chrome Developer Tool when you run your test in Cypress.
I was Googling the same problem and somehow landed here before reaching the documentation.
Anyway, have you tried something like:
cy.wait('#login').should((xhr) => {
const body = xhr.request.body
expect(body).to.match(/email/)
})
I haven't tested it out with a multipart/form-data encoded request, but I suspect that you'll also find the request body that way.
Good luck!
It's better to use cy.intercept() in order to spy, stub and assert network requests and responses.
// assert that a request to this route
// was made with a body that included 'user'
cy.wait('#someRoute').its('request.body').should('include', 'user')
// assert that a request to this route
// received a response with HTTP status 500
cy.wait('#someRoute').its('response.statusCode').should('eq', 500)
// assert that a request to this route
// received a response body that includes 'id'
cy.wait('#someRoute').its('response.body').should('include', 'id')
Link to the docs

What is the correct format and sequence to acquire the correct token for LinkedIn API V2?

Our LinkedIn APP no longer works with the evolution of V2. I have tried a couple of times and failed to create the correct token. I am seeking help to create the correct authorization link to get the token. Error from the App is currently "Empty oauth2 access token"
I created a new LinkedIn app to replace our old one. I have tried to follow the instructions from LinkedIn and Microsoft but my efforts have produced the following error
My most recent attempt was:
https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=78xaqf0ereiisy&redirect_uri=https://www.gachina.com&state=gachina&scope=r_emailaddress r_liteprofile w_member_social
I received: https://www.gachina.com/?code=AQS65Njp1F9-L-mKSrAJKZeQ-ij2OX7wboTc30-hrfQIwwJ0yfWd4FBqxLl-ZXHmL5HurKud4t9WcGeHB62EfPNcy3ddoqT1LztUHhR59iL-Q8f9WLrX03d9e3OCTmY-3vR8a_4ENeIN0GFpeLy7DKRDmuUNcQ82UwScqhApdtwzEBw-_Y0duYG87Lc1KQ&state=gachina
then I used the format shown here:
https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow
https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={authorization_code_from_step2_response}&redirect_uri=hhttps%3A%2F%2Fdev.example.com%2Fauth%2Flinkedin%2Fcallback&client_id={your_client_id}&client_secret={your_client_secret}
with
https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code=AQS65Njp1F9-L-mKSrAJKZeQ-ij2OX7wboTc30-hrfQIwwJ0yfWd4FBqxLl-ZXHmL5HurKud4t9WcGeHB62EfPNcy3ddoqT1LztUHhR59iL-Q8f9WLrX03d9e3OCTmY-3vR8a_4ENeIN0GFpeLy7DKRDmuUNcQ82UwScqhApdtwzEBw-_Y0duYG87Lc1KQ&redirect_uri=https://www.gachina.com/auth/Linkedin/callback&client_id=78xaqf0ereiisy&client_secret={client_secret}
but I receive the following upon submitting the above link with our {client secret} in place
{"error":"invalid_redirect_uri","error_description":"Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists"}
I am doing all of this within minutes. So, I do not believe there is an expiration of code.
Can you help identify the error of steps or code to receive a Token?
This will return the access token
$params = array('grant_type' => 'authorization_code',
'client_id' => $this->api_key,
'client_secret' => $this->api_secret,
'code' => $_GET['code'],
'redirect_uri' => base_url().$this->redirect,
);
// Access Token request
$url = 'https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params);
$data_len = strlen(http_build_query($params));
// Tell streams to make a POST request
$context = stream_context_create(
array('http' =>
array('method' => 'POST','header'=> 'Content-Length: 0'
)
)
);
// Retrieve access token information
$response = file_get_contents($url, false, $context);
$token = json_decode($response);
return $token->access_token;

Logstash and Flowdock integration

I'm trying to send a subset of messages to Flowdock as output from Logstash. Unfortunately, due to this issue I get essentially nothing back about why my messages aren't making it. Stripping down to a basic example, I see the problem even if I change my output config to the following:
output {
http {
http_method => "post"
url => "https://api.flowdock.com/v1/messages/team_inbox/API_TOKEN"
format => "message"
content_type => "application/json"
message => "{\"source\":\"logstash\",\"from_address\":\"me#example.com\", \"subject\":\"Log Message\", \"content\":\"test\"}"
}
}
I know, though, that output is generally working because if I add the following to output I see log messages written to the file:
file {
path => "/mnt/test.log"
}
I also know that the http message I'm sending to Flowdock should work since
curl -X POST https://api.flowdock.com/v1/messages/team_inbox/API_TOKEN -d "{\"source\":\"logstash\",\"from_address\":\"me#example.com\",\"subject\":\"Log Message\",\"content\":\"test\"}" -H "Content-Type: application/json"
results in a message being posted to the team inbox.
Are there any ways to work around this issue to determine why my output from logstash is failing?
I would start debugging the issue by first sending the requests from Logstash to a service that just outputs the received request, for example RequestBin.
Something like:
output {
http {
http_method => "post"
url => "http://requestb.in/<created_id>"
format => "message"
content_type => "application/json"
message => "{\"source\":\"logstash\",\"from_address\":\"me#example.com\",\"subject\":\"Log Message\", \"content\":\"test\"}"
}
}
After you've made sure that the request Logstash is making is correct, take that request (preferably the exact data) and try to send it to Flowdock using curl or some other means.
At this point you should be able to tell why the request fails in either end and notify the party accordingly (i.e. open a ticket to https://logstash.jira.com/secure/Dashboard.jspa or send an email to support#flowdock.com).

Any way to to use PHPUnit for testing API requests and responses using just PHP?

The responses are in JSON and I am using a custom-built MVC framework which I'm not sure how the request and response process is produced. Service methods are created using the following syntax.
public function getSessionsMethod()
{
// data auto encoded as JSON
return array('hello', 'world');
}
A request from JavaScript would look like this /svc/api/getSessions.
My initial thought was to simply use a streams approach are there best practices for this form of testing?
public function testCanGetSessionsForAGivenId()
{
$params = http_build_query(
array(
'id' => 3,
)
);
$options = array(
'http' => array(
'method' => 'GET',
'content' => $params,
)
);
$context = stream_context_create($options);
$response = file_get_contents(
'http://vbates/svc/api/getSessions', false, $context
);
$json = json_decode($response);
$this->assertEquals(3, $json->response);
}
This doesn't look like unit testing to me but rather integration testing. You can use PHPUnit to do it, but you should understand the difference first.
There are many components involved in getting the response for a given service method:
The dispatcher: Extracts the parameters from the URL and dispatches to the appropriate service method.
The service method: Does the real work to be tested here.
The JSON encoder: Turns the service method's return value into a JSON response.
You should first test these individually in isolation. Once you've verified that the dispatcher and encoder work for general URLs and return values, there's no point in wasting cycles testing that they work with every service method.
Instead, focus your effort on testing each service method without involving these other components. Your test case should instantiate and call the service methods directly with various inputs and make assertions on their return values. Not only will this require less effort on your part, it will make tracking down problems easier because each failure will be limited to a single component.

Resources