public void Validate()
 {
     foreach (var eachEntry in this.Bills)
     {
         if (eachEntry.ValidationErrors == null)
         {
             eachEntry.ValidationErrors = new List <string>();
         }
         try
         {
             if (System.IO.File.Exists(eachEntry.BillPath))
             {
                 //eachEntry.IsValid = ComputerVisionHelper.VerifyText(eachEntry.Amount, eachEntry.BillPath, ConfigurationManager.AppSettings["CognitiveServicesKey"], eachEntry.ValueBesideLabel).Result;
                 eachEntry.AmountMatchType = ComputerVisionHelper.VerifyText(eachEntry.Amount, eachEntry.BillPath, ConfigurationManager.AppSettings["CognitiveServicesKey"], eachEntry.ValueBesideLabel).Result;
             }
             else
             {
                 eachEntry.AmountMatchType = MatchType.NoMatch;
                 eachEntry.ValidationErrors.Add("File not found");
             }
         }
         catch (Exception ex)
         {
             eachEntry.AmountMatchType = MatchType.NoMatch;
             eachEntry.ValidationErrors.Add(string.Format("Exception Occured for Bill Id: {0}. Exception Message: {1}", eachEntry.ID, ex.Message));
         }
     }
 }
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequestMessage req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request for driving license data.");


            // Get request body

            Byte[] byteArray = await req.Content.ReadAsByteArrayAsync();

            if (byteArray == null || byteArray.Length == 0)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(@"Empty request body")
                });
            }

            var textResult = await ComputerVisionHelper.ExtractLocalTextAsync(byteArray, log);

            if (textResult == null || !textResult.Any())
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(@"No text found")
                });
            }
            var license = textResult.Select(tr => tr.Text).ToList().ExtractDrivingInfo();

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(license), Encoding.UTF8, "application/json")
            });
        }
        private async Task <string> GetFileText(IFormFile file)
        {
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                var fileBytes = ms.ToArray();
                var lines     = await ComputerVisionHelper.ExtractLocalTextAsync(fileBytes);

                return(string.Join(" - ", lines.Select(t => t.Text)));
            }
        }
        internal async Task ReadImageOcrTextAndTranslate(string toLanguage = "en-US")
        {
            string inputImageFilePath = Path.Combine(
                HelperFunctions.GetSampleDataFullPath(customSettings.SampleDataFolders.PhotosToAnalyzeFolder),
                customSettings.SampleIndividualFiles.PhotoFileToProcess
                );

            string fileNamePrefix  = Path.GetFileName(inputImageFilePath);
            string outFolder       = HelperFunctions.GetSampleDataFullPath(customSettings.SampleDataFolders.AnalyzedImagesFolder);
            string outBaseFilePath = Path.Combine(outFolder, fileNamePrefix);

            // ensure destination Path exists
            Directory.CreateDirectory(outFolder);



            // OCR - text extraction

            // Get vision client

            Console.WriteLine($"Extracting Text using Vision OCR from {inputImageFilePath}...");

            ComputerVisionClient visionClient = ComputerVision.Authenticate(
                customSettings.ComputerVisionSettings.Endpoint,
                customSettings.ComputerVisionSettings.Key);

            string ocrFilePath = outBaseFilePath + "-ReadOcrResults.txt";

            var ocrResult = await ComputerVision.RecognizeTextFromImageLocal(visionClient, inputImageFilePath, false);

            var ocrLineTexts = ComputerVisionHelper.GetOcrResultLineTexts(ocrResult);
            await File.WriteAllLinesAsync(ocrFilePath, ocrLineTexts);

            Console.WriteLine($"Generated OCR output file {ocrFilePath}.");
            Console.WriteLine();

            // Detect Languages using Text Analytics Api
            TextAnalyticsClient textClient = TextAnalytics.GetClient(
                customSettings.TextAnalyticsSettings.Key,
                customSettings.TextAnalyticsSettings.Endpoint
                );


            Console.WriteLine("Detect the language from generated OCR text using TextAnalytics...");
            IEnumerable <string> sourceLanguages = await TextAnalytics.DetectLanguageBatchAsync(textClient, ocrLineTexts);

            //Console.WriteLine($"Detected languages Count: {sourceLanguages.Count()}");
            //Console.WriteLine($"Detected Languages: {string.Join(", ", sourceLanguages)}");
            Console.WriteLine();


            // Now translate the extracted text (OCR) to output language (here default is English)
            Console.WriteLine($"Now translate the generated OCR file to English {toLanguage}...");

            string ocrText = await File.ReadAllTextAsync(ocrFilePath);

            string translatedText = await JournalHelper.Translator.Translate.TranslateTextRequestAsync(
                customSettings.TranslatorConfigSettings.Key,
                customSettings.TranslatorConfigSettings.Endpoint,
                toLanguage,
                ocrText
                );

            string outTranslatedFilePath = outBaseFilePath + "-translated-" + toLanguage + ".json";

            if (!translatedText.StartsWith("["))
            {
                Console.WriteLine($"Storing the generated translation output to file: {outTranslatedFilePath}... ");
                var json = JObject.Parse(translatedText);
                Helper.WriteToJsonFile <JObject>(outTranslatedFilePath, json);

                if (json.ContainsKey("error"))
                {
                    Console.WriteLine($"\t\t\tTRANSLATOR ERROR: {json["error"]["code"]}");
                    Console.WriteLine($"\t\t\tMESSAGE: {json["error"]["message"]}");
                    return;
                }
            }

            string txtFile = outTranslatedFilePath + ".txt";

            Console.WriteLine($"Generating txt file with translated texts - {txtFile}");

            IEnumerable <string> texts = JournalHelper.Translator.Translate.GetTranslatedTexts(translatedText);
            await File.WriteAllLinesAsync(txtFile, texts);

            Console.WriteLine();
        }