コード例 #1
0
        public async Task StartRecognizeInvoicesWithSupportedLocale()
        {
            var client  = CreateFormRecognizerClient();
            var options = new RecognizeInvoicesOptions()
            {
                IncludeFieldElements = true,
                Locale = FormRecognizerLocale.EnUS
            };
            RecognizeInvoicesOperation operation;

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceJpg);
            using (Recording.DisableRequestBodyRecording())
            {
                operation = await client.StartRecognizeInvoicesAsync(stream, options);
            }

            RecognizedFormCollection recognizedForms = await operation.WaitForCompletionAsync();

            var invoice = recognizedForms.Single();

            ValidatePrebuiltForm(
                invoice,
                includeFieldElements: true,
                expectedFirstPageNumber: 1,
                expectedLastPageNumber: 1);

            Assert.Greater(invoice.Fields.Count, 0);

            var receiptPage = invoice.Pages.Single();

            Assert.Greater(receiptPage.Lines.Count, 0);
            Assert.AreEqual(0, receiptPage.SelectionMarks.Count);
            Assert.AreEqual(2, receiptPage.Tables.Count);
        }
コード例 #2
0
        public async Task StartRecognizeInvoicesSendsUserSpecifiedLocale(string locale)
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/prebuilt/invoice/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceJpg);
            var recognizeOptions = new RecognizeInvoicesOptions {
                Locale = locale
            };
            await client.StartRecognizeInvoicesAsync(stream, recognizeOptions);

            var requestUriQuery = mockTransport.Requests.Single().Uri.Query;

            var localeQuery = "locale=";
            var index       = requestUriQuery.IndexOf(localeQuery);
            var length      = requestUriQuery.Length - (index + localeQuery.Length);

            Assert.AreEqual(locale, requestUriQuery.Substring(index + localeQuery.Length, length));
        }
コード例 #3
0
        public async Task StartRecognizeInvoicesIncludeFieldElements()
        {
            var client  = CreateFormRecognizerClient();
            var options = new RecognizeInvoicesOptions()
            {
                IncludeFieldElements = true
            };
            RecognizeInvoicesOperation operation;

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceJpg);
            using (Recording.DisableRequestBodyRecording())
            {
                operation = await client.StartRecognizeInvoicesAsync(stream, options);
            }

            RecognizedFormCollection recognizedForms = await operation.WaitForCompletionAsync();

            var invoicesform = recognizedForms.Single();

            ValidatePrebuiltForm(
                invoicesform,
                includeFieldElements: true,
                expectedFirstPageNumber: 1,
                expectedLastPageNumber: 1);
        }
コード例 #4
0
        public async Task RecognizeInvoicesFromFile()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            string invoicePath = FormRecognizerTestEnvironment.CreatePath("Invoice_1.pdf");

            #region Snippet:FormRecognizerSampleRecognizeInvoicesFileStream
            //@@ string invoicePath = "<invoicePath>";

            using var stream = new FileStream(invoicePath, FileMode.Open);
            var options = new RecognizeInvoicesOptions()
            {
                Locale = "en-US"
            };

            RecognizeInvoicesOperation operation = await client.StartRecognizeInvoicesAsync(stream, options);

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection invoices = operationResponse.Value;

            // To see the list of the supported fields returned by service and its corresponding types, consult:
            // https://aka.ms/formrecognizer/invoicefields

            RecognizedForm invoice = invoices.Single();

            if (invoice.Fields.TryGetValue("VendorName", out FormField vendorNameField))
            {
                if (vendorNameField.Value.ValueType == FieldValueType.String)
                {
                    string vendorName = vendorNameField.Value.AsString();
                    Console.WriteLine($"Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("CustomerName", out FormField customerNameField))
            {
                if (customerNameField.Value.ValueType == FieldValueType.String)
                {
                    string customerName = customerNameField.Value.AsString();
                    Console.WriteLine($"Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("InvoiceTotal", out FormField invoiceTotalField))
            {
                if (invoiceTotalField.Value.ValueType == FieldValueType.Float)
                {
                    float invoiceTotal = invoiceTotalField.Value.AsFloat();
                    Console.WriteLine($"Invoice Total: '{invoiceTotal}', with confidence {invoiceTotalField.Confidence}");
                }
            }

            #endregion
        }
コード例 #5
0
        public void StartRecognizeInvoicesRespectsTheCancellationToken()
        {
            var client  = CreateInstrumentedClient();
            var options = new RecognizeInvoicesOptions {
                ContentType = FormContentType.Pdf
            };

            using var stream             = new MemoryStream(Array.Empty <byte>());
            using var cancellationSource = new CancellationTokenSource();
            cancellationSource.Cancel();

            Assert.ThrowsAsync(Is.InstanceOf <OperationCanceledException>(), async() => await client.StartRecognizeInvoicesAsync(stream, recognizeInvoicesOptions: options, cancellationToken: cancellationSource.Token));
        }
コード例 #6
0
        public async Task <RecognizedForm> Analyze(Stream fileStream)
        {
            var options = new RecognizeInvoicesOptions()
            {
                Locale = "en-US"
            };

            RecognizeInvoicesOperation operation = await GetClient().StartRecognizeInvoicesAsync(fileStream, options);

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection invoices = operationResponse.Value;

            return(ProcessResults(invoices));
        }
        public async Task StartRecognizesInvoicesSendsUserSpecifiedContentType()
        {
            var mockResponse = new MockResponse(202);
            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/prebuilt/invoice/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options = new FormRecognizerClientOptions() { Transport = mockTransport };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceLeTiff);
            var recognizeOptions = new RecognizeInvoicesOptions { ContentType = FormContentType.Jpeg };
            await client.StartRecognizeInvoicesAsync(stream, recognizeOptions);

            var request = mockTransport.Requests.Single();

            Assert.True(request.Headers.TryGetValue("Content-Type", out var contentType));
            Assert.AreEqual("image/jpeg", contentType);
        }
コード例 #8
0
        public async Task RecognizeInvoicesFromUri()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            Uri invoiceUri = FormRecognizerTestEnvironment.CreateUri("Invoice_1.pdf");

            #region Snippet:FormRecognizerSampleRecognizeInvoicesUri
            var options = new RecognizeInvoicesOptions()
            {
                Locale = "en-US"
            };
            RecognizedFormCollection invoices = await client.StartRecognizeInvoicesFromUriAsync(invoiceUri, options).WaitForCompletionAsync();

            // To see the list of the supported fields returned by service and its corresponding types, consult:
            // https://aka.ms/formrecognizer/invoicefields

            RecognizedForm invoice = invoices.Single();

            FormField invoiceIdField;
            if (invoice.Fields.TryGetValue("InvoiceId", out invoiceIdField))
            {
                if (invoiceIdField.Value.ValueType == FieldValueType.String)
                {
                    string invoiceId = invoiceIdField.Value.AsString();
                    Console.WriteLine($"    Invoice Id: '{invoiceId}', with confidence {invoiceIdField.Confidence}");
                }
            }

            FormField invoiceDateField;
            if (invoice.Fields.TryGetValue("InvoiceDate", out invoiceDateField))
            {
                if (invoiceDateField.Value.ValueType == FieldValueType.Date)
                {
                    DateTime invoiceDate = invoiceDateField.Value.AsDate();
                    Console.WriteLine($"    Invoice Date: '{invoiceDate}', with confidence {invoiceDateField.Confidence}");
                }
            }

            FormField dueDateField;
            if (invoice.Fields.TryGetValue("DueDate", out dueDateField))
            {
                if (dueDateField.Value.ValueType == FieldValueType.Date)
                {
                    DateTime dueDate = dueDateField.Value.AsDate();
                    Console.WriteLine($"    Due Date: '{dueDate}', with confidence {dueDateField.Confidence}");
                }
            }

            FormField vendorNameField;
            if (invoice.Fields.TryGetValue("VendorName", out vendorNameField))
            {
                if (vendorNameField.Value.ValueType == FieldValueType.String)
                {
                    string vendorName = vendorNameField.Value.AsString();
                    Console.WriteLine($"    Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
                }
            }

            FormField vendorAddressField;
            if (invoice.Fields.TryGetValue("VendorAddress", out vendorAddressField))
            {
                if (vendorAddressField.Value.ValueType == FieldValueType.String)
                {
                    string vendorAddress = vendorAddressField.Value.AsString();
                    Console.WriteLine($"    Vendor Address: '{vendorAddress}', with confidence {vendorAddressField.Confidence}");
                }
            }

            FormField customerNameField;
            if (invoice.Fields.TryGetValue("CustomerName", out customerNameField))
            {
                if (customerNameField.Value.ValueType == FieldValueType.String)
                {
                    string customerName = customerNameField.Value.AsString();
                    Console.WriteLine($"    Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
                }
            }

            FormField customerAddressField;
            if (invoice.Fields.TryGetValue("CustomerAddress", out customerAddressField))
            {
                if (customerAddressField.Value.ValueType == FieldValueType.String)
                {
                    string customerAddress = customerAddressField.Value.AsString();
                    Console.WriteLine($"    Customer Address: '{customerAddress}', with confidence {customerAddressField.Confidence}");
                }
            }

            FormField customerAddressRecipientField;
            if (invoice.Fields.TryGetValue("CustomerAddressRecipient", out customerAddressRecipientField))
            {
                if (customerAddressRecipientField.Value.ValueType == FieldValueType.String)
                {
                    string customerAddressRecipient = customerAddressRecipientField.Value.AsString();
                    Console.WriteLine($"    Customer address recipient: '{customerAddressRecipient}', with confidence {customerAddressRecipientField.Confidence}");
                }
            }

            FormField invoiceTotalField;
            if (invoice.Fields.TryGetValue("InvoiceTotal", out invoiceTotalField))
            {
                if (invoiceTotalField.Value.ValueType == FieldValueType.Float)
                {
                    float invoiceTotal = invoiceTotalField.Value.AsFloat();
                    Console.WriteLine($"    Invoice Total: '{invoiceTotal}', with confidence {invoiceTotalField.Confidence}");
                }
            }
        }
コード例 #9
0
        public async Task RecognizeInvoicesFromFile()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:FormRecognizerSampleRecognizeInvoicesFileStream
#if SNIPPET
            string invoicePath = "<invoicePath>";
#else
            string invoicePath = FormRecognizerTestEnvironment.CreatePath("recommended_invoice.jpg");
#endif

            using var stream = new FileStream(invoicePath, FileMode.Open);
            var options = new RecognizeInvoicesOptions()
            {
                Locale = "en-US"
            };

            RecognizeInvoicesOperation operation = await client.StartRecognizeInvoicesAsync(stream, options);

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection invoices = operationResponse.Value;

            // To see the list of all the supported fields returned by service and its corresponding types, consult:
            // https://aka.ms/formrecognizer/invoicefields

            RecognizedForm invoice = invoices.Single();

            if (invoice.Fields.TryGetValue("VendorName", out FormField vendorNameField))
            {
                if (vendorNameField.Value.ValueType == FieldValueType.String)
                {
                    string vendorName = vendorNameField.Value.AsString();
                    Console.WriteLine($"Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("CustomerName", out FormField customerNameField))
            {
                if (customerNameField.Value.ValueType == FieldValueType.String)
                {
                    string customerName = customerNameField.Value.AsString();
                    Console.WriteLine($"Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("Items", out FormField itemsField))
            {
                if (itemsField.Value.ValueType == FieldValueType.List)
                {
                    foreach (FormField itemField in itemsField.Value.AsList())
                    {
                        Console.WriteLine("Item:");

                        if (itemField.Value.ValueType == FieldValueType.Dictionary)
                        {
                            IReadOnlyDictionary <string, FormField> itemFields = itemField.Value.AsDictionary();

                            if (itemFields.TryGetValue("Description", out FormField itemDescriptionField))
                            {
                                if (itemDescriptionField.Value.ValueType == FieldValueType.String)
                                {
                                    string itemDescription = itemDescriptionField.Value.AsString();

                                    Console.WriteLine($"  Description: '{itemDescription}', with confidence {itemDescriptionField.Confidence}");
                                }
                            }

                            if (itemFields.TryGetValue("Quantity", out FormField itemQuantityField))
                            {
                                if (itemQuantityField.Value.ValueType == FieldValueType.Float)
                                {
                                    float quantityAmount = itemQuantityField.Value.AsFloat();

                                    Console.WriteLine($"  Quantity: '{quantityAmount}', with confidence {itemQuantityField.Confidence}");
                                }
                            }

                            if (itemFields.TryGetValue("UnitPrice", out FormField itemUnitPriceField))
                            {
                                if (itemUnitPriceField.Value.ValueType == FieldValueType.Float)
                                {
                                    float itemUnitPrice = itemUnitPriceField.Value.AsFloat();

                                    Console.WriteLine($"  UnitPrice: '{itemUnitPrice}', with confidence {itemUnitPriceField.Confidence}");
                                }
                            }

                            if (itemFields.TryGetValue("Tax", out FormField itemTaxPriceField))
                            {
                                if (itemTaxPriceField.Value.ValueType == FieldValueType.Float)
                                {
                                    try
                                    {
                                        float itemTax = itemTaxPriceField.Value.AsFloat();
                                        Console.WriteLine($"  Tax: '{itemTax}', with confidence {itemTaxPriceField.Confidence}");
                                    }
                                    catch
                                    {
                                        string itemTaxText = itemTaxPriceField.ValueData.Text;
                                        Console.WriteLine($"  Tax: '{itemTaxText}', with confidence {itemTaxPriceField.Confidence}");
                                    }
                                }
                            }

                            if (itemFields.TryGetValue("Amount", out FormField itemAmountField))
                            {
                                if (itemAmountField.Value.ValueType == FieldValueType.Float)
                                {
                                    float itemAmount = itemAmountField.Value.AsFloat();

                                    Console.WriteLine($"  Amount: '{itemAmount}', with confidence {itemAmountField.Confidence}");
                                }
                            }
                        }
                    }
                }
            }

            if (invoice.Fields.TryGetValue("SubTotal", out FormField subTotalField))
            {
                if (subTotalField.Value.ValueType == FieldValueType.Float)
                {
                    float subTotal = subTotalField.Value.AsFloat();
                    Console.WriteLine($"Sub Total: '{subTotal}', with confidence {subTotalField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("TotalTax", out FormField totalTaxField))
            {
                if (totalTaxField.Value.ValueType == FieldValueType.Float)
                {
                    float totalTax = totalTaxField.Value.AsFloat();
                    Console.WriteLine($"Total Tax: '{totalTax}', with confidence {totalTaxField.Confidence}");
                }
            }

            if (invoice.Fields.TryGetValue("InvoiceTotal", out FormField invoiceTotalField))
            {
                if (invoiceTotalField.Value.ValueType == FieldValueType.Float)
                {
                    float invoiceTotal = invoiceTotalField.Value.AsFloat();
                    Console.WriteLine($"Invoice Total: '{invoiceTotal}', with confidence {invoiceTotalField.Confidence}");
                }
            }

            #endregion
        }
コード例 #10
0
    // </snippet_bc_print>

    // <snippet_invoice_call>
    private static async Task AnalyzeInvoice(
        FormRecognizerClient recognizerClient, string invoiceUrl)
    {
        var options = new RecognizeInvoicesOptions()
        {
            Locale = "en-US"
        };
        RecognizedFormCollection invoices = await recognizerClient.StartRecognizeInvoicesFromUriAsync(invoiceUrl, options).WaitForCompletionAsync();

        // </snippet_invoice_call>
        // <snippet_invoice_print>
        RecognizedForm invoice = invoices.Single();

        FormField invoiceIdField;

        if (invoice.Fields.TryGetValue("InvoiceId", out invoiceIdField))
        {
            if (invoiceIdField.Value.ValueType == FieldValueType.String)
            {
                string invoiceId = invoiceIdField.Value.AsString();
                Console.WriteLine($"    Invoice Id: '{invoiceId}', with confidence {invoiceIdField.Confidence}");
            }
        }

        FormField invoiceDateField;

        if (invoice.Fields.TryGetValue("InvoiceDate", out invoiceDateField))
        {
            if (invoiceDateField.Value.ValueType == FieldValueType.Date)
            {
                DateTime invoiceDate = invoiceDateField.Value.AsDate();
                Console.WriteLine($"    Invoice Date: '{invoiceDate}', with confidence {invoiceDateField.Confidence}");
            }
        }

        FormField dueDateField;

        if (invoice.Fields.TryGetValue("DueDate", out dueDateField))
        {
            if (dueDateField.Value.ValueType == FieldValueType.Date)
            {
                DateTime dueDate = dueDateField.Value.AsDate();
                Console.WriteLine($"    Due Date: '{dueDate}', with confidence {dueDateField.Confidence}");
            }
        }

        FormField vendorNameField;

        if (invoice.Fields.TryGetValue("VendorName", out vendorNameField))
        {
            if (vendorNameField.Value.ValueType == FieldValueType.String)
            {
                string vendorName = vendorNameField.Value.AsString();
                Console.WriteLine($"    Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
            }
        }

        FormField vendorAddressField;

        if (invoice.Fields.TryGetValue("VendorAddress", out vendorAddressField))
        {
            if (vendorAddressField.Value.ValueType == FieldValueType.String)
            {
                string vendorAddress = vendorAddressField.Value.AsString();
                Console.WriteLine($"    Vendor Address: '{vendorAddress}', with confidence {vendorAddressField.Confidence}");
            }
        }

        FormField customerNameField;

        if (invoice.Fields.TryGetValue("CustomerName", out customerNameField))
        {
            if (customerNameField.Value.ValueType == FieldValueType.String)
            {
                string customerName = customerNameField.Value.AsString();
                Console.WriteLine($"    Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
            }
        }

        FormField customerAddressField;

        if (invoice.Fields.TryGetValue("CustomerAddress", out customerAddressField))
        {
            if (customerAddressField.Value.ValueType == FieldValueType.String)
            {
                string customerAddress = customerAddressField.Value.AsString();
                Console.WriteLine($"    Customer Address: '{customerAddress}', with confidence {customerAddressField.Confidence}");
            }
        }

        FormField customerAddressRecipientField;

        if (invoice.Fields.TryGetValue("CustomerAddressRecipient", out customerAddressRecipientField))
        {
            if (customerAddressRecipientField.Value.ValueType == FieldValueType.String)
            {
                string customerAddressRecipient = customerAddressRecipientField.Value.AsString();
                Console.WriteLine($"    Customer address recipient: '{customerAddressRecipient}', with confidence {customerAddressRecipientField.Confidence}");
            }
        }

        FormField invoiceTotalField;

        if (invoice.Fields.TryGetValue("InvoiceTotal", out invoiceTotalField))
        {
            if (invoiceTotalField.Value.ValueType == FieldValueType.Float)
            {
                float invoiceTotal = invoiceTotalField.Value.AsFloat();
                Console.WriteLine($"    Invoice Total: '{invoiceTotal}', with confidence {invoiceTotalField.Confidence}");
            }
        }
    }
コード例 #11
0
        public async Task StartRecognizeInvoicesCanParseMultipageForm(bool useStream)
        {
            var client  = CreateFormRecognizerClient();
            var options = new RecognizeInvoicesOptions()
            {
                IncludeFieldElements = true
            };
            RecognizeInvoicesOperation operation;

            if (useStream)
            {
                using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceMultipage);
                using (Recording.DisableRequestBodyRecording())
                {
                    operation = await client.StartRecognizeInvoicesAsync(stream, options);
                }
            }
            else
            {
                var uri = FormRecognizerTestEnvironment.CreateUri(TestFile.InvoiceMultipage);
                operation = await client.StartRecognizeInvoicesFromUriAsync(uri, options);
            }

            RecognizedFormCollection recognizedForms = await operation.WaitForCompletionAsync();

            var form = recognizedForms.Single();

            Assert.NotNull(form);

            // The expected values are based on the values returned by the service, and not the actual
            // values present in the invoice. We are not testing the service here, but the SDK.

            Assert.AreEqual("prebuilt:invoice", form.FormType);
            Assert.AreEqual(1, form.PageRange.FirstPageNumber);
            Assert.AreEqual(2, form.PageRange.LastPageNumber);

            Assert.NotNull(form.Fields);

            Assert.True(form.Fields.ContainsKey("VendorName"));
            Assert.True(form.Fields.ContainsKey("RemittanceAddressRecipient"));
            Assert.True(form.Fields.ContainsKey("RemittanceAddress"));

            FormField vendorName = form.Fields["VendorName"];

            Assert.AreEqual(2, vendorName.ValueData.PageNumber);
            Assert.AreEqual("Southridge Video", vendorName.Value.AsString());

            FormField addressRecepient = form.Fields["RemittanceAddressRecipient"];

            Assert.AreEqual(1, addressRecepient.ValueData.PageNumber);
            Assert.AreEqual("Contoso Ltd.", addressRecepient.Value.AsString());

            FormField address = form.Fields["RemittanceAddress"];

            Assert.AreEqual(1, address.ValueData.PageNumber);
            Assert.AreEqual("2345 Dogwood Lane Birch, Kansas 98123", address.Value.AsString());

            ValidatePrebuiltForm(
                form,
                includeFieldElements: true,
                expectedFirstPageNumber: 1,
                expectedLastPageNumber: 2);
        }