/
AnalyzeInvoicesAsync.java
191 lines (174 loc) · 10.1 KB
/
AnalyzeInvoicesAsync.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.documentintelligence;
import com.azure.ai.documentintelligence.models.AnalyzeDocumentRequest;
import com.azure.ai.documentintelligence.models.AnalyzeResult;
import com.azure.ai.documentintelligence.models.AnalyzeResultOperation;
import com.azure.ai.documentintelligence.models.Document;
import com.azure.ai.documentintelligence.models.DocumentField;
import com.azure.ai.documentintelligence.models.DocumentFieldType;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.PollerFlux;
import reactor.core.publisher.Mono;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* Async sample for analyzing commonly found invoice fields from a local file input stream of an invoice document.
* See fields found on an invoice <a href=https://aka.ms/documentintelligence/invoicefields>here</a>
*/
public class AnalyzeInvoicesAsync {
/**
* Main method to invoke this demo.
*
* @param args Unused. Arguments to the program.
* @throws IOException Exception thrown when there is an error in reading all the bytes from the File.
*/
public static void main(final String[] args) throws IOException {
// Instantiate a client that will be used to call the service.
DocumentIntelligenceAsyncClient client = new DocumentIntelligenceClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("https://{endpoint}.cognitiveservices.azure.com/")
.buildAsyncClient();
File invoice = new File("../documentintelligence/azure-ai-documentintelligence/src/samples/resources/"
+ "sample-forms/invoices/sample_invoice.jpg");
PollerFlux<AnalyzeResultOperation, AnalyzeResultOperation> analyzeInvoicePoller =
client.beginAnalyzeDocument("prebuilt-invoice",
null,
null,
null,
null,
null,
null,
new AnalyzeDocumentRequest().setBase64Source(Files.readAllBytes(invoice.toPath()))
);
Mono<AnalyzeResult> analyzeInvoiceResultMono = analyzeInvoicePoller
.last()
.flatMap(pollResponse -> {
if (pollResponse.getStatus().isComplete()) {
System.out.println("Polling completed successfully");
return pollResponse.getFinalResult();
} else {
return Mono.error(new RuntimeException("Polling completed unsuccessfully with status:"
+ pollResponse.getStatus()));
}
}).map(AnalyzeResultOperation::getAnalyzeResult);
analyzeInvoiceResultMono.subscribe(analyzeInvoiceResult -> {
for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
Document analyzedInvoice = analyzeInvoiceResult.getDocuments().get(i);
Map<String, DocumentField> invoiceFields = analyzedInvoice.getFields();
System.out.printf("----------- Analyzing invoice %d -----------%n", i);
DocumentField vendorNameField = invoiceFields.get("VendorName");
if (vendorNameField != null) {
if (DocumentFieldType.STRING == vendorNameField.getType()) {
String merchantName = vendorNameField.getValueString();
System.out.printf("Vendor Name: %s, confidence: %.2f%n",
merchantName, vendorNameField.getConfidence());
}
}
DocumentField vendorAddressField = invoiceFields.get("VendorAddress");
if (vendorAddressField != null) {
if (DocumentFieldType.STRING == vendorAddressField.getType()) {
String merchantAddress = vendorAddressField.getValueString();
System.out.printf("Vendor address: %s, confidence: %.2f%n",
merchantAddress, vendorAddressField.getConfidence());
}
}
DocumentField customerNameField = invoiceFields.get("CustomerName");
if (customerNameField != null) {
if (DocumentFieldType.STRING == customerNameField.getType()) {
String merchantAddress = customerNameField.getValueString();
System.out.printf("Customer Name: %s, confidence: %.2f%n",
merchantAddress, customerNameField.getConfidence());
}
}
DocumentField customerAddressRecipientField = invoiceFields.get("CustomerAddressRecipient");
if (customerAddressRecipientField != null) {
if (DocumentFieldType.STRING == customerAddressRecipientField.getType()) {
String customerAddr = customerAddressRecipientField.getValueString();
System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n",
customerAddr, customerAddressRecipientField.getConfidence());
}
}
DocumentField invoiceIdField = invoiceFields.get("InvoiceId");
if (invoiceIdField != null) {
if (DocumentFieldType.STRING == invoiceIdField.getType()) {
String invoiceId = invoiceIdField.getValueString();
System.out.printf("Invoice ID: %s, confidence: %.2f%n",
invoiceId, invoiceIdField.getConfidence());
}
}
DocumentField invoiceDateField = invoiceFields.get("InvoiceDate");
if (customerNameField != null) {
if (DocumentFieldType.DATE == invoiceDateField.getType()) {
LocalDate invoiceDate = invoiceDateField.getValueDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateField.getConfidence());
}
}
DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
if (customerAddressRecipientField != null) {
if (DocumentFieldType.NUMBER == invoiceTotalField.getType()) {
Double invoiceTotal = invoiceTotalField.getValueNumber();
System.out.printf("Invoice Total: %.2f, confidence: %.2f%n",
invoiceTotal, invoiceTotalField.getConfidence());
}
}
DocumentField invoiceItemsField = invoiceFields.get("Items");
if (invoiceItemsField != null) {
System.out.printf("Invoice Items: %n");
if (DocumentFieldType.ARRAY == invoiceItemsField.getType()) {
List<DocumentField> invoiceItems = invoiceItemsField.getValueArray();
invoiceItems.stream()
.filter(invoiceItem -> DocumentFieldType.OBJECT == invoiceItem.getType())
.map(DocumentField::getValueObject)
.forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {
// See a full list of fields found on an invoice here:
// https://aka.ms/documentintelligence/invoicefields
if ("Description".equals(key)) {
if (DocumentFieldType.STRING == documentField.getType()) {
String name = documentField.getValueString();
System.out.printf("Description: %s, confidence: %.2fs%n",
name, documentField.getConfidence());
}
}
if ("Quantity".equals(key)) {
if (DocumentFieldType.NUMBER == documentField.getType()) {
Double quantity = documentField.getValueNumber();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, documentField.getConfidence());
}
}
if ("UnitPrice".equals(key)) {
if (DocumentFieldType.NUMBER == documentField.getType()) {
Double unitPrice = documentField.getValueNumber();
System.out.printf("Unit Price: %f, confidence: %.2f%n",
unitPrice, documentField.getConfidence());
}
}
if ("ProductCode".equals(key)) {
if (DocumentFieldType.NUMBER == documentField.getType()) {
Double productCode = documentField.getValueNumber();
System.out.printf("Product Code: %f, confidence: %.2f%n",
productCode, documentField.getConfidence());
}
}
}));
}
}
}
});
// The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep
// the thread so the program does not end before the send operation is complete. Using .block() instead of
// .subscribe() will turn this into a synchronous call.
try {
TimeUnit.MINUTES.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}