Exemplo n.º 1
0
        /// <summary>
        /// Vision - OCR - BatchRead from File Path -> Byte Array
        /// </summary>
        /// <param name="imageFilePath"></param>
        /// <param name="apiVersion"></param>
        /// <returns></returns>
        public static async Task <Tuple <string, OCRObjectResult> > VisionOCRResultBatchReadFromImageAsync(string imageFilePath, string apiVersion)
        {
            // Computer Vision URL
            var urlString = Config.COGNITIVE_SERVICES_REGION_URI + "/vision/" + apiVersion + "/read/core/asyncBatchAnalyze";
            // return variables
            var             responseContent = string.Empty;
            OCRObjectResult ocrObject       = null;
            string          ocrResultString = string.Empty;

            using (var httpClient = new HttpClient())
            {
                // Setup HttpClient
                httpClient.BaseAddress = new Uri(urlString);

                // Request headers
                httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", Config.COGNITIVE_SERVICES_KEY);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Reads the contents of the specified local image into a byte array.
                byte[] byteData = Util.GetImageAsByteArray(imageFilePath);

                // Adds the byte array as an octet stream to the request body.
                using (ByteArrayContent content = new ByteArrayContent(byteData))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                    // Make request with resiliency policy (can retry http requests)
                    var resilienyStrategy = CognitiveServicesRetryPolicy.DefineAndRetrieveResiliencyStrategy();
                    var response          = await resilienyStrategy.ExecuteAsync(() => httpClient.PostAsync(urlString, content));

                    // read response and write to view
                    // batch call, you need to wait for the "job" to finish
                    if (response.IsSuccessStatusCode)
                    {
                        var urlLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
                        var resilienyStrategyBatchJob = CognitiveServicesRetryPolicy.DefineAndRetrieveResiliencyStrategyForBatchJob();

                        var ocrResultResponse = await resilienyStrategyBatchJob.ExecuteAsync(() => httpClient.GetAsync(urlLocation));

                        if (ocrResultResponse.IsSuccessStatusCode)
                        {
                            ocrResultString = await ocrResultResponse.Content.ReadAsStringAsync();

                            if (string.IsNullOrEmpty(ocrResultString))
                            {
                                var test = ocrResultString;
                            }
                        }

                        ocrObject = JsonConvert.DeserializeObject <OCRObjectResult>(ocrResultString);
                    }
                    else
                    {
                        throw new Exception(response.StatusCode + " : " + response.ReasonPhrase);
                    }
                }
            }

            return(new Tuple <string, OCRObjectResult>(ocrResultString, ocrObject));
        }
        public static async Task <Tuple <string, CustomVisionObjectResult> > CustomVisionObjectResult(string uri)
        {
            // Two Computer Vision API versions for OCR. v1.0 and v2.0 (in preview)
            // v2.0 is based on newer AI technology

            // Computer Vision URL
            var urlString = "https://southcentralus.api.cognitive.microsoft.com/customvision/v2.0/Prediction/460af9b0-5e66-4e70-a84a-d402e413fe2d/url?iterationId=12848efa-e746-445d-8e45-8a5a58c33ba7";
            // return variables
            var responseContent = string.Empty;
            CustomVisionObjectResult customVisionObjectResult = null;

            using (var httpClient = new HttpClient())
            {
                // Setup HttpClient
                httpClient.BaseAddress = new Uri(urlString);

                // Request headers
                // TODO: Change later, not used for now
                httpClient.DefaultRequestHeaders.Add("Prediction-Key", string.Empty);
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // Request body
                var uriBody = "{\"url\":\"" + uri + "\"}";

                using (var content = new StringContent(uriBody))
                {
                    content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                    // Make request with resiliency policy (can retry http requests)
                    var resilienyStrategy = CognitiveServicesRetryPolicy.DefineAndRetrieveResiliencyStrategy();
                    var response          = await resilienyStrategy.ExecuteAsync(() => httpClient.PostAsync(urlString, content));

                    //read response and write to view
                    if (response.IsSuccessStatusCode)
                    {
                        responseContent = await response.Content.ReadAsStringAsync();
                    }
                    else
                    {
                        throw new Exception(response.StatusCode + " : " + response.ReasonPhrase);
                    }
                }

                customVisionObjectResult = JsonConvert.DeserializeObject <CustomVisionObjectResult>(responseContent);
            }

            return(new Tuple <string, CustomVisionObjectResult>(responseContent, customVisionObjectResult));
        }