// 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); }
public static async Task <RecognitionResult> MakeTextRequest(MediaFile file) { using (var stream = file.GetStream()) { var client = CreateClient(); RecognizeTextInStreamHeaders headers = await client.RecognizeTextInStreamAsync(stream, TextRecognitionMode.Handwritten); if (headers?.OperationLocation == null) { return(null); } // Extract the operation id from the url string operationId = headers.OperationLocation.Substring(headers.OperationLocation.Length - 36); TextOperationResult result = await client.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 client.GetTextOperationResultAsync(operationId); } return(result.RecognitionResult); } }
/// <summary> /// Perform OCR analysis of the specified BHL page. /// </summary> /// <remarks>It is assumed that the page being analyzed is handwritten.</remarks> /// <param name="pageID">BHL identifier for the page</param> /// <returns>Text of the page</returns> static public async Task GetNewText(int pageID) { // Invoke the Azure Computer Vision service to extract the text of the page. // Assume this is a handwritten page. string imageUrl = string.Format(Config.BhlPageImageUrl, pageID.ToString()); TextOperationResult result = await NewTextAsync( async (ComputerVisionClient client) => await client.RecognizeTextAsync(imageUrl, TextRecognitionMode.Handwritten), headers => headers.OperationLocation); // Write the new text to a file if (result.Status == TextOperationStatusCodes.Succeeded) { StringBuilder sb = new StringBuilder(); if (result.RecognitionResult.Lines != null) { foreach (var line in result.RecognitionResult.Lines) { sb.AppendLine(line.Text); } } File.WriteAllText( string.Format("{0}\\{1}.txt", Config.NewFolder, pageID.ToString()), sb.ToString()); } }
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 static List <AzureResource> ConvertTextResultToAzureResources(TextOperationResult predictionResult) { var types = new List <AzureResourceType>(); foreach (var line in predictionResult.RecognitionResult.Lines) { var wordsList = line.Words.Select(word => word.Text).ToList(); // Case insensitive wordsList = wordsList.ConvertAll(w => w.ToLower()); // Remove punctiation marks wordsList = wordsList.ConvertAll(w => w.Replace("[.,]+", string.Empty)); foreach (var pattern in RecognizedTextToAzureTag.Keys) { // Check that contains all words in pattern if (pattern.Intersect(wordsList).Count() == pattern.Count()) { types.Add(RecognizedTextToAzureTag[pattern]); } } } List <AzureResource> allResources = AzureResourceManager.Instance.AvailableResources; return(allResources.Where(r => types.Contains(r.Type)).ToList()); }
private async Task <string[]> GetTextAsync( ComputerVisionClient computerVision, string operationLocation) { string[] results; // 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) { await Task.Delay(1000); result = await computerVision.GetTextOperationResultAsync(operationId); } var lines = result.RecognitionResult.Lines; return(lines.Select(l => l.Text).ToArray()); }
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); }
/// <summary> /// Log text from the given TextOperationResult object. /// </summary> /// <param name="results">The TextOperationResult.</param> protected void LogTextRecognitionResult(TextOperationResult results) { StringBuilder stringBuilder = new StringBuilder(); if (results != null && results.RecognitionResult != null && results.RecognitionResult.Lines != null && results.RecognitionResult.Lines.Count > 0) { stringBuilder.Append("Text: "); stringBuilder.AppendLine(); foreach (var line in results.RecognitionResult.Lines) { foreach (var word in line.Words) { stringBuilder.Append(word.Text); stringBuilder.Append(" "); } stringBuilder.AppendLine(); stringBuilder.AppendLine(); } } if (string.IsNullOrWhiteSpace(stringBuilder.ToString())) { Log("No text is recognized."); } else { Log(stringBuilder.ToString()); } if (results.Status == TextOperationStatusCodes.Running || results.Status == TextOperationStatusCodes.NotStarted) { Log(Invariant($"Status is {results.Status} after trying {MaxRetryTimes} times")); } }
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 // ----------------------------------------------------------------------- }
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 async Task <RecognitionResult> RecognizeTextAndAdd(ImageFile imageFile, TextRecognitionMode textRecognitionMode) { RecognitionResult recognitionResult = null; TextOperationResult textOperationResult = await UploadAndRecognizeImageAsync(imageFile.Path, textRecognitionMode); if (textOperationResult.Status == TextOperationStatusCodes.Succeeded) { recognitionResult = textOperationResult.RecognitionResult; _computerVisionRepository.AddRecognitionResult(imageFile, recognitionResult, textRecognitionMode); } return(recognitionResult); }
private static void DisplayResults(TextOperationResult result) { // Display the results 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 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); }
private void ShowExtractedText(TextOperationResult result) { if (result == null || result.Status != TextOperationStatusCodes.Succeeded) { ImageDescription = "Error occurred."; return; } foreach (var line in result.RecognitionResult.Lines) { ImageDescription += line.Text + "<br>"; } }
protected internal override IOperationResult ReadResponse(IPooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); var result = new TextOperationResult(); //maybe we should throw an exception when the item is not found? if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0) return result.Fail("Failed to read response. Item not found"); result.Success = UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); return result; }
protected internal override IOperationResult ReadResponse(PooledSocket socket) { GetResponse r = GetHelper.ReadItem(socket); var result = new TextOperationResult(); if (r == null) return result.Fail("Failed to read response"); this.result = r.Item; this.Cas = r.CasValue; GetHelper.FinishCurrent(socket); return result.Pass(); }
protected internal override IOperationResult ReadResponse(PooledSocket socket) { string response = TextSocketHelper.ReadResponse(socket); var result = new TextOperationResult(); //maybe we should throw an exception when the item is not found? if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0) { return(result.Fail("Failed to read response. Item not found")); } result.Success = UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); return(result); }
// Fail if we didn't get a valid result from the recognition service private static void ValidateTextOperationResult(this TextOperationResult result, string name) { switch (result.Status) { case TextOperationStatusCodes.Failed: throw new FunctionInvocationException($"Text recognition server wasn't able to recognize text in '{name}'"); case TextOperationStatusCodes.NotStarted: throw new FunctionInvocationException($"Text recognition server wasn't able to start recognizing text in '{name}'"); case TextOperationStatusCodes.Running: throw new FunctionTimeoutException($"Text recognition server didn't respond on a reasonable time frame when recognizing text in '{name}'"); } }
protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken)) { string response = await TextSocketHelper.ReadResponseAsync(socket, cancellationToken).ConfigureAwait(false); var result = new TextOperationResult(); //maybe we should throw an exception when the item is not found? if (String.Compare(response, "NOT_FOUND", StringComparison.Ordinal) == 0) { return(result.Fail("Failed to read response. Item not found")); } result.Success = UInt64.TryParse(response, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out this.result); return(result); }
protected override Enyim.Caching.Memcached.Results.IOperationResult ReadResponse(PooledSocket socket) { string description = TextSocketHelper.ReadResponse(socket); if (String.Compare(description, "END", StringComparison.Ordinal) == 0) { return(null); } if (description.Length < 7 || String.Compare(description, 0, "CONFIG ", 0, 7, StringComparison.Ordinal) != 0) { throw new MemcachedClientException("No CONFIG response received.\r\n" + description); } string[] parts = description.Split(' '); /****** Format ******** * * CONFIG <key> <flags> <bytes> * 0 1 2 3 * */ ushort flags = UInt16.Parse(parts[2], CultureInfo.InvariantCulture); int length = Int32.Parse(parts[3], CultureInfo.InvariantCulture); byte[] allNodes = new byte[length]; byte[] eod = new byte[2]; socket.Read(allNodes, 0, length); socket.Read(eod, 0, 2); // data is terminated by \r\n this.result = new CacheItem(flags, new ArraySegment <byte>(allNodes, 0, length)); this.ConfigResult = this.result; string response = TextSocketHelper.ReadResponse(socket); if (String.Compare(response, "END", StringComparison.Ordinal) != 0) { throw new MemcachedClientException("No END was received."); } var result = new TextOperationResult(); return(result.Pass()); }
protected internal override IOperationResult ReadResponse(PooledSocket socket) { GetResponse r = GetHelper.ReadItem(socket); var result = new TextOperationResult(); if (r == null) { return(result.Fail("Failed to read response")); } this.result = r.Item; this.Cas = r.CasValue; GetHelper.FinishCurrent(socket); return(result.Pass()); }
/// <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); } }
protected internal override async Task <IOperationResult> ReadResponseAsync(PooledSocket socket, CancellationToken cancellationToken = default(CancellationToken)) { var response = await GetHelper.ReadItemAsync(socket, cancellationToken).ConfigureAwait(false); var result = new TextOperationResult(); if (response == null) { return(result.Fail("Failed to read response")); } this.result = response.Item; this.Cas = response.CasValue; await GetHelper.FinishCurrentAsync(socket, cancellationToken).ConfigureAwait(false); return(result.Pass()); }
// 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); }
protected internal override IOperationResult ReadResponse(PooledSocket socket) { this.result = new Dictionary <string, CacheItem>(); this.Cas = new Dictionary <string, ulong>(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { this.StatusCode = response.StatusCode; // found the noop, quit if (response.CorrelationId == this.noopId) { return(result.Pass()); } string key; // find the key to the response if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } if (log.IsDebugEnabled) { log.DebugFormat("Reading item {0}", key); } // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); this.result[key] = new CacheItem((ushort)flags, response.Data); this.Cas[key] = response.CAS; } // finished reading but we did not find the NOOP return(result.Fail("Found response with CorrelationId {0}, but no key is matching it.")); }
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()); }
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 TextRecognitionResult GetTextRecognitionResult(TextOperationResult result) { var lines = result.RecognitionResult.Lines .Select(x => new Dtos.Line() { BoundingBox = BoundingBox.Create(x.BoundingBox.ToList()), Text = x.Text, Words = x.Words.Select(y => new Dtos.Word() { BoundingBox = BoundingBox.Create(x.BoundingBox.ToList()), Text = y.Text }).ToList() }).ToList(); return(new TextRecognitionResult() { Lines = lines }); }
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); }
protected internal override IOperationResult ReadResponse(PooledSocket socket) { this.result = new Dictionary<string, CacheItem>(); this.Cas = new Dictionary<string, ulong>(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { this.StatusCode = response.StatusCode; // found the noop, quit if (response.CorrelationId == this.noopId) return result.Pass(); string key; // find the key to the response if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); this.result[key] = new CacheItem((ushort)flags, response.Data); this.Cas[key] = response.CAS; } // finished reading but we did not find the NOOP return result.Fail("Found response with CorrelationId {0}, but no key is matching it."); }