В этом кратком руководстве используются следующие функции для анализа и извлечения данных и значений из форм и документов:
Макет — анализ и извлечение таблиц, строк, слов и меток выбора, таких как переключатели и флажки в документах форм, без необходимости обучения модели.
Предварительно созданный счет— анализ и извлечение общих полей из определенных типов документов с помощью предварительно обученной модели.
Подписка Azure — создайте бесплатную учетную запись.
Последняя версия Visual Studio Code или предпочтительная интегрированная среда разработки.
См.Java в Visual Studio Code.
Совет
- Visual Studio Code предлагает Пакет кодировки для Java для Windows и macOS. Пакет кодировки — это набор VS Code, комплект SDK для Java (JDK) и набор рекомендуемых расширений Microsoft. Пакет кодировки можно также использовать для исправления существующей среды разработки.
- Если вы используете VS Code и пакет кода для Java, установите расширение Gradle для Java .
Если вы не используете Visual Studio Code, убедитесь, что в среде разработки установлено следующее:
Служба ИИ Azure или ресурс аналитики документов. После получения подписки Azure создайте ресурс аналитики документов с несколькими службами в портал Azure, чтобы получить ключ и конечную точку. Используйте бесплатную ценовую категорию (F0
), чтобы опробовать службу, а затем выполните обновление до платного уровня для рабочей среды.
Совет
Создайте ресурс служб искусственного интеллекта Azure, если вы планируете получить доступ к нескольким службам ИИ Azure в рамках одной конечной точки или ключа. Только для доступа к аналитике документов создайте ресурс аналитики документов. Если вы планируете использовать проверку подлинности Microsoft Entra, вам потребуется ресурс с одним обслуживанием.
После развертывания ресурса выберите Перейти к ресурсу. Вам потребуется ключ и конечная точка из ресурса, создаваемого для подключения приложения к API аналитики документов. Позже вы вставьте ключ и конечную точку в код:
В окне консоли (например, cmd, PowerShell или Bash) создайте новый каталог для приложения под названием doc-intel-app и перейдите к нему.
mkdir doc-intel-app && doc-intel-app
mkdir doc-intel-app; cd doc-intel-app
Выполните команду gradle init
из рабочей папки. Эта команда создает основные файлы сборки для Gradle, включая build.gradle.kts, который используется во время выполнения для создания и настройки приложения.
gradle init --type basic
Когда появится запрос на выбор предметно-ориентированного языка, выберите Kotlin.
Примите имя проекта по умолчанию (doc-intel-app), выбрав "Возврат " или "ВВОД".
В окне консоли (например, cmd, PowerShell или Bash) создайте новый каталог для приложения под названием form-recognize-app и перейдите к нему.
mkdir form-recognize-app && form-recognize-app
mkdir form-recognize-app; cd form-recognize-app
Выполните команду gradle init
из рабочей папки. Эта команда создает основные файлы сборки для Gradle, включая build.gradle.kts, который используется во время выполнения для создания и настройки приложения.
gradle init --type basic
Когда появится запрос на выбор предметно-ориентированного языка, выберите Kotlin.
Примите имя проекта по умолчанию (form-recognize-app), выбрав "Возврат " или "Ввод".
Установка клиентской библиотеки
В этом кратком руководстве используется диспетчер зависимостей Gradle. Клиентскую библиотеку и информацию для других диспетчеров зависимостей можно найти в центральном репозитории Maven.
Откройте файл проекта Build. gradle. КТС в интегрированной среде разработки. Скопируйте и вставьте следующий код, чтобы включить клиентскую библиотеку в качестве инструкции implementation
, а также необходимые подключаемые модули и параметры.
plugins {
java
application
}
application {
mainClass.set("DocIntelligence")
}
repositories {
mavenCentral()
}
dependencies {
implementation group: 'com.azure', name: 'azure-ai-documentintelligence', version: '1.0.0'
}
В этом кратком руководстве используется диспетчер зависимостей Gradle. Клиентскую библиотеку и информацию для других диспетчеров зависимостей можно найти в центральном репозитории Maven.
Откройте файл проекта Build. gradle. КТС в интегрированной среде разработки. Скопируйте и вставьте следующий код, чтобы включить клиентскую библиотеку в качестве инструкции implementation
, а также необходимые подключаемые модули и параметры.
plugins {
java
application
}
application {
mainClass.set("FormRecognizer")
}
repositories {
mavenCentral()
}
dependencies {
implementation group: 'com.azure', name: 'azure-ai-formrecognizer', version: '4.1.0'
}
В этом кратком руководстве используется диспетчер зависимостей Gradle. Клиентскую библиотеку и информацию для других диспетчеров зависимостей можно найти в центральном репозитории Maven.
Откройте файл проекта Build. gradle. КТС в интегрированной среде разработки. Скопируйте и вставьте следующий код, чтобы включить клиентскую библиотеку в качестве инструкции implementation
, а также необходимые подключаемые модули и параметры.
plugins {
java
application
}
application {
mainClass.set("FormRecognizer")
}
repositories {
mavenCentral()
}
dependencies {
implementation group: 'com.azure', name: 'azure-ai-formrecognizer', version: '4.0.0'
}
Чтобы взаимодействовать со службой аналитики DocumentIntelligenceClient
документов, необходимо создать экземпляр класса. Для этого вы создадите AzureKeyCredential
с key
помощью портал Azure и DocumentIntelligenceClient
экземпляра с AzureKeyCredential
помощью аналитики документовendpoint
.
Чтобы взаимодействовать со службой аналитики DocumentAnalysisClient
документов, необходимо создать экземпляр класса. Для этого вы создадите AzureKeyCredential
с key
помощью портал Azure и DocumentAnalysisClient
экземпляра с AzureKeyCredential
помощью аналитики документовendpoint
.
В каталоге doc-intel-app выполните следующую команду:
mkdir -p src/main/java
Вы создадите следующую структуру каталогов:
Перейдите в каталог java
и создайте файл с именем DocIntelligence.java
.
Совет
- Вы можете создать новый файл с помощью PowerShell.
- Откройте окно PowerShell в каталоге проекта, удерживая клавишу Shift и нажав правой кнопкой мыши на папку.
- Введите следующую команду New-Item DocIntelligence.java.
Откройте файл DocIntelligence.java
. Скопируйте и вставьте один из следующих примеров кода в приложение:
Перейдите в каталог java
и создайте файл с именем FormRecognizer.java
.
Совет
- Вы можете создать новый файл с помощью PowerShell.
- Откройте окно PowerShell в каталоге проекта, удерживая клавишу Shift и нажав правой кнопкой мыши на папку.
- Введите следующую команду: New-Item FormRecognizer.java.
Откройте файл FormRecognizer.java
. Скопируйте и вставьте один из следующих примеров кода в приложение:
Важно!
Обязательно удалите ключ из кода, когда завершите работу, и ни в коем случае не публикуйте его в открытом доступе. Для рабочей среды используйте безопасный способ хранения и доступа к учетным данным, например Azure Key Vault. Дополнительные сведения см. в статье "Безопасность служб искусственного интеллекта Azure".
Извлеките из документов текст, метки выбора, стили текста, сведения о структуре таблиц и координаты ограничивающих рамок для них.
- В этом примере потребуется файл документа в URI. В этом кратком руководстве можно использовать наш пример документа .
- Чтобы проанализировать заданный файл по универсальному коду ресурса, используйте метод
beginAnalyzeDocumentFromUrl
и передайте prebuilt-layout
в качестве идентификатора модели. Возвращаемое значение — это объект AnalyzeResult
, содержащий данные об отправленном документе.
- Значение универсального кода ресурса (URI) для файла было добавлено в переменную
documentUrl
в методе Main.
Добавьте в файл DocIntelligence.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
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.DocumentTable;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import java.util.List;
public class DocIntelligence {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(String[] args) {
// create your `DocumentIntelligenceClient` instance and `AzureKeyCredential` variable
DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
// sample document
String modelId = "prebuilt-layout";
String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
SyncPoller <AnalyzeResultOperation, AnalyzeResultOperation> analyzeLayoutPoller =
client.beginAnalyzeDocument(modelId,
null,
null,
null,
null,
null,
null,
new AnalyzeDocumentRequest().setUrlSource(documentUrl));
AnalyzeResult analyzeLayoutResult = analyzeLayoutPoller.getFinalResult().getAnalyzeResult();
// pages
analyzeLayoutResult.getPages().forEach(documentPage -> {
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
documentPage.getWidth(),
documentPage.getHeight(),
documentPage.getUnit());
// lines
documentPage.getLines().forEach(documentLine ->
System.out.printf("Line '%s' is within a bounding polygon %s.%n",
documentLine.getContent(),
documentLine.getPolygon()));
// words
documentPage.getWords().forEach(documentWord ->
System.out.printf("Word '%s' has a confidence score of %.2f.%n",
documentWord.getContent(),
documentWord.getConfidence()));
// selection marks
documentPage.getSelectionMarks().forEach(documentSelectionMark ->
System.out.printf("Selection mark is '%s' and is within a bounding polygon %s with confidence %.2f.%n",
documentSelectionMark.getState().toString(),
documentSelectionMark.getPolygon(),
documentSelectionMark.getConfidence()));
});
// tables
List < DocumentTable > tables = analyzeLayoutResult.getTables();
for (int i = 0; i < tables.size(); i++) {
DocumentTable documentTable = tables.get(i);
System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
documentTable.getColumnCount());
documentTable.getCells().forEach(documentTableCell -> {
System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
documentTableCell.getRowIndex(), documentTableCell.getColumnIndex());
});
System.out.println();
}
// styles
analyzeLayoutResult.getStyles().forEach(documentStyle -
> System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten()));
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к основному каталогу проекта — doc-intel-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run
Добавьте в файл FormRecognizer.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
import com.azure.ai.formrecognizer.documentanalysis.models.*;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import java.time.LocalDate;
import java.util.Map;
import java.util.stream.Collectors;
public class FormRecognizer {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(String[] args) {
// create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
// sample document
String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
String modelId = "prebuilt-layout";
SyncPoller < OperationResult, AnalyzeResult > analyzeLayoutResultPoller =
client.beginAnalyzeDocumentFromUrl(modelId, documentUrl);
AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult();
// pages
analyzeLayoutResult.getPages().forEach(documentPage -> {
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
documentPage.getWidth(),
documentPage.getHeight(),
documentPage.getUnit());
// lines
documentPage.getLines().forEach(documentLine ->
System.out.printf("Line %s is within a bounding polygon %s.%n",
documentLine.getContent(),
documentLine.getPolygon().toString()));
// words
documentPage.getWords().forEach(documentWord ->
System.out.printf("Word '%s' has a confidence score of %.2f%n",
documentWord.getContent(),
documentWord.getConfidence()));
// selection marks
documentPage.getSelectionMarks().forEach(documentSelectionMark ->
System.out.printf("Selection mark is %s and is within a bounding polygon %s with confidence %.2f.%n",
documentSelectionMark.getState().toString(),
documentSelectionMark.getPolygon().toString(),
documentSelectionMark.getConfidence()));
});
// tables
List < DocumentTable > tables = analyzeLayoutResult.getTables();
for (int i = 0; i < tables.size(); i++) {
DocumentTable documentTable = tables.get(i);
System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
documentTable.getColumnCount());
documentTable.getCells().forEach(documentTableCell -> {
System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
documentTableCell.getRowIndex(), documentTableCell.getColumnIndex());
});
System.out.println();
}
}
// Utility function to get the bounding polygon coordinates
private static String getBoundingCoordinates(List < Point > Polygon) {
return Polygon.stream().map(point -> String.format("[%.2f, %.2f]", point.getX(),
point.getY())).collect(Collectors.joining(", "));
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к главному каталогу проекта — form-recognize-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run
Выходные данные модели макета
Ниже приведен фрагмент ожидаемых выходных данных:
Table 0 has 5 rows and 3 columns.
Cell 'Title of each class', has row index 0 and column index 0.
Cell 'Trading Symbol', has row index 0 and column index 1.
Cell 'Name of exchange on which registered', has row index 0 and column index 2.
Cell 'Common stock, $0.00000625 par value per share', has row index 1 and column index 0.
Cell 'MSFT', has row index 1 and column index 1.
Cell 'NASDAQ', has row index 1 and column index 2.
Cell '2.125% Notes due 2021', has row index 2 and column index 0.
Cell 'MSFT', has row index 2 and column index 1.
Cell 'NASDAQ', has row index 2 and column index 2.
Cell '3.125% Notes due 2028', has row index 3 and column index 0.
Cell 'MSFT', has row index 3 and column index 1.
Cell 'NASDAQ', has row index 3 and column index 2.
Cell '2.625% Notes due 2033', has row index 4 and column index 0.
Cell 'MSFT', has row index 4 and column index 1.
Cell 'NASDAQ', has row index 4 and column index 2.
Чтобы просмотреть все выходные данные, посетите репозиторий примеров Azure на GitHub, где находятся выходные данные модели макета.
Добавьте в файл FormRecognizer.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentTable;
import com.azure.ai.formrecognizer.documentanalysis.models.Point;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import java.util.List;
import java.util.stream.Collectors;
public class FormRecognizer {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(String[] args) {
// create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
// sample document
String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
String modelId = "prebuilt-layout";
SyncPoller < OperationResult, AnalyzeResult > analyzeLayoutPoller =
client.beginAnalyzeDocumentFromUrl(modelId, documentUrl);
AnalyzeResult analyzeLayoutResult = analyzeLayoutPoller.getFinalResult();
// pages
analyzeLayoutResult.getPages().forEach(documentPage -> {
System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
documentPage.getWidth(),
documentPage.getHeight(),
documentPage.getUnit());
// lines
documentPage.getLines().forEach(documentLine ->
System.out.printf("Line '%s' is within a bounding polygon %s.%n",
documentLine.getContent(),
getBoundingCoordinates(documentLine.getPolygon())));
// words
documentPage.getWords().forEach(documentWord ->
System.out.printf("Word '%s' has a confidence score of %.2f.%n",
documentWord.getContent(),
documentWord.getConfidence()));
// selection marks
documentPage.getSelectionMarks().forEach(documentSelectionMark ->
System.out.printf("Selection mark is '%s' and is within a bounding polygon %s with confidence %.2f.%n",
documentSelectionMark.getSelectionMarkState().toString(),
getBoundingCoordinates(documentSelectionMark.getPolygon()),
documentSelectionMark.getConfidence()));
});
// tables
List < DocumentTable > tables = analyzeLayoutResult.getTables();
for (int i = 0; i < tables.size(); i++) {
DocumentTable documentTable = tables.get(i);
System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
documentTable.getColumnCount());
documentTable.getCells().forEach(documentTableCell -> {
System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
documentTableCell.getRowIndex(), documentTableCell.getColumnIndex());
});
System.out.println();
}
// styles
analyzeLayoutResult.getStyles().forEach(documentStyle -
> System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten()));
}
/**
* Utility function to get the bounding polygon coordinates.
*/
private static String getBoundingCoordinates(List < Point > Polygon) {
return Polygon.stream().map(point -> String.format("[%.2f, %.2f]", point.getX(),
point.getY())).collect(Collectors.joining(", "));
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к главному каталогу проекта — form-recognize-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run
Предварительно созданная модель
Анализ и извлечение общих полей из конкретных типов документов с помощью предварительно созданной модели. В этом примере мы анализируем счет с помощью предварительно созданной модели счета .
Совет
Вы можете использовать не только счета. Есть несколько предварительно созданных моделей, у каждой из которых собственный набор поддерживаемых полей. Модель, используемая для analyze
операции, зависит от типа документа, который необходимо проанализировать. См. Извлечение данных модели.
- Анализ счета с помощью модели готового счета. Для работы с этим кратким руководством можно использовать пример документа со счетом.
- Мы добавили значение URL файла в переменную
invoiceUrl
, расположенную в верхней части файла.
- Чтобы проанализировать заданный файл по универсальному коду ресурса, используйте метод
beginAnalyzeDocuments
и передайте PrebuiltModels.Invoice
в качестве идентификатора модели. Возвращаемое значение — это объект result
, содержащий данные об отправленном документе.
- Для простоты здесь показаны не все пары "ключ-значение", возвращаемые службой. Список всех поддерживаемых полей и соответствующих типов см. на странице концепции Счет.
Добавьте в файл DocIntelligence.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
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.SyncPoller;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
public class DocIntelligence {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(String[] args) {
// sample document
String modelId = "prebuilt-invoice";
String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";
public static void main(final String[] args) throws IOException {
// Instantiate a client that will be used to call the service.
DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
SyncPoller<AnalyzeResultOperation, AnalyzeResultOperation > analyzeInvoicesPoller =
client.beginAnalyzeDocument(modelId,
null,
null,
null,
null,
null,
null,
new AnalyzeDocumentRequest().setUrlSource(invoiceUrl));
AnalyzeResult analyzeInvoiceResult = analyzeInvoicesPoller.getFinalResult().getAnalyzeResult();
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 -> 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());
}
}
}));
}
}
}
}
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к основному каталогу проекта — doc-intel-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run
Добавьте в файл FormRecognizer.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
import com.azure.ai.formrecognizer.documentanalysis.models.*;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import java.time.LocalDate;
import java.util.Map;
import java.util.stream.Collectors;
public class FormRecognizer {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(final String[] args) throws IOException {
// create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
// sample document
String modelId = "prebuilt-invoice";
String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";
SyncPoller < OperationResult, AnalyzeResult > analyzeInvoicePoller = client.beginAnalyzeDocumentFromUrl(modelId, invoiceUrl);
AnalyzeResult analyzeInvoiceResult = analyzeInvoicePoller.getFinalResult();
for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
AnalyzedDocument 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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateField.getConfidence());
}
}
DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
if (customerAddressRecipientField != null) {
if (DocumentFieldType.DOUBLE == invoiceTotalField.getType()) {
Double invoiceTotal = invoiceTotalField.getValueAsDouble();
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.LIST == invoiceItemsField.getType()) {
List < DocumentField > invoiceItems = invoiceItemsField.getValueAsList();
invoiceItems.stream()
.filter(invoiceItem -> DocumentFieldType.MAP == invoiceItem.getType())
.map(documentField -> documentField.getValueAsMap())
.forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {
// See a full list of fields found on an invoice here:
// https://aka.ms/formrecognizer/invoicefields
if ("Description".equals(key)) {
if (DocumentFieldType.STRING == documentField.getType()) {
String name = documentField.getValueAsString();
System.out.printf("Description: %s, confidence: %.2fs%n",
name, documentField.getConfidence());
}
}
if ("Quantity".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double quantity = documentField.getValueAsDouble();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, documentField.getConfidence());
}
}
if ("UnitPrice".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double unitPrice = documentField.getValueAsDouble();
System.out.printf("Unit Price: %f, confidence: %.2f%n",
unitPrice, documentField.getConfidence());
}
}
if ("ProductCode".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double productCode = documentField.getValueAsDouble();
System.out.printf("Product Code: %f, confidence: %.2f%n",
productCode, documentField.getConfidence());
}
}
}));
}
}
}
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к основному каталогу проекта — doc-intel-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run
Выходные данные предварительно созданной модели
Ниже приведен фрагмент ожидаемых выходных данных:
----------- Analyzing invoice 0 -----------
Analyzed document has doc type invoice with confidence : 1.00
Vendor Name: CONTOSO LTD., confidence: 0.92
Vendor address: 123 456th St New York, NY, 10001, confidence: 0.91
Customer Name: MICROSOFT CORPORATION, confidence: 0.84
Customer Address Recipient: Microsoft Corp, confidence: 0.92
Invoice ID: INV-100, confidence: 0.97
Invoice Date: 2019-11-15, confidence: 0.97
Чтобы просмотреть все выходные данные, посетите репозиторий примеров Azure на GitHub, где находятся выходные данные модели готового счета.
Добавьте в файл FormRecognizer.java
следующий пример кода. Убедитесь, что вы обновляете переменные ключа и конечной точки со значениями из экземпляра аналитики документов портал Azure:
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzedDocument;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentField;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentFieldType;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
public class FormRecognizer {
// set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
private static final String endpoint = "<your-endpoint>";
private static final String key = "<your-key>";
public static void main(String[] args) {
// create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
// sample document
String modelId = "prebuilt-invoice";
String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";
SyncPoller < OperationResult, AnalyzeResult > analyzeInvoicePoller = client.beginAnalyzeDocumentFromUrl(modelId, invoiceUrl);
AnalyzeResult analyzeInvoiceResult = analyzeInvoicePoller.getFinalResult();
for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
AnalyzedDocument 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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsString();
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.getValueAsDate();
System.out.printf("Invoice Date: %s, confidence: %.2f%n",
invoiceDate, invoiceDateField.getConfidence());
}
}
DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
if (customerAddressRecipientField != null) {
if (DocumentFieldType.DOUBLE == invoiceTotalField.getType()) {
Double invoiceTotal = invoiceTotalField.getValueAsDouble();
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.LIST == invoiceItemsField.getType()) {
List < DocumentField > invoiceItems = invoiceItemsField.getValueAsList();
invoiceItems.stream()
.filter(invoiceItem -> DocumentFieldType.MAP == invoiceItem.getType())
.map(documentField -> documentField.getValueAsMap())
.forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {
// See a full list of fields found on an invoice here:
// https://aka.ms/formrecognizer/invoicefields
if ("Description".equals(key)) {
if (DocumentFieldType.STRING == documentField.getType()) {
String name = documentField.getValueAsString();
System.out.printf("Description: %s, confidence: %.2fs%n",
name, documentField.getConfidence());
}
}
if ("Quantity".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double quantity = documentField.getValueAsDouble();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, documentField.getConfidence());
}
}
if ("UnitPrice".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double unitPrice = documentField.getValueAsDouble();
System.out.printf("Unit Price: %f, confidence: %.2f%n",
unitPrice, documentField.getConfidence());
}
}
if ("ProductCode".equals(key)) {
if (DocumentFieldType.DOUBLE == documentField.getType()) {
Double productCode = documentField.getValueAsDouble();
System.out.printf("Product Code: %f, confidence: %.2f%n",
productCode, documentField.getConfidence());
}
}
}));
}
}
}
}
}
Создание и запуск приложения
После добавления примера кода в приложение вернитесь к основному каталогу проекта — doc-intel-app.
Выполните сборку приложения с помощью команды build
:
gradle build
Запустите приложение с помощью команды run
:
gradle run