Инициировать уведомление после завершения извлечения с помощью Computer Vision OCR

Я изучаю API чтения Microsoft Computer Vision (asyncBatchAnalyze) для извлечения текста из изображений. Я нашел пример кода на сайте Microsoft для асинхронного извлечения текста из изображений. Он работает следующим образом:

1) Отправьте изображение в asyncBatchAnalyze API. 2) Этот API принимает запрос и возвращает URI. 3) Нам нужно опросить этот URI, чтобы получить извлеченные данные.

Есть ли способ, которым мы можем инициировать какое-либо уведомление (например, публикацию уведомления в AWS SQS или аналогичном сервисе), когда asyncBatchAnalyze выполняется с анализом изображения?


public class MicrosoftOCRAsyncReadText {

    private static final String SUBSCRIPTION_KEY = “key”;
    private static final String ENDPOINT = "https://computervision.cognitiveservices.azure.com";
    private static final String URI_BASE = ENDPOINT + "/vision/v2.1/read/core/asyncBatchAnalyze";


    public static void main(String[] args) {

    CloseableHttpClient httpTextClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpResultClient = HttpClientBuilder.create().build();;

        try {
            URIBuilder builder = new URIBuilder(URI_BASE);

            URI uri = builder.build();
            HttpPost request = new HttpPost(uri);

            request.setHeader("Content-Type", "application/octet-stream");
            request.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);


            String image = "/Users/xxxxx/Documents/img1.jpg";
            File file = new File(image);       
            FileEntity reqEntity = new FileEntity(file);
            request.setEntity(reqEntity);

            HttpResponse response = httpTextClient.execute(request);

            if (response.getStatusLine().getStatusCode() != 202) {
                HttpEntity entity = response.getEntity();
                String jsonString = EntityUtils.toString(entity);
                JSONObject json = new JSONObject(jsonString);
                System.out.println("Error:\n");
                System.out.println(json.toString(2));
                return;
            }

            String operationLocation = null;

            Header[] responseHeaders = response.getAllHeaders();
            for (Header header : responseHeaders) {
                if (header.getName().equals("Operation-Location")) {
                    operationLocation = header.getValue();
                    break;
                }
            }

            if (operationLocation == null) {
                System.out.println("\nError retrieving Operation-Location.\nExiting.");
                System.exit(1);
            }

            /* Wait for asyncBatchAnalyze to complete. In place of this wait, can we trigger any notification from Computer Vision when the extract text operation is complete?
*/
            Thread.sleep(5000);

            // Call the second REST API method and get the response.
            HttpGet resultRequest = new HttpGet(operationLocation);
            resultRequest.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);

            HttpResponse resultResponse = httpResultClient.execute(resultRequest);
            HttpEntity responseEntity = resultResponse.getEntity();

            if (responseEntity != null) {
                String jsonString = EntityUtils.toString(responseEntity);
                JSONObject json = new JSONObject(jsonString);
                System.out.println(json.toString(2));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}


person Ankit Mahajan    schedule 12.05.2020    source источник


Ответы (1)


В этих асинхронных операциях нет механизма уведомлений/веб-перехватчиков.

Единственное, что я вижу правильно, это изменить реализацию, о которой вы упомянули, используя условие while, которое регулярно проверяет, есть ли результат или нет (и механизм отмены ожидания - на основе максимального времени ожидания или количества повторных попыток) .

См. пример в документах Microsoft здесь, особенно эта часть:

// If the first REST API method completes successfully, the second 
// REST API method retrieves the text written in the image.
//
// Note: The response may not be immediately available. Text
// recognition is an asynchronous operation that can take a variable
// amount of time depending on the length of the text.
// You may need to wait or retry this operation.
//
// This example checks once per second for ten seconds.
string contentString;
int i = 0;
do
{
    System.Threading.Thread.Sleep(1000);
    response = await client.GetAsync(operationLocation);
    contentString = await response.Content.ReadAsStringAsync();
    ++i;
}
while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);

if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
{
    Console.WriteLine("\nTimeout error.\n");
    return;
}

// Display the JSON response.
Console.WriteLine("\nResponse:\n\n{0}\n",
    JToken.Parse(contentString).ToString());
person Nicolas R    schedule 13.05.2020