Search code examples
node.jsazureocr

Computer vision Read api azure


I have tried Read api of azure for reading text from image/pdf (https://eastus.dev.cognitive.microsoft.com/docs/services/computer-vision-v3-2/operations/5d986960601faab4bf452005/console) and it works correctly then I tried using code

var request = require('request');
var options = {
  'method': 'POST',
  'url': 'https://eastus.api.cognitive.microsoft.com/vision/v3.2/read/analyze?language=en&readingOrder=basic&model-version=latest',
  'headers': {
    'Host': 'eastus.api.cognitive.microsoft.com',
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': 'key'
  },
  body: JSON.stringify({"url":"url"})

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log("response",response.body);
});

the response.body is not returning any value. Can someone help me what may be the issue?


Solution

  • It is by design as the doc indicated:

    When you call the Read operation, the call returns with a response header called 'Operation-Location'. The 'Operation-Location' header contains a URL with the Operation Id to be used in the second step. In the second step, you use the Get Read Result operation to fetch the detected text lines and words as part of the JSON response.

    The response body is empty, you can Operation-Location in the response header.

    Just try the code below to get the Operation-Location and final result:

    var request = require('request');
    
    var region = ''
    var key = ''
    var imageUrl = ""
    
    var options = {
      'method': 'POST',
      'url': `https://${region}.api.cognitive.microsoft.com/vision/v3.2/read/analyze?language=en&readingOrder=basic&model-version=latest`,
      'headers': {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': key
      },
      body: JSON.stringify({"url":imageUrl})
    
    };
    
    
    request(options, function (error, response) {
        if (error) throw new Error(error);
    
        resultURL = response.headers['operation-location'];
        //print result URL
        console.log(resultURL)
    
        options.url= resultURL
        options.method='GET'
    
        //wait 5s to allow Azure process the image
        wait(5000).then(function(){
                request.get(options,function(error, result){
                    console.log(result.body)
                });
            })
    });
    
    function wait(ms) {
        return new Promise(resolve => setTimeout(() => resolve(), ms));
    };
    

    Result:

    enter image description here