Rychlý start: Sada SDK klientské knihovny pro Javu verze 3.0 | Náhled
Poznámka
Rozpoznávání formulářů verze 3.0 je aktuálně ve verzi Public Preview. Některé funkce nemusí být podporované nebo mají omezené možnosti.
Referenční dokumentace | Zdrojový kód knihovny | Balíček (Maven) | Vzorky
Začínáme s Azure Rozpoznávání formulářů s využitím programovacího jazyka Java. Azure Rozpoznávání formulářů je cloudová služba Azure Applied AI Service, která pomocí strojového učení extrahuje a analyzuje pole formuláře, text a tabulky z vašich dokumentů. Můžete snadno volat Rozpoznávání formulářů integrací našich klientských knihoven SDK do vašich pracovních postupů a aplikací. Doporučujeme používat bezplatnou službu, když se s technologií učíte. Nezapomeňte, že počet bezplatných stránek je omezený na 500 za měsíc.
Další informace o funkcích Rozpoznávání formulářů a možnostech vývoje najdete na naší stránce Přehled.
V tomto rychlém startu použijete následující funkce k analýze a extrahování dat a hodnot z formulářů a dokumentů:
🆕 obecný dokument– analýza a extrahování textu, tabulek, struktury, párů klíč-hodnota a pojmenovaných entit
Rozložení– analyzujte a extrahujte tabulky, řádky, slova a značky výběru, jako jsou přepínače a zaškrtávací políčka ve formulářích dokumentů, aniž byste trénovali model.
Předem sestavená faktura Analyzujte a extrahujte běžná pole z faktur pomocí předem natrénovaných modelů faktur.
Požadavky
- Předplatné Azure – Vytvořte si ho zdarma.
- Sada Java Development Kit (JDK)verze 8 nebo novější
- Prostředek Cognitive Services nebo Rozpoznávání formulářů. Jakmile máte předplatné Azure, vytvořte prostředek služby s jednou nebo více Rozpoznávání formulářů ve službě Azure Portal a získejte svůj klíč a koncový bod. K vyzkoušejí služby můžete použít bezplatnou cenovou úroveň ( ) a později upgradovat
F0na placenou úroveň pro produkční prostředí.
Tip
Pokud plánujete Cognitive Services více kognitivních služeb v rámci jednoho koncového bodu nebo klíče, vytvořte nový prostředek. Pro Rozpoznávání formulářů přístup vytvořte prostředek Rozpoznávání formulářů. Upozorňujeme, že pokud chcete použít ověřování pomocí služby , budete potřebovat Azure Active Directory službu.
Po nasazení prostředku klikněte na Přejít k prostředku. Klíč a koncový bod z prostředku, který vytvoříte, potřebujete pro připojení aplikace k rozhraní ROZPOZNÁVÁNÍ FORMULÁŘŮ API. Klíč a koncový bod vložíte do kódu níže v pozdější části tohoto rychlého startu:
Nastavení
Vytvoření nového projektu Gradle
V okně konzoly (například cmd, PowerShell nebo Bash) vytvořte pro svou aplikaci nový adresář s názvem form-recognizer-app a přejděte do něj.
mkdir form-recognizer-app && form-recognizer-app
Z gradle init pracovního adresáře spusťte příkaz . Tento příkaz vytvoří základní soubory sestavení pro Gradle, včetně build.gradle.kts, který se používá za běhu k vytvoření a konfiguraci aplikace.
gradle init --type basic
Po zobrazení výzvy k výběru DSL vyberte Kotlin.
Přijměte výchozí název projektu (form-recognizer-app).
Instalace klientské knihovny
V tomto rychlém startu se používá správce závislostí Gradle. Klientskou knihovnu a informace o dalších správcích závislostí najdete v centrálním úložišti Maven.
Do souboru build.gradle.kts projektu zahrnovat klientskou knihovnu jako příkaz spolu s požadovanými moduly plug-in a implementation nastavením.
plugins {
java
application
}
application {
mainClass.set("FormRecognizer")
}
repositories {
mavenCentral()
}
dependencies {
implementation(group = "com.azure", name = "azure-ai-formrecognizer", version = "4.0.0-beta.1")
}
Vytvoření souboru Java
Z pracovního adresáře spusťte následující příkaz:
mkdir -p src/main/java
Vytvoříte následující adresářovou strukturu:
Přejděte do nové složky a vytvořte soubor s názvem FormRecognizer.java (vytvořený během gradle init příkazu ). Otevřete ho v upřednostňovaném editoru nebo integrovaném vývojovém prostředí (IDE) a přidejte následující deklarace a import příkazy balíčku:
package com.azure.ai.formrecognizer;
import com.azure.ai.formrecognizer.models.AnalyzeDocumentOptions;
import com.azure.ai.formrecognizer.models.AnalyzedDocument;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.util.Context;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.Arrays;
Vyberte vzorový kód, který chcete zkopírovat a vložit do hlavní metody vaší aplikace:
Důležité
Až budete hotovi, nezapomeňte klíč z kódu odebrat a nikdy ho veřejně ne zveřejníte. V produkčním prostředí použijte zabezpečené metody pro ukládání přihlašovacích údajů a přístup k přihlašovacím údajům. Další informace najdete Cognitive Services zabezpečení sítě.
Vyzkoušet: Obecný model dokumentu
- V tomto příkladu budete potřebovat soubor dokumentu formuláře s identifikátorem URI. Pro tento rychlý start můžete použít náš ukázkový dokument formuláře.
- K analýze daného souboru s identifikátorem URI použijete metodu a jako
beginAnalyzeDocumentFromUrlID modelu předáteprebuilt-document. Vrácená hodnota je objektAnalyzeResultobsahující data o odeslaném dokumentu. - Do proměnné v metodě main jsme přidali hodnotu
documentUrlidentifikátoru URI souboru. - Pro zjednodušení se zde nezobrazí všechna pole entity, která služba vrací. Seznam všech podporovaných polí a odpovídajících typů najdete na naší stránce Koncepty obecného dokumentu.
Aktualizujte třídu FormRecognizer vaší aplikace následujícím kódem (klíč a proměnné koncového bodu aktualizujte hodnotami z vaší instance Rozpoznávání formulářů v Azure Portal):
public class FormRecognizer {
static final String key = "PASTE_YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY_HERE";
static final String endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";
public static void main(String[] args) {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
String modelId = "prebuilt-document";
SyncPoller < DocumentOperationResult, AnalyzeResult > analyzeDocumentPoller =
documentAnalysisClient.beginAnalyzeDocumentFromUrl(modelId, documentUrl);
AnalyzeResult analyzeResult = analyzeDocumentPoller.getFinalResult();
for (int i = 0; i < analyzeResult.getDocuments().size(); i++) {
final AnalyzedDocument analyzedDocument = analyzeResult.getDocuments().get(i);
System.out.printf("----------- Analyzing document %d -----------%n", i);
System.out.printf("Analyzed document has doc type %s with confidence : %.2f%n",
analyzedDocument.getDocType(), analyzedDocument.getConfidence());
}
analyzeResult.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 box %s.%n",
documentLine.getContent(),
documentLine.getBoundingBox().toString()));
// words
documentPage.getWords().forEach(documentWord - >
System.out.printf("Word %s has a confidence score of %.2f%n.",
documentWord.getContent(),
documentWord.getConfidence()));
});
// tables
List < DocumentTable > tables = analyzeResult.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();
}
// Entities
analyzeResult.getEntities().forEach(documentEntity - > {
System.out.printf("Entity category : %s, sub-category %s%n: ",
documentEntity.getCategory(), documentEntity.getSubCategory());
System.out.printf("Entity content: %s%n: ", documentEntity.getContent());
System.out.printf("Entity confidence: %.2f%n", documentEntity.getConfidence());
});
// Key-value
analyzeResult.getKeyValuePairs().forEach(documentKeyValuePair - > {
System.out.printf("Key content: %s%n", documentKeyValuePair.getKey().getContent());
System.out.printf("Key content bounding region: %s%n",
documentKeyValuePair.getKey().getBoundingRegions().toString());
System.out.printf("Value content: %s%n", documentKeyValuePair.getValue().getContent());
System.out.printf("Value content bounding region: %s%n", documentKeyValuePair.getValue().getBoundingRegions().toString());
});
Build a custom document analysis model
In 3. x.x, creating a custom model required specifying useTrainingLabels to indicate whether to use labeled data when creating the custom model with the beginTraining method.
In 4. x.x, we introduced the new general document model(prebuilt - document) to replace the train without labels functionality from 3. x.x which extracts entities, key - value pairs, and layout from a document with the beginBuildModel method.In 4. x.x the beginBuildModel always returns labeled data otherwise.
Train a custom model using 3. x.x beginTraining:
String trainingFilesUrl = "{SAS_URL_of_your_container_in_blob_storage}";
SyncPoller < FormRecognizerOperationResult, CustomFormModel > trainingPoller =
formTrainingClient.beginTraining(trainingFilesUrl,
false,
new TrainingOptions()
.setModelName("my model trained without labels"),
Context.NONE);
CustomFormModel customFormModel = trainingPoller.getFinalResult();
// Model Info
System.out.printf("Model Id: %s%n", customFormModel.getModelId());
System.out.printf("Model name given by user: %s%n", customFormModel.getModelName());
System.out.printf("Model Status: %s%n", customFormModel.getModelStatus());
System.out.printf("Training started on: %s%n", customFormModel.getTrainingStartedOn());
System.out.printf("Training completed on: %s%n%n", customFormModel.getTrainingCompletedOn());
System.out.println("Recognized Fields:");
// looping through the subModels, which contains the fields they were trained on
// Since the given training documents are unlabeled we still group them but, they do not have a label.
customFormModel.getSubmodels().forEach(customFormSubmodel - > {
System.out.printf("Submodel Id: %s%n: ", customFormSubmodel.getModelId());
// Since the training data is unlabeled, we are unable to return the accuracy of this model
customFormSubmodel.getFields().forEach((field, customFormModelField) - >
System.out.printf("Field: %s Field Label: %s%n",
field, customFormModelField.getLabel()));
});
System.out.println();
customFormModel.getTrainingDocuments().forEach(trainingDocumentInfo - > {
System.out.printf("Document name: %s%n", trainingDocumentInfo.getName());
System.out.printf("Document status: %s%n", trainingDocumentInfo.getStatus());
System.out.printf("Document page count: %d%n", trainingDocumentInfo.getPageCount());
if (!trainingDocumentInfo.getErrors().isEmpty()) {
System.out.println("Document Errors:");
trainingDocumentInfo.getErrors().forEach(formRecognizerError - >
System.out.printf("Error code %s, Error message: %s%n", formRecognizerError.getErrorCode(),
formRecognizerError.getMessage()));
}
});
}
Vyzkoušet: Model rozložení
Extrahujte text, značky výběru, styly textu a struktury tabulek spolu s jejich souřadnicemi ohraničující oblasti z dokumentů.
- V tomto příkladu budete potřebovat soubor dokumentu formuláře s identifikátorem URI. Pro tento rychlý start můžete použít náš ukázkový dokument formuláře.
- K analýze daného souboru s identifikátorem URI použijete metodu a jako
beginAnalyzeDocumentFromUrlID modelu předáteprebuilt-layout. Vrácená hodnota je objektAnalyzeResultobsahující data o odeslaném dokumentu. - Do proměnné v metodě main jsme přidali hodnotu
documentUrlidentifikátoru URI souboru.
Aktualizujte třídu FormRecognizer vaší aplikace následujícím kódem (klíč a proměnné koncového bodu aktualizujte hodnotami z vaší instance Rozpoznávání formulářů v Azure Portal):
public class FormRecognizer {
static final String key = "PASTE_YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY_HERE";
static final String endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";
public static void main(String[] args) {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
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 < DocumentOperationResult, AnalyzeResult > analyzeLayoutResultPoller =
documentAnalysisClient.beginAnalyzeDocument(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 box %s.%n",
documentLine.getContent(),
documentLine.getBoundingBox().toString()));
// selection marks
documentPage.getSelectionMarks().forEach(documentSelectionMark - >
System.out.printf("Selection mark is %s and is within a bounding box %s with confidence %.2f.%n",
documentSelectionMark.getState().toString(),
documentSelectionMark.getBoundingBox().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();
}
}
Vyzkoušet: Předem připravený model
Tato ukázka ukazuje, jak analyzovat data z určitých typů běžných dokumentů s předem natrénovaných modely, například pomocí faktury.
- V tomto příkladu analyzujeme dokument faktury pomocí předem sestavených modelů. Pro tento rychlý start můžete použít náš ukázkový dokument faktury.
- K analýze daného souboru s identifikátorem URI použijete metodu a jako
beginAnalyzeDocumentFromUrlID modelu předáteprebuilt-invoice. Vrácená hodnota je objektAnalyzeResultobsahující data o odeslaném dokumentu. - Do proměnné v metodě main jsme přidali hodnotu
invoiceUrlidentifikátoru URI souboru. - Pro zjednodušení se tady nezobrazí všechny páry klíč-hodnota, které služba vrací. Pokud chcete zobrazit seznam všech podporovaných polí a odpovídajících typů, podívejte se na naši stránku konceptu faktury.
Volba ID modelu předem sestavené faktury
Nejste omezeni na faktury – existuje několik předem připravených modelů, ze kterých si můžete vybrat, z nichž každý má vlastní sadu podporovaných polí. Model, který se má použít pro operaci analýzy, závisí na typu dokumentu, který se má analyzovat. Tady jsou ID modelů pro předem sestavené modely, které aktuálně podporuje Rozpoznávání formulářů služby:
- prebuilt-invoice: Extrahuje text, značky výběru, tabulky, páry klíč-hodnota a klíčové informace z faktur.
- prebuilt-receipt: Extrahuje z účtenek textové a klíčové informace.
- prebuilt-idDocument:Extrahuje textové a klíčové informace z řidičský průkazů a mezinárodních pasů.
- prebuilt-businessCard:Extrahuje textové a klíčové informace z vizitek.
Aktualizujte třídu FormRecognizer vaší aplikace následujícím kódem (klíč a proměnné koncového bodu aktualizujte hodnotami z vaší instance Rozpoznávání formulářů v Azure Portal):
public class FormRecognizer {
static final String key = "PASTE_YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY_HERE";
static final String endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";
public static void main(String[] args) {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"
String modelId = "prebuilt-invoice";
PollerFlux < DocumentOperationResult, AnalyzeResult > analyzeInvoicePoller = client.beginAnalyzeDocumentFromUrl("prebuilt-invoice", invoiceUrl);
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()));
}
});
analyzeInvoiceResultMono.subscribe(analyzeInvoiceResult - > {
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.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.FLOAT == invoiceTotalField.getType()) {
Float invoiceTotal = invoiceTotalField.getValueFloat();
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.getValueList();
invoiceItems.stream()
.filter(invoiceItem - > DocumentFieldType.MAP == invoiceItem.getType())
.map(formField - > formField.getValueMap())
.forEach(formFieldMap - > formFieldMap.forEach((key, formField) - > {
// See a full list of fields found on an invoice here:
// https://aka.ms/formrecognizer/invoicefields
if ("Description".equals(key)) {
if (DocumentFieldType.STRING == formField.getType()) {
String name = formField.getValueString();
System.out.printf("Description: %s, confidence: %.2fs%n",
name, formField.getConfidence());
}
}
if ("Quantity".equals(key)) {
if (DocumentFieldType.FLOAT == formField.getType()) {
Float quantity = formField.getValueFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
if ("UnitPrice".equals(key)) {
if (DocumentFieldType.FLOAT == formField.getType()) {
Float unitPrice = formField.getValueFloat();
System.out.printf("Unit Price: %f, confidence: %.2f%n",
unitPrice, formField.getConfidence());
}
}
if ("ProductCode".equals(key)) {
if (DocumentFieldType.FLOAT == formField.getType()) {
Float productCode = formField.getValueFloat();
System.out.printf("Product Code: %f, confidence: %.2f%n",
productCode, formField.getConfidence());
}
}
}));
}
}
}
});
}
}
Sestavení a spuštění aplikace
Vraťte se do hlavního adresáře projektu – form-recognizer-app.
- Sestavte aplikaci pomocí
buildpříkazu :
gradle build
- Spusťte aplikaci pomocí
runpříkazu :
gradle run
Gratulujeme! V tomto rychlém startu jste použili Rozpoznávání formulářů Java SDK k analýze různých formulářů a dokumentů různými způsoby. Dále si projděte referenční dokumentaci, ve které najdete podrobnější Rozpoznávání formulářů o rozhraní API.