0
votes

I have download this code from official microsoft cognitive github repository:

https://github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples/tree/master/samples/ComputerVision/OCR

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Microsoft.Azure.CognitiveServices.Samples.ComputerVision.BatchReadFile
{
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
    using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;

    class Program
    {
        static void Main(string[] args)
        {
            // Add your Computer Vision subscription key and endpoint to your environment variables
            string subscriptionKey = "my key0001"; // Environment.GetEnvironmentVariable("my key0001");
            string endpoint = "https://controllo.cognitiveservices.azure.com/"; // Environment.GetEnvironmentVariable("https://controllo.cognitiveservices.azure.com/");

            try
            {
                BatchReadFileSample.RunAsync(endpoint, subscriptionKey).Wait(5000);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("\nPress ENTER to exit.");
            Console.ReadLine();
        }
    }
    public class BatchReadFileSample
    {
        public static async Task RunAsync(string endpoint, string key)
        {
            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
            {
                Endpoint = endpoint
            };
            const int numberOfCharsInOperationId = 36;

            // string localImagePath = @"Images\handwritten_text.jpg";  // See this repo's readme.md for info on how to get these images. Alternatively, you can just set the path to any appropriate image on your machine.
            string localImagePath = @"C:\Users\marco.panza\OneDrive - Accenture\Desktop\Sorgenti\OCR C#\info.png";

           // string remoteImageUrl = "https://github.com/Azure-Samples/cognitive-services-sample-data-files/raw/master/ComputerVision/Images/printed_text.jpg";

            Console.WriteLine("Text being batch read ...");
             await BatchReadFileFromStreamAsync(computerVision, localImagePath, numberOfCharsInOperationId); 
           // await BatchReadFileFromUrlAsync(computerVision, remoteImageUrl, numberOfCharsInOperationId);
        }

        // Read text from a remote image
        private static async Task BatchReadFileFromUrlAsync(ComputerVisionClient computerVision, string imageUrl, int numberOfCharsInOperationId)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine("\nInvalid remote image url:\n{0} \n", imageUrl);
                return;
            }

            // Start the async process to read the text
            BatchReadFileHeaders textHeaders = await computerVision.BatchReadFileAsync(imageUrl);
            await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
        }

        // Recognize text from a local image
        private static async Task BatchReadFileFromStreamAsync(ComputerVisionClient computerVision, string imagePath, int numberOfCharsInOperationId)
        {
            if (!File.Exists(imagePath))
            {
                Console.WriteLine("\nUnable to open or read local image path:\n{0} \n", imagePath);
                return;
            }

            using (Stream imageStream = File.OpenRead(imagePath))
            {
                // Start the async process to recognize the text
                BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(imageStream);
                await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
            }
        }

        // Retrieve the recognized text
        private static async Task GetTextAsync(ComputerVisionClient computerVision, string operationLocation, int numberOfCharsInOperationId)
        {
            // Retrieve the URI where the recognized text will be
            // stored from the Operation-Location header
            string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            ReadOperationResult result = await computerVision.GetReadOperationResultAsync(operationId);

            // Wait for the operation to complete
            int i = 0;
            int maxRetries = 10;
            while ((result.Status == TextOperationStatusCodes.Running ||
                    result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries)
            {
                Console.WriteLine("Server status: {0}, waiting {1} seconds...", result.Status, i);
                await Task.Delay(1000);
                result = await computerVision.GetReadOperationResultAsync(operationId);
            }

            // Display the results
            Console.WriteLine();
            var recResults = result.RecognitionResults;
            foreach (TextRecognitionResult recResult in recResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();
        }
    }
}

but I get this error:

One or more errors occurred. (Operation returned an invalid status code 'Unauthorized')

the key and end point are correct (I have posted a pseudo key for security reasons).

The first time I have tried with this code:

string subscriptionKey = Environment.GetEnvironmentVariable("my key0001");
 string endpoint = Environment.GetEnvironmentVariable("https://controllo.cognitiveservices.azure.com/");

but these string return null and after I have tried to assigh directly the value:

string subscriptionKey = "my key0001");
 string endpoint = "https://controllo.cognitiveservices.azure.com/);

and I get this error:

"One or more errors occurred. (Operation returned an invalid status code 'Unauthorized')"

can someone help me please ?

1
Did you get a key from the microsoft website? The existing key may not be valid. How old is the code you downloaded? Is code using URL that is HTTP or HTTPS (secure)? Most servers are now using HTTPS and will fail if using HTTP.jdweng
I get the real key from microsoft website. and the source here github.com/Azure-Samples/cognitive-services-dotnet-sdk-samples/…user3449922
I need to do a OCR to PDF on local driveuser3449922
Looked at sample and code is using HTTPS and with Net 4.6.2. HTTPS uses TLS for authentication. Last June Microsoft did a security push which disabled TLS 1.0 and 1.1 on servers and now requires TLS 1.2 or 1.3. Also issues with older version of Net supporting all the encryption modes especially if TLS 1.3 is being used. Old version of Net may not support encryption mode. First I would make sure you using latest version of AZURE. Then it is best to use Net 4.7.2 or newer which give option of using Net for TLS or Windows Operating System for TLS and select in config file Operating system.jdweng
I have used vs2019 that automatically was updated "ComputerVision" to 5.0 that is the last update. Do you know if extst a better source code for "Microsoft.Azure.CognitiveServices.Vision.ComputerVision" api ?user3449922

1 Answers

1
votes

Pls make sure that you have created a current type of cognitive service, I recommend you to create All Cognitive Services just as below:

enter image description here

You can follow this doc to create it(Multi-service resource).

I did some test on my side by this service and everything works for me as expected :

My local test image:

enter image description here

Result:

enter image description here