Snabbstart: SDK v3.0 för Java-klientbibliotek | Förhandsgranska

Anteckning

Formigenkänning v3.0 finns för närvarande i offentlig förhandsversion. Vissa funktioner kanske inte stöds eller har begränsade funktioner.

Referensdokumentation | Bibliotekskällkod | Paket (Maven) | Prover

Kom igång med Azure Formigenkänning med programmeringsspråket Java. Azure Formigenkänning är en molnbaserad Azure Applied AI-tjänst som använder maskininlärning för att extrahera och analysera formulärfält, text och tabeller från dina dokument. Du kan enkelt anropa Formigenkänning modeller genom att integrera våra klientbiblioteks-SDks i dina arbetsflöden och program. Vi rekommenderar att du använder den kostnadsfria tjänsten när du lär dig tekniken. Kom ihåg att antalet kostnadsfria sidor är begränsat till 500 per månad.

Mer information om Formigenkänning och utvecklingsalternativ finns på översiktssidan.

I den här snabbstarten använder du följande funktioner för att analysera och extrahera data och värden från formulär och dokument:

  • 🆕 dokument – Analyseraoch extrahera text, tabeller, struktur, nyckel/värde-par och namngivna entiteter.

  • Layout– Analysera och extrahera tabeller, linjer, ord och markeringsmarkeringar som alternativknappar och kryssrutor i formulärdokument, utan att du behöver träna en modell.

  • Förbyggd faktura Analysera och extrahera vanliga fält från fakturor med hjälp av en förtränad fakturamodell.

Förutsättningar

  • Azure-prenumeration – Skapa en utan kostnad.
  • A Java Development Kit (JDK), version 8 eller senare
  • En Cognitive Services eller Formigenkänning resurs. När du har din Azure-prenumeration kan du skapa en resurs för Formigenkänning tjänst eller flera tjänster i Azure Portal för att hämta din nyckel och slutpunkt. Du kan använda den kostnadsfria prisnivån ( F0 ) för att prova tjänsten och senare uppgradera till en betald nivå för produktion.

Tips

Skapa en Cognitive Services resurs om du planerar att komma åt flera kognitiva tjänster under en enda slutpunkt/nyckel. För Formigenkänning åtkomst skapar du en Formigenkänning resurs. Observera att du behöver en resurs för en enskild tjänst om du planerar att använda Azure Active Directory autentisering.

  • När resursen har distribuerats klickar du på Gå till resurs. Du behöver nyckeln och slutpunkten från den resurs som du skapar för att ansluta ditt program till Formigenkänning-API:et. Du klistrar in nyckeln och slutpunkten i koden nedan senare i snabbstarten:

    Skärmbild: Nycklar och slutpunktsplats i Azure Portal.

Konfigurera

Skapa ett nytt Gradle-projekt

I ett konsolfönster (till exempel cmd, PowerShell eller Bash) skapar du en ny katalog för din app med namnet form-recognizer-app och navigerar till den.

mkdir form-recognizer-app && form-recognizer-app

Kör gradle init kommandot från arbetskatalogen. Det här kommandot skapar viktiga byggfiler för Gradle, inklusive build.gradle.kts, som används vid körning för att skapa och konfigurera ditt program.

gradle init --type basic
  1. Välj en DSL när du uppmanas till det och välj Kotlin.

  2. Acceptera standardprojektets namn (form-recognizer-app)

Installera klientbiblioteket

I den här snabbstarten används Gradle-beroendehanteraren. Du hittar klientbiblioteket och information för andra beroendehanterare på den centrala Maven-lagringsplatsen.

I projektets build.gradle.kts-fil inkluderar du klientbiblioteket som en instruktion, tillsammans med nödvändiga implementation plugin-program och inställningar.

plugins {
    java
    application
}
application {
    mainClass.set("FormRecognizer")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.azure", name = "azure-ai-formrecognizer", version = "4.0.0-beta.1")
}

Skapa en Java-fil

Kör följande kommando från arbetskatalogen:

mkdir -p src/main/java

Du skapar följande katalogstruktur:

Skärmbild: Java-katalogstruktur

Navigera till den nya mappen och skapa en fil med namnet FormRecognizer.java (som skapades under gradle init kommandot ). Öppna den i önskat redigeringsprogram eller IDE och lägg till följande paketdeklaration och import -instruktioner:

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;

Välj ett kodexempel som du vill kopiera och klistra in i programmets huvudmetod:

Viktigt

Kom ihåg att ta bort nyckeln från koden när du är klar och aldrig publicera den offentligt. För produktion använder du säkra metoder för att lagra och komma åt dina autentiseringsuppgifter. Se artikeln Cognitive Services säkerhet för mer information.

Prova: Allmän dokumentmodell

  • I det här exemplet behöver du en formulärdokumentfil på en URI. Du kan använda vårt exempelformulärdokument för den här snabbstarten.
  • Om du vill analysera en viss fil på en URI använder du metoden beginAnalyzeDocumentFromUrl och skickar prebuilt-document som modell-ID. Det returnerade värdet är ett AnalyzeResult objekt som innehåller data om det skickade dokumentet.
  • Vi har lagt till filens URI-värde i documentUrl variabeln i main-metoden.
  • För enkelhetens skull visas inte alla entitetsfält som tjänsten returnerar här. En lista över alla fält som stöds och motsvarande typer finns på sidan allmänt dokumentkoncept.

Uppdatera programmets FormRecognizer-klass med följande kod (se till att uppdatera nyckel- och slutpunktsvariablerna med värden från Formigenkänning-instansen i 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()));
            }
        });
    }

Prova: Layoutmodell

Extrahera text, markeringsmarkeringar, textformat och tabellstrukturer, tillsammans med deras koordinater för avgränsade regioner från dokument.

  • I det här exemplet behöver du en formulärdokumentfil på en URI. Du kan använda vårt exempelformulärdokument för den här snabbstarten.
  • Om du vill analysera en viss fil på en URI använder du metoden beginAnalyzeDocumentFromUrl och skickar prebuilt-layout som modell-ID. Det returnerade värdet är ett AnalyzeResult objekt som innehåller data om det skickade dokumentet.
  • Vi har lagt till filens URI-värde i documentUrl variabeln i main-metoden.

Uppdatera programmets FormRecognizer-klass med följande kod (se till att uppdatera nyckel- och slutpunktsvariablerna med värden från Formigenkänning-instansen i 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();
        }
    }

Prova: Förbyggd modell

Det här exemplet visar hur du analyserar data från vissa typer av vanliga dokument med förtränade modeller, med hjälp av en faktura som exempel.

  • I det här exemplet analyserar vi ett fakturadokument med hjälp av en förbyggd modell. Du kan använda vårt exempelfakturadokument för den här snabbstarten.
  • Om du vill analysera en viss fil på en URI använder du metoden beginAnalyzeDocumentFromUrl och skickar prebuilt-invoice som modell-ID. Det returnerade värdet är ett AnalyzeResult objekt som innehåller data om det skickade dokumentet.
  • Vi har lagt till filens URI-värde i invoiceUrl variabeln i main-metoden.
  • För enkelhetens skull visas inte alla nyckel/värde-par som tjänsten returnerar här. En lista över alla fält som stöds och motsvarande typer finns på vår sida fakturakoncept.

Välj det fördefinierade modell-ID:t för fakturan

Du är inte begränsad till fakturor – det finns flera fördefinierade modeller att välja mellan, där var och en har en egen uppsättning fält som stöds. Vilken modell som ska användas för analysåtgärden beror på vilken typ av dokument som ska analyseras. Här är modell-ID:erna för de fördefinierade modeller som stöds av Formigenkänning tjänsten:

  • prebuilt-invoice:extraherar text, markeringsmarkeringar, tabeller, nyckel/värde-par och nyckelinformation från fakturor.
  • prebuilt-receipt:extraherar text- och nyckelinformation från kvitton.
  • prebuilt-idDocument:extraherar text- och nyckelinformation från drivrutinslicenser och internationella pass.
  • prebuilt-businessCard:extraherar text och viktig information från visitkort.

Uppdatera programmets FormRecognizer-klass med följande kod (se till att uppdatera nyckel- och slutpunktsvariablerna med värden från Formigenkänning-instansen i 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());
                                    }
                                }
                            }));
                    }
                }
            }
        });
    }
}

Skapa och köra ditt program

Gå tillbaka till huvudprojektkatalogen,form-recognizer-app.

  1. Skapa ditt program med build kommandot :
gradle build
  1. Kör programmet med run kommandot :
gradle run

Grattis! I den här snabbstarten använde du Formigenkänning Java SDK för att analysera olika formulär och dokument på olika sätt. Utforska sedan referensdokumentationen för att lära dig Formigenkänning API på djupet.

Nästa steg