コード例 #1
0
        static async Task GetTextFromImageAsync(ComputerVisionClient visionClient, string url)
        {
            BatchReadFileHeaders textHeaders = await visionClient.BatchReadFileAsync(url);

            string operationLocation     = textHeaders.OperationLocation;
            int    maxCharsInOperationId = 36;
            string operationId           = operationLocation.Substring(operationLocation.Length - maxCharsInOperationId);
            int    i                    = 0;
            int    maxRetries           = 10;
            ReadOperationResult results = null;

            do
            {
                results = await visionClient.GetReadOperationResultAsync(operationId);

                Console.WriteLine($"Статус сервера {results.Status}, выполняется {i} c");
                await Task.Delay(1000);

                if (i == 9)
                {
                    Console.WriteLine("Сервер вызвал таймаут");
                }
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);
            Console.WriteLine();
            var textRecognitionResults = results.RecognitionResults;

            foreach (TextRecognitionResult textRecognitionResult in results.RecognitionResults)
            {
                foreach (var line in textRecognitionResult.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
        }
コード例 #2
0
        /*
         * END - GENERATE THUMBNAIL
         */

        // <snippet_extract_call>

        /*
         * BATCH READ FILE - URL IMAGE
         * Recognizes handwritten text.
         * This API call offers an improvement of results over the Recognize Text calls.
         */
        public static async Task BatchReadFileUrl(ComputerVisionClient client, string urlImage)
        {
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine("BATCH READ FILE - URL IMAGE");
            Console.WriteLine();

            // Read text from URL
            BatchReadFileHeaders textHeaders = await client.BatchReadFileAsync(urlImage);

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;
            // </snippet_extract_call>

            // <snippet_extract_response>
            // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
            // We only need the ID and not the full URL
            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            Console.WriteLine($"Extracting text from URL image {Path.GetFileName(urlImage)}...");
            Console.WriteLine();
            do
            {
                results = await client.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);

                if (maxRetries == 9)
                {
                    Console.WriteLine("Server timed out.");
                }
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);
            // </snippet_extract_response>

            // <snippet_extract_display>
            // Display the found text.
            Console.WriteLine();
            var textRecognitionLocalFileResults = results.RecognitionResults;

            foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    Console.WriteLine(line.Text);
                }
            }
            Console.WriteLine();
        }
コード例 #3
0
        private static async Task <string> ExtractRemoteTextAsync(ComputerVisionClient computerVision, string imageUrl)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                throw new Exception($"Invalid remoteImageUrl: {imageUrl}");
            }

            var textHeaders = await computerVision.BatchReadFileAsync(imageUrl);

            return(await GetTextAsync(computerVision, textHeaders.OperationLocation));
        }
コード例 #4
0
        // Read text from a remote image
        private static async Task ExtractTextFromUrlAsync(ComputerVisionClient computerVision, string imageUrl, int numberOfCharsInOperationId, TextRecognitionMode textRecognitionMode)
        {
            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, textRecognitionMode);

            await GetTextAsync(computerVision, textHeaders.OperationLocation, numberOfCharsInOperationId);
        }
コード例 #5
0
        // public static ComputerVisionClient Authenticate(string endpoint, string key)
        // {
        //     ComputerVisionClient client =
        //       new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
        //       { Endpoint = endpoint };
        //     return client;
        // }

        public async Task <List <string> > BatchReadFileUrl(ComputerVisionClient client, string urlImage)
        {
            String fullTextResultList = "";

            // Read text from URL

            var textHeaders = await client.BatchReadFileAsync(urlImage);

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;

            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            do
            {
                results = await client.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);

                if (i == 9)
                {
                    Console.WriteLine("Server timed out.");
                }
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

            var textRecognitionLocalFileResults = results.RecognitionResults;

            foreach (TextRecognitionResult recResult in textRecognitionLocalFileResults)
            {
                foreach (Line line in recResult.Lines)
                {
                    fullTextResultList += line.Text + " ";
                }
            }
            var cleanResults = resultCleanUp(fullTextResultList);

            return(cleanResults);
        }
コード例 #6
0
        public static async Task <string> ExtractText(ComputerVisionClient client, string urlImage)
        {
            // Read text from URL
            BatchReadFileHeaders textHeaders = await client.BatchReadFileAsync(urlImage);

            // After the request, get the operation location (operation ID)
            string operationLocation = textHeaders.OperationLocation;

            // Retrieve the URI where the recognized text will be stored from the Operation-Location header.
            // We only need the ID and not the full URL
            const int numberOfCharsInOperationId = 36;
            string    operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);

            // Extract the text
            // Delay is between iterations and tries a maximum of 10 times.
            int i          = 0;
            int maxRetries = 10;
            ReadOperationResult results;

            Console.WriteLine($"Extracting text from URL image {System.IO.Path.GetFileName(urlImage)}...");
            Console.WriteLine();
            do
            {
                results = await client.GetReadOperationResultAsync(operationId);

                Console.WriteLine("Server status: {0}, waiting {1} seconds...", results.Status, i);
                await Task.Delay(1000);
            }while ((results.Status == TextOperationStatusCodes.Running ||
                     results.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries);

            // Display the found text.
            Console.WriteLine();
            var    recognitionResults = results.RecognitionResults;
            string content            = string.Empty;

            foreach (TextRecognitionResult result in recognitionResults)
            {
                foreach (Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models.Line line in result.Lines)
                {
                    Console.WriteLine(line.Text);
                    content += line.Text + Environment.NewLine;
                }
            }
            Console.WriteLine();
            return(content);
        }
コード例 #7
0
        // Read text from a remote image
        private static async Task ExtractRemoteTextAsync(
            ComputerVisionClient computerVision, string imageUrl)
        {
            if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute))
            {
                Console.WriteLine(
                    "\nInvalid remoteImageUrl:\n{0} \n", imageUrl);
                return;
            }

            // Start the async process to read the text
            BatchReadFileHeaders textHeaders =
                await computerVision.BatchReadFileAsync(
                    imageUrl);

            await GetTextAsync(computerVision, textHeaders.OperationLocation);
        }
コード例 #8
0
        public async Task <string> ScanDocumentAndGetResultsAsync(string documentUrl)
        {
            BatchReadFileHeaders batchReadFileHeaders = await _computerVisionClient.BatchReadFileAsync(documentUrl);

            string operationId         = GetScanOperationResultId(batchReadFileHeaders.OperationLocation);
            var    readOperationResult = await ReadDocumentScanResult(operationId);

            StringBuilder sb = new StringBuilder();

            foreach (var recognitionResult in readOperationResult.RecognitionResults)
            {
                foreach (var line in recognitionResult.Lines)
                {
                    sb.AppendLine(line.Text);
                }
            }

            return(sb.ToString());
        }
コード例 #9
0
                        public async Task ExtractText(string data, bool flag)
                        {
                            ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { });

                            //Endpoint
                            computerVision.Endpoint = Endpoint;

                            if (flag)
                            {
                                if (!Uri.IsWellFormedUriString(data, UriKind.Absolute))
                                {
                                    Error = "Invalid remoteImageUrl: " + data;
                                }

                                //Starting the async process to read the text
                                BatchReadFileHeaders textHeaders = await computerVision.BatchReadFileAsync(data, textRecognitionMode);

                                await GetTextAsync(computerVision, textHeaders.OperationLocation);
                            }
                            else
                            {
                                //Image data to Byte Array
                                byte[] imageBytes = Convert.FromBase64String(data);

                                //Byte Array To Stream
                                Stream stream = new MemoryStream(imageBytes);

                                try
                                {
                                    //Starting the async process to recognize the text
                                    BatchReadFileInStreamHeaders textHeaders = await computerVision.BatchReadFileInStreamAsync(stream, textRecognitionMode);

                                    await GetTextAsync(computerVision, textHeaders.OperationLocation);
                                }
                                catch (Exception e)
                                {
                                    Error = e.Message;
                                }
                            }
                        }
コード例 #10
0
        public async Task <string> GetTextFromImage(string imageUrl)
        {
            var textHeaders = await client.BatchReadFileAsync(imageUrl, TextRecognitionMode.Handwritten);

            return(await GetOcrResults(textHeaders.OperationLocation));
        }
コード例 #11
0
        public async Task <ConvertResponse> ExtractTextBatchRead(ConvertResponse response)
        {
            try
            {
                var key      = _config["computerVision:key"];
                var endpoint = _config["computerVision:endpoint"];
                ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(key))
                {
                    Endpoint = endpoint
                };

                var operationInfo = await computerVision.BatchReadFileAsync(response.Request.UploadBlobUrl + _config["storage:sas"]);

                var result      = new ReadOperationResult();
                var operationId = operationInfo.OperationLocation.Split('/').Last();

                while (result.Status != TextOperationStatusCodes.Failed && result.Status != TextOperationStatusCodes.Succeeded)
                {
                    await Task.Delay(500);

                    result = await computerVision.GetReadOperationResultAsync(operationId);
                }

                if (result.Status == TextOperationStatusCodes.Failed)
                {
                    response.ErrorMessage = $"Text translation failed.";
                    return(response);
                }

                var text = new StringBuilder();
                foreach (var page in result.RecognitionResults)
                {
                    Line lastLine = null;
                    foreach (var line in page.Lines)
                    {
                        // if (lastLine?.Words.Count >= 4)
                        // {
                        //  text.Append($" {line.Text}");
                        // }
                        // else
                        // {
                        text.Append(Environment.NewLine + line.Text);
                        // }

                        lastLine = line;
                    }
                }

                Console.WriteLine();
                Console.WriteLine(text.ToString());

                var transcriptBlobName = Path.GetFileNameWithoutExtension(response.Request.BlobName) + ".txt";

                var blobClient = new BlobStorageClient(_config);
                var textBlob   = blobClient.GetBlobBlock("transcripts", transcriptBlobName);

                response.TranscriptBlobUrl = textBlob.Uri.AbsoluteUri;
                response.Transcript        = text.ToString().Trim();

                await textBlob.UploadTextAsync(response.Transcript);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Console.WriteLine(ex.Message);
                response.ErrorMessage = ex.ToString();
            }

            return(response);
        }