private string AnalyzePdfForm(IFormRecognizerClient formClient, Guid formRecognizerModelId, string filePath)
        {
            //TODO: As this is part of .NET Library, writing to console does not makes sense
            // Write to an Exceptions section either in jsonResult or another output and send it to caller
            if (string.IsNullOrEmpty(filePath))
            {
                Console.WriteLine("\nInvalid file path.");
                return(null);
            }

            string jsonResult = "";

            try
            {
                using (FileStream stream = new FileStream(filePath, FileMode.Open))
                {
                    //Get the result from an asynchronous call but as a synchnous way by using .Result
                    AnalyzeResult result = formClient.AnalyzeWithCustomModelAsync(formRecognizerModelId, stream, contentType: "application/pdf").Result;
                    jsonResult = TransformAnalyzeResult(result);
                }
            }
            catch (ErrorResponseException e)
            {
                Console.WriteLine("Analyze PDF form : " + e.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Analyze PDF form : " + ex.Message);
            }

            return(jsonResult);
        }
Exemplo n.º 2
0
        // Analyze PNG form data
        private static async Task AnalyzePngForm(
            IFormRecognizerClient formClient, Guid modelId, string pngFormFile)
        {
            if (string.IsNullOrEmpty(pngFormFile))
            {
                Console.WriteLine("\nInvalid pngFormFile.");
                return;
            }

            try
            {
                using (FileStream stream = new FileStream(pngFormFile, FileMode.Open))
                {
                    AnalyzeResult result = await formClient.AnalyzeWithCustomModelAsync(modelId, stream, contentType : "image/png");

                    Console.WriteLine("\nExtracted data from:" + pngFormFile);
                    DisplayAnalyzeResult(result);
                }
            }
            catch (ErrorResponseException e)
            {
                Console.WriteLine("Analyze PNG form  " + e.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Analyze PNG  form  : " + ex.Message);
            }
        }
Exemplo n.º 3
0
 private async Task <AnalyzeResult> AnalyzePdfForm(IFormRecognizerClient formClient, Guid modelId, Stream pdfFormFile)
 {
     try
     {
         return(await formClient.AnalyzeWithCustomModelAsync(modelId, pdfFormFile, contentType : "application/pdf"));
     }
     catch (ErrorResponseException e)
     {
         return(null);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
        private async Task <AnalyzerResponse> AnalyzePdfForm(Guid modelId, IFormFile file)
        {
            if (file.Length <= 0)
            {
                throw new InvalidDataException("Invalid formFile");
            }

            try
            {
                var fileName = string.Format(TempFileName, Path.GetExtension(file.FileName));

                using var iFormFileStream = file.OpenReadStream();
                using var stream          = File.Create(fileName);
                iFormFileStream.Seek(0, SeekOrigin.Begin);
                iFormFileStream.CopyTo(stream);
                stream.Close();

                using var fileStream = new FileStream(fileName, FileMode.Open);
                var result = await _formRecognizerClient.AnalyzeWithCustomModelAsync(modelId, fileStream, file.ContentType);

                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }

                _logger.Information($"Analyzed file {file.FileName}:");

                var analyzerResponse = GetAllAmountsAndValues(result);
                var analzyerResultBuildFileStream = _fileBuilder.BuildFileFromAnalyzeResult(result);
                analyzerResponse.AnalzyerResultBuildFileId = await _s3FileService.UploadFileAsync(analzyerResultBuildFileStream);

                return(analyzerResponse);
            }
            catch (ErrorResponseException responseEx)
            {
                _logger.Error(responseEx, "Error while analyzing file");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Error while analyzing file");
            }

            return(new AnalyzerResponse());
        }
        public async Task <AnalyzeResult> AnalyzeForm(IFormRecognizerClient client, Guid modelId, string filePath)
        {
            AnalyzeResult result = null;
            //Default to PDF
            string contentType = "application/pdf";

            switch (Path.GetExtension(filePath).ToLower().Replace(".", ""))
            {
            case "pdf":
                contentType = "application/pdf";
                break;

            case "jpg":
                contentType = "image/jpeg";
                break;

            case "png":
                contentType = "image/png";
                break;

            default:
                break;
            }

            try
            {
                using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    result = await client.AnalyzeWithCustomModelAsync(modelId, stream, contentType : contentType);
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }

            //used the following to serialize the result object and use for testing
            //var jsonVersion = Newtonsoft.Json.JsonConvert.SerializeObject(result);
            //System.IO.File.WriteAllText(Shared.FormRecognitionService.PATH_TO_PROJECT_ROOT + @"\Code\SampleData\SerializedObjects\AnalyzedResult.json", jsonVersion);

            return(result);
        }
Exemplo n.º 6
0
        public async Task <IEnumerable <FormPredictionResult> > ProcessForms([FromForm] ProcessFormsRequest request)
        {
            var results = new List <FormPredictionResult>();

            var stagedFiles = await SaveFilesToStagingDirectory(request.RunId, request.Files);

            var runFileNames = stagedFiles.ToList();

            if (runFileNames.ToList().Count > 0)
            {
                foreach (var filePath in runFileNames)
                {
                    // Open saved file and send to form recognition API. For some reason, this doesn't work without doing the save first.
                    using (var fileStream = new FileStream(filePath, FileMode.Open))
                    {
                        AnalyzeResult result = await _formClient.AnalyzeWithCustomModelAsync(
                            FormRecogniserSettings.TaxCodeFormModelId, fileStream, contentType : "application/pdf");

                        if (result.Errors.Count == 0 && result.Pages.Count > 0)
                        {
                            var extractedPage = result.Pages[0];

                            var predictions = new List <KeyValuePair <string, string> >();
                            foreach (var predictionResult in extractedPage.KeyValuePairs)
                            {
                                if (predictionResult.Key.Count > 0 && predictionResult.Value.Count > 0)
                                {
                                    predictions.Add(new KeyValuePair <string, string>(predictionResult.Key[0].Text, predictionResult.Value[0].Text));
                                }
                            }

                            results.Add(new FormPredictionResult {
                                Id = Guid.NewGuid(), Predictions = predictions
                            });
                        }
                    }
                }
            }

            return(results);
        }
        public async Task <AnalyzeResult> AnalyzeAsync(string fileMimeType, Stream fileStream)
        {
            if (fileStream == null || fileStream.Length == 0)
            {
                throw new ArgumentException("Request can´t no be null.");
            }

            try
            {
                Guid modelId = await GetLastModelIDAsync();

                return((modelId != Guid.Empty) ? await _formClient.AnalyzeWithCustomModelAsync(modelId, fileStream, fileMimeType) : null);
            }
            catch (ErrorResponseException exr)
            {
                throw exr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }