// Recognize text from a remote image private async Task <TextOperationResult> ExtractRemoteTextAsync(ComputerVisionClient computerVision, string imageUrl) { if (!Uri.IsWellFormedUriString(imageUrl, UriKind.Absolute)) { Debug.WriteLine("\nInvalid remoteImageUrl:\n{0} \n", imageUrl); return(null); } // Start the async process to recognize the text RecognizeTextHeaders textHeaders = await computerVision.RecognizeTextAsync(imageUrl, textRecognitionMode); // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = textHeaders.OperationLocation.Substring(textHeaders.OperationLocation.Length - numberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { Debug.WriteLine("Server status: {0}, waiting {1} seconds...", result.Status, i); await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } // Return the results return(result); }
// Retrieve the recognized text private static async Task GetTextAsync( ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - Constants.NUMBER_OF_CHARS_IN_OPERATION_ID); Console.WriteLine("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(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.GetTextOperationResultAsync(operationId); } DisplayResults(result); }
private async Task <List <string> > GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { Debug.WriteLine("Server status: {0}, waiting {1} seconds...", result.Status, i); await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } List <string> resultlines = new List <string>(); IList <Line> lines = result.RecognitionResult?.Lines; foreach (Line line in lines) { resultlines.Add(line.Text.Trim().Replace(" ", "")); } return(resultlines); }
// Retrieve the recognized text private static async Task <IList <Line> > GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); Console.WriteLine("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(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(200); result = await computerVision.GetTextOperationResultAsync(operationId); } // Display the results var lines = result.RecognitionResult.Lines; return(lines); }
private async Task <TextOperationResult> GetTextAsync( ComputerVisionClient computerVision, string operationLocation, CancellationToken cancellationToken) { // Retrieve the URI where the recognized text will be stored from the Operation-Location header string operationId = operationLocation.Substring(operationLocation.Length - NumberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId, cancellationToken); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { System.Diagnostics.Debug.WriteLine( "Server status: {0}, waiting {1} seconds...", result.Status, i); await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId, cancellationToken); } return(result); }
private static async Task <string> GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header var operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId); var result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } // Return the results var lines = result.RecognitionResult.Lines; return(string.Join(Environment.NewLine, lines.Select(l => l.Text))); }
private async Task <TextOperationResult> GetTextOperationResult(ComputerVisionClient client, string operationId) { var result = default(TextOperationResult); for (int attempt = 1; attempt <= 3; attempt++) { try { result = await client.GetTextOperationResultAsync(operationId); if (result.Status == TextOperationStatusCodes.Failed || result.Status == TextOperationStatusCodes.Succeeded) { break; } await Task.Delay(3000); result = await client.GetTextOperationResultAsync(operationId); } catch (ComputerVisionErrorException ex) { await HandleComputerVisionErrorException(ex); } catch (Exception ex) { } } return(result); }
private static async Task <string> GetTextAsync(string operationLocation) { var operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); var result = await visionClient.GetTextOperationResultAsync(operationId); int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { await Task.Delay(1000); result = await visionClient.GetTextOperationResultAsync(operationId); } var sb = new StringBuilder(); foreach (var line in result.RecognitionResult.Lines) { foreach (var word in line.Words) { sb.Append(word.Text); sb.Append(" "); } sb.Append("\r\n"); } return(sb.ToString()); }
private async Task <TextOperationResult> RecognizeAsync <T>(Func <ComputerVisionClient, Task <T> > GetHeadersAsyncFunc, Func <T, string> GetOperationUrlFunc) where T : new() { // ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- var result = default(TextOperationResult); OutputWriterSB.AppendLine("Create result variable for storing result"); // // Create Cognitive Services Vision API Service client. // var Credentials = new ApiKeyServiceClientCredentials("d8358f4194c8447bbca7c9e1605f15b0"); var Endpoint = "https://sushmavisionapi.cognitiveservices.azure.com/"; using (var client = new ComputerVisionClient(Credentials) { Endpoint = Endpoint }) { Debug.WriteLine("ComputerVisionClient is created"); OutputWriterSB.AppendLine("ComputerVisionClient is created"); try { Debug.WriteLine("Calling ComputerVisionClient.RecognizeTextAsync()..."); OutputWriterSB.AppendLine("Calling ComputerVisionClient.RecognizeTextAsync()..."); T recognizeHeaders = await GetHeadersAsyncFunc(client); string operationUrl = GetOperationUrlFunc(recognizeHeaders); string operationId = operationUrl.Substring(operationUrl.LastIndexOf('/') + 1); Debug.WriteLine("Calling ComputerVisionClient.GetTextOperationResultAsync()..."); OutputWriterSB.AppendLine("Calling ComputerVisionClient.GetTextOperationResultAsync()..."); result = await client.GetTextOperationResultAsync(operationId); for (int attempt = 1; attempt <= 3; attempt++) { if (result.Status == TextOperationStatusCodes.Failed || result.Status == TextOperationStatusCodes.Succeeded) { break; } Debug.WriteLine(string.Format("Server status: {0}, wait {1} seconds...", result.Status, TimeSpan.FromSeconds(3))); await Task.Delay(TimeSpan.FromSeconds(3)); Debug.WriteLine("Calling ComputerVisionClient.GetTextOperationResultAsync()..."); result = await client.GetTextOperationResultAsync(operationId); } } catch (Exception ex) { result = new TextOperationResult() { Status = TextOperationStatusCodes.Failed }; Debug.WriteLine(ex.Message); } return(result); } }
private async Task <TextOperationResult> RecognizeAsync <T>(Func <ComputerVisionClient, Task <T> > GetHeadersAsyncFunc, Func <T, string> GetOperationUrlFunc) where T : new() { // ----------------------------------------------------------------------- // KEY SAMPLE CODE STARTS HERE // ----------------------------------------------------------------------- var result = default(TextOperationResult); // // Create Cognitive Services Vision API Service client. // using (var client = new ComputerVisionClient(Credentials) { Endpoint = Endpoint }) { Log("ComputerVisionClient is created"); try { Log("Calling ComputerVisionClient.RecognizeTextAsync()..."); T recognizeHeaders = await GetHeadersAsyncFunc(client); string operationUrl = GetOperationUrlFunc(recognizeHeaders); string operationId = operationUrl.Substring(operationUrl.LastIndexOf('/') + 1); Log("Calling ComputerVisionClient.GetTextOperationResultAsync()..."); result = await client.GetTextOperationResultAsync(operationId); for (int attempt = 1; attempt <= MaxRetryTimes; attempt++) { if (result.Status == TextOperationStatusCodes.Failed || result.Status == TextOperationStatusCodes.Succeeded) { break; } Log(string.Format("Server status: {0}, wait {1} seconds...", result.Status, QueryWaitTimeInSecond)); await Task.Delay(QueryWaitTimeInSecond); Log("Calling ComputerVisionClient.GetTextOperationResultAsync()..."); result = await client.GetTextOperationResultAsync(operationId); } } catch (ClientException ex) { result = new TextOperationResult() { Status = TextOperationStatusCodes.Failed }; Log(ex.Error.Message); } return(result); } // ----------------------------------------------------------------------- // KEY SAMPLE CODE ENDS HERE // ----------------------------------------------------------------------- }
// Retrieve the recognized text private static async Task GetTextAsync( ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); Console.WriteLine("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(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.GetTextOperationResultAsync(operationId); } // Write to text file instead of console // EXAMPLE==> string path = @"D:\ouput\outfile"+temp+".txt" string path = @"OUTPUT_PATH" + temp + ".txt"; temp = temp + 1; if (!File.Exists(path)) { File.Create(path).Dispose(); } if (File.Exists(path)) { foreach (Line line in result.RecognitionResult.Lines) { using (var tw = new StreamWriter(path, true)) { tw.WriteLine(line.Text); } } } Console.WriteLine("Successfully extracted"); await Task.Delay(1000); //Environment.Exit(0); }
/// <summary> /// Use the Azure Computer Vision API to perform OCR analysis of the specified BHL page image. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="GetHeadersAsyncFunc"></param> /// <param name="GetOperationUrlFunc"></param> /// <returns></returns> static private async Task <TextOperationResult> NewTextAsync <T>(Func <ComputerVisionClient, Task <T> > GetHeadersAsyncFunc, Func <T, string> GetOperationUrlFunc) where T : new() { var result = default(TextOperationResult); // Create Cognitive Services Computer Vision API Service client. ApiKeyServiceClientCredentials credentials = new ApiKeyServiceClientCredentials(Config.SubscriptionKey); using (var client = new ComputerVisionClient(credentials) { Endpoint = Config.Endpoint }) { try { T recognizeHeaders = await GetHeadersAsyncFunc(client); string operationUrl = GetOperationUrlFunc(recognizeHeaders); string operationId = operationUrl.Substring(operationUrl.LastIndexOf('/') + 1); result = await client.GetTextOperationResultAsync(operationId); // Retry a few times in the case of failure for (int attempt = 1; attempt <= Config.MaxRetryTimes; attempt++) { if (result.Status == TextOperationStatusCodes.Failed || result.Status == TextOperationStatusCodes.Succeeded) { break; } await Task.Delay(Config.QueryWaitTimeInSeconds); // Wait a bit before retrying result = await client.GetTextOperationResultAsync(operationId); } } catch (Exception ex) { result = new TextOperationResult() { Status = TextOperationStatusCodes.Failed }; } return(result); } }
private async Task <RecognitionResult> GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { var operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId); var result = await computerVision.GetTextOperationResultAsync(operationId); int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } return(result.RecognitionResult); }
// Retrieve the recognized text private static async Task <String> GetTextAsync( ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; String S1 = ""; try { if (result != null && result.Status != null) { while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { result = await computerVision.GetTextOperationResultAsync(operationId); } var lines = result.RecognitionResult.Lines; foreach (Line line in lines) { if (line.Text.Contains("+")) { line.Text = line.Text.Replace(" ", ""); } S1 = S1 + line.Text + "\n"; } } } catch (Exception e) { } return(S1); }
private static async Task GetTextAsync( ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); Console.WriteLine("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(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.GetTextOperationResultAsync(operationId); } StringBuilder text = new StringBuilder(); // Display the results Console.WriteLine(); var lines = result.RecognitionResult.Lines; foreach (Line line in lines) { text.AppendLine(line.Text); } Recipes recp = new Recipes(); recp.Title = Guid.NewGuid().ToString(); recp.Text = text.ToString(); DataRepository.Instance.Save <Recipes>(recp); }
private static async Task <TextOperationResult> GetTextRecognitionResultAsync(ComputerVisionClient computerVision, string operationLocation) { // Retrieve the URI where the recognized text will be stored from the Operation-Location header string operationId = operationLocation.Substring(operationLocation.Length - NumberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < MaxRetriesOnTextRecognition) { await Task.Delay(DelayOnTextRecognition); result = await computerVision.GetTextOperationResultAsync(operationId); } return(result); }
public async Task <IHttpActionResult> Post() { //HttpRequestMessage request = this.Request; ComputerVisionClient computerVision = new ComputerVisionClient( new ApiKeyServiceClientCredentials(subscriptionKey), new System.Net.Http.DelegatingHandler[] { }); // Specify the Azure region computerVision.Endpoint = "https://eastus2.api.cognitive.microsoft.com"; RecognizeTextHeaders analysis = null; //using (Stream imageStream = await request.Content.ReadAsStreamAsync()) //{ // analysis = await computerVision.RecognizeTextInStreamAsync(imageStream, TextRecognitionMode.Printed); //} analysis = await computerVision.RecognizeTextAsync("https://amazonasatual.com.br/wp-content/uploads/2018/08/CNH-falsa-Manaus.jpeg", TextRecognitionMode.Printed); string operation = analysis.OperationLocation.Split('/').GetValue(analysis.OperationLocation.Split('/').Length - 1).ToString(); Thread.Sleep(5000); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operation); Cadastro cadastro = new Cadastro(); cadastro.Nome = result.RecognitionResult.Lines[5].Text; cadastro.RG = result.RecognitionResult.Lines[7].Text; cadastro.CPF = result.RecognitionResult.Lines[11].Text; { DateTime resultado; if (DateTime.TryParse(result.RecognitionResult.Lines[12].Text, out resultado)) { cadastro.DtNascimento = resultado; } } cadastro.NomeMae = result.RecognitionResult.Lines[19].Text; { DateTime resultado; if (DateTime.TryParse(result.RecognitionResult.Lines[29].Text, out resultado)) { cadastro.Validade = resultado; } } return(Ok(cadastro)); }
private static async Task <string> GetTextAsync( ComputerVisionClient computerVision, string operationLocation, ILogger log) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); Console.WriteLine("\nCalling GetTextRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 60; 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.GetTextOperationResultAsync(operationId); }//TODO make the method of waiting less rubbish, maybe use durable function? if (result.RecognitionResult == null) { log.LogError("Failed to OCR text from image. Max try count exceeded."); return(null); } if (result.Status == TextOperationStatusCodes.Failed) { log.LogError("Failed to OCR text from image."); return(null); } return(string.Join(Environment.NewLine, result.RecognitionResult.Lines.Select(l => l.Text))); }
private static async Task GetTextAsync(ComputerVisionClient computerVision, string operationLocation, TraceWriter log, CognitiveImageTextAnalysis cognitiveImageTextAnalysis) { string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId); log.Info("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { log.Info("Server status: " + result.Status + ", waiting " + i + " seconds..."); await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } cognitiveImageTextAnalysis.textOperationResult = result; }
private async Task <IList <Line> > GetTextAsync(ComputerVisionClient client, string operationLocation) { _client = client; string operationId = operationLocation.Substring(operationLocation.Length - 36); TextOperationResult result = await _client.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 5; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { await Task.Delay(1000); result = await _client.GetTextOperationResultAsync(operationId); } var lines = result.RecognitionResult.Lines; return(lines); }
// Retrieve the recognized text private static async Task <IList <Line> > GetTextAsync(ComputerVisionClient computerVision, string operationLocation, ILogger logger) { // Retrieve the URI where the recognized text will be // stored from the Operation-Location header string operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); Console.WriteLine("\nCalling GetHandwritingRecognitionOperationResultAsync()"); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete int i = 0; int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { logger.LogInformation( $"Server status: {result.Status}, waiting {i * 1000} milliseconds..."); await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } // Display the results if (result.RecognitionResult != null && result.RecognitionResult.Lines != null) { var lines = result.RecognitionResult.Lines; return(lines); } else { logger.LogError($"Unable to get text operation result: {JsonConvert.SerializeObject(result)}"); return(null); } }
// 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); TextOperationResult result = await computerVision.GetTextOperationResultAsync(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.GetTextOperationResultAsync(operationId); } // Display the results Console.WriteLine(); var recResults = result.RecognitionResult; foreach (Line line in recResults.Lines) { foreach (Word word in line.Words) { Console.WriteLine("{0} at location {1}, {2}, {3}, {4}", word.Text, word.BoundingBox[0], word.BoundingBox[1], word.BoundingBox[2], word.BoundingBox[3]); } Console.WriteLine(); } Console.WriteLine(); }
private static async Task GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { string operationId = operationLocation.Substring(operationLocation.Length - 36); TextOperationResult result = await computerVision.GetTextOperationResultAsync(operationId); 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(i *1000); result = await computerVision.GetTextOperationResultAsync(operationId); } Console.WriteLine(); var lines = result.RecognitionResult.Lines; foreach (Line line in lines) { Console.WriteLine(line.Text); } Console.WriteLine(); }
// Retrieve the recognized text private static async Task <IEnumerable <Line> > GetTextAsync(ComputerVisionClient computerVision, string operationLocation, int count = 0) { if (computerVision == null) { throw new ArgumentNullException(nameof(computerVision)); } try { const int numberOfCharsInOperationId = 36; var operationId = operationLocation.Substring( operationLocation.Length - numberOfCharsInOperationId); var result = await computerVision.GetTextOperationResultAsync(operationId); // Wait for the operation to complete var i = 0; const int maxRetries = 10; while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && i++ < maxRetries) { result = await computerVision.GetTextOperationResultAsync(operationId); } return(result.RecognitionResult.Lines); } catch { Thread.Sleep(5000); return(count <= 25 ? await GetTextAsync(computerVision, operationLocation, ++count) : throw new InvalidOperationException()); } }
public async Task <string> TextFromImageAsync(byte[] data) { ComputerVisionClient computerVision = new ComputerVisionClient(new ApiKeyServiceClientCredentials("8715a698ede2411b8909589611ad3f6d"), new System.Net.Http.DelegatingHandler[] { }); computerVision.Endpoint = "https://westcentralus.api.cognitive.microsoft.com"; HttpOperationHeaderResponse <RecognizeTextInStreamHeaders> res = await computerVision.RecognizeTextInStreamWithHttpMessagesAsync(new MemoryStream(data), TextRecognitionMode.Printed); var str = await res.Response.Content.ReadAsStringAsync(); var id = res.Headers.OperationLocation; const int numberOfCharsInOperationId = 36; id = id.Substring(id.Length - numberOfCharsInOperationId); TextOperationResult result = await computerVision.GetTextOperationResultAsync(id); var r = res.Response.Content.ReadAsStringAsync(); return(r.ToString()); }
// Wait for the text recognition to complete private static async Task <TextOperationResult> GetTextOperationResultAsync(ComputerVisionClient computerVision, string operationId, TraceWriter log, string logHeader) { int attempt = 1; TextOperationResult result; do { log.Info($"{logHeader} Waiting {attempt} second(s)..."); await Task.Delay(attempt * 1000); result = await computerVision.GetTextOperationResultAsync(operationId); log.Info($"{logHeader} Text recognition server status: {result.Status}"); } while ( (result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && attempt++ < maxRetries); return(result); }
private static async Task GetTextAsync(ComputerVisionClient computerVision, string operationLocation) { var operationId = operationLocation.Substring(operationLocation.LastIndexOf('/') + 1); while (true) { var result = await computerVision.GetTextOperationResultAsync(operationId); Console.WriteLine("Polling for result..."); if (result.Status == TextOperationStatusCodes.Succeeded) { foreach (var line in result.RecognitionResult.Lines) { Console.WriteLine(line.Text); } break; } await Task.Delay(1000); } }
public static async Task <TextOperationResult> RecognizeText(string filename, string subscriptionKey, string serviceEndpoint) { ComputerVisionClient vision = new ComputerVisionClient(new ApiKeyServiceClientCredentials(subscriptionKey), new DelegatingHandler[] { }) { Endpoint = serviceEndpoint }; TextRecognitionMode mode = TextRecognitionMode.Printed; using (Stream stream = File.OpenRead(filename)) { try { RecognizeTextInStreamHeaders headers = await vision.RecognizeTextInStreamAsync(stream, mode); string id = headers.OperationLocation.Substring(headers.OperationLocation.LastIndexOf('/') + 1); int count = 0; TextOperationResult result; do { result = await vision.GetTextOperationResultAsync(id); if (result.Status == TextOperationStatusCodes.Succeeded || result.Status == TextOperationStatusCodes.Failed) { return(result); } await Task.Delay(DelayBetweenRetriesInMilliseconds); }while ((result.Status == TextOperationStatusCodes.Running || result.Status == TextOperationStatusCodes.NotStarted) && count++ < MaximumNumberOfRetries); } catch { // TODO: handle exception here } } return(null); }
public async Task <LabelImageAdded> ObterIngredientes(string pathFile) { _logs.AppendLine("Iniciando método de ObterIngredientes"); try { List <string> ingredientes = new List <string>(); StringBuilder concat = new StringBuilder(); bool entrar = false; _logs.AppendLine($"Lendo o arquivo: {pathFile} "); using (var imgStream = new FileStream(pathFile, FileMode.Open)) { RecognizeTextInStreamHeaders results = await _client.RecognizeTextInStreamAsync(imgStream, TextRecognitionMode.Printed); Thread.Sleep(2000); string idImagem = results.OperationLocation.Split('/').Last(); var resultText = await _client.GetTextOperationResultAsync(idImagem); var lines = resultText.RecognitionResult.Lines; _logs.AppendLine($"Número de linhas encontradas: {lines.Count} "); if (lines.Count > 0) { foreach (Line line in lines) { if (line.Text.IndexOf("INGREDIENTE") >= 0 || entrar) { entrar = true; concat.Append(line.Text); } } if (concat.ToString().Length > 0) { var resultado = Regex.Replace(concat.ToString(), "[^A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ, -]", ""); resultado = resultado.Replace("INGREDIENTES", ""); resultado = resultado.Replace("INGREDIENTE", ""); _logs.AppendLine($"Retorno dos ingredientes: {resultado}"); LabelImageAdded labelImageAdded = new LabelImageAdded(); labelImageAdded.ItemName = pathFile; labelImageAdded.Ingredients = resultado.Split(','); _logs.AppendLine($"LabelImageAdded serializado: {JsonConvert.SerializeObject(labelImageAdded)}"); _logger.LogInformation(_logs.ToString()); return(labelImageAdded); } else { _logs.AppendLine("Não foi encontrado ingredientes"); } } else { _logs.AppendLine("Não foi encontrado ingredientes"); } } } catch (Exception ex) { _logs.AppendLine($"Ocorreu um erro: {ex.Message}"); _logger.LogError(ex, _logs.ToString()); } finally { _logger.LogInformation(_logs.ToString()); Log _log = new Log(); _log.DataHora = DateTime.Now; _log.Mensagem = _logs.ToString(); LogService _logService = new LogService(); await _logService.MainAsync(_log); } return(null); }