Beispiel #1
0
        // OCR Request by URL & Extract Key-Value Pairs
        public static async Task <List <string> > MakeOCRRequestByUrl(string imageUrl, string formType, ExecutionContext executionContext)
        {
            Console.Write("C# HTTP trigger function processed: MakeOCRRequestByUrl");

            string urlBase = Environment.GetEnvironmentVariable("CognitiveServicesUrlBase");
            string key     = Environment.GetEnvironmentVariable("CognitiveServicesKey");

            var client      = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);

            // Request parameters
            queryString["mode"] = "Printed";
            Uri uri = new Uri(urlBase + "recognizeText?" + queryString);

            HttpResponseMessage response;

            var requstbody = "{\"url\":\"" + $"{imageUrl}" + "\"}";

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes(requstbody);

            using (var content = new ByteArrayContent(byteData))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                response = await client.PostAsync(uri, content);
            }

            string operationLocation = null;

            // The response contains the URI to retrieve the result of the process.
            if (response.IsSuccessStatusCode)
            {
                operationLocation = response.Headers.GetValues("Operation-Location").FirstOrDefault();
            }

            string contentString;
            int    i = 0;

            do
            {
                System.Threading.Thread.Sleep(1000);
                response = await client.GetAsync(operationLocation);

                contentString = await response.Content.ReadAsStringAsync();

                ++i;
            }while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);


            string json = response.Content.ReadAsStringAsync().Result;

            json = json.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });
            RecognizeText ocrOutput = JsonConvert.DeserializeObject <RecognizeText>(json);

            if (ocrOutput != null && ocrOutput.RecognitionResult != null && ocrOutput.RecognitionResult.Lines != null)
            {
                List <string> resultText = new List <string>();

                resultText = (from Line sline in ocrOutput.RecognitionResult.Lines
                              select(string) sline.Text).ToList <string>();

                // Extract Key-Value Pairs
                resultText = OCRHelper.ExtractKeyValuePairs(ocrOutput.RecognitionResult.Lines, formType, executionContext);

                return(resultText);
            }
            else
            {
                return(null);
            }
        }