Quickstart: SDK v3.0-clientbibliotheek voor Python | Voorbeeld
Notitie
Form Recognizer v3.0 is momenteel beschikbaar als openbare preview. Sommige functies worden mogelijk niet ondersteund of hebben beperkte mogelijkheden.
Referentiedocumentatie | Broncode bibliotheek | Package (PyPi) | Voorbeelden
Aan de slag met Azure Form Recognizer de programmeertaal Python. Azure Form Recognizer is een cloudgebaseerde, door Azure toegepaste AI-service die gebruikmaakt van machine learning voor het extraheren en analyseren van formuliervelden, tekst en tabellen uit uw documenten. U kunt eenvoudig een Form Recognizer aanroepen door onze clientbibliotheek-SDK's te integreren in uw werkstromen en toepassingen. U wordt aangeraden de gratis service te gebruiken wanneer u de technologie leert. Houd er rekening mee dat het aantal gratis pagina's beperkt is tot 500 per maand.
Ga naar onze overzichtspagina Form Recognizer meer informatie over de functies en ontwikkelingsopties.
In deze snelstart gebruikt u de volgende functies om gegevens en waarden uit formulieren en documenten te analyseren en te extraheren:
🆕 algemeen document:tekst, tabellen, structuur, sleutel-waardeparen en benoemde entiteiten analyseren en extraheren.
Indeling:tabellen, lijnen, woorden en selectiemarkeringen zoals keuzerondjes en selectievakjes in formulierendocumenten analyseren en extraheren, zonder dat u een model hoeft te trainen.
Vooraf gebouwde factuur Algemene velden van facturen analyseren en extraheren met behulp van een vooraf getraind factuurmodel.
Vereisten
Azure-abonnement: Krijg een gratis abonnement
-
- Uw Python-installatie moet pip bevatten. U kunt controleren of pip is geïnstalleerd door uit te voeren
pip --versionop de opdrachtregel. Haal pip op door de nieuwste versie van Python te installeren.
- Uw Python-installatie moet pip bevatten. U kunt controleren of pip is geïnstalleerd door uit te voeren
Een Cognitive Services of Form Recognizer resource. Zodra u uw Azure-abonnement hebt, maakt u een resource voor één service Form Recognizer voor meerdere Azure Portal om uw sleutel en eindpunt op te halen. U kunt de gratis prijscategorie (
F0) gebruiken om de service uit te proberen, en later upgraden naar een betaalde laag voor productie.
Tip
Maak een Cognitive Services als u van plan bent toegang te krijgen tot meerdere cognitieve services onder één eindpunt/sleutel. Als Form Recognizer alleen toegang hebt, maakt u een Form Recognizer resource. Houd er rekening mee dat u een resource met één service nodig hebt als u van plan bent om Azure Active Directory gebruiken.
Nadat uw resource is geïmplementeerd, selecteert u Ga naar resource. U hebt de sleutel en het eindpunt nodig van de resource die u maakt om uw toepassing te verbinden met Form Recognizer API. U plakt uw sleutel en eindpunt later in de quickstart in de onderstaande code:
Instellen
Open een terminalvenster in uw lokale omgeving en installeer de Azure Form Recognizer-clientbibliotheek voor Python met pip:
pip install azure-ai-formrecognizer --pre
Een nieuwe Python-toepassing maken
Maak een nieuwe Python-toepassing met de naam form_recognizer_quickstart.py in uw favoriete editor of IDE. Importeer vervolgens de volgende bibliotheken:
import os
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
Variabelen maken voor het eindpunt en de sleutel van uw Azure-resource
endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY"
Op dit moment moet uw Python-toepassing de volgende regels code bevatten:
import os
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY"
Selecteer een codevoorbeeld dat u in uw toepassing wilt kopiëren en plakken:
Belangrijk
Vergeet niet de sleutel uit uw code te verwijderen wanneer u klaar bent, en plaats deze sleutel nooit in het openbaar. Gebruik voor productie veilige methoden om uw referenties op te slaan en te openen. Zie het artikel Cognitive Services Beveiliging voor meer informatie.
Probeer het: Algemeen documentmodel
- Voor dit voorbeeld hebt u een formulierdocumentbestand op een URI nodig. U kunt ons voorbeeldformulierdocument gebruiken voor deze snelstart.
- Als u een bepaald bestand op een URI wilt analyseren, gebruikt u de methode
begin_analyze_documenten gebruikt u deprebuilt-documentmodel-id. De geretourneerde waarde is eenresultobject met gegevens over het ingediende document. - We hebben de bestands-URI-waarde toegevoegd aan de
formUrlvariabele bovenaan het bestand. - Om het eenvoudig te houden, worden alle entiteitsvelden die de service retourneert, hier niet weergegeven. Zie onze pagina Algemeen documentconcept voor een overzicht van alle ondersteunde velden en bijbehorende typen.
Voeg de volgende code toe aan uw algemene documenttoepassing op de regel onder de key variabele
def format_bounding_region(bounding_regions):
if not bounding_regions:
return "N/A"
return ", ".join("Page #{}: {}".format(region.page_number, format_bounding_box(region.bounding_box)) for region in bounding_regions)
def format_bounding_box(bounding_box):
if not bounding_box:
return "N/A"
return ", ".join(["[{}, {}]".format(p.x, p.y) for p in bounding_box])
def analyze_general_documents():
formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-document", formUrl)
result = poller.result()
for style in result.styles:
if style.is_handwritten:
print("Document contains handwritten content: ")
print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans]))
print("----Key-value pairs found in document----")
for kv_pair in result.key_value_pairs:
if kv_pair.key:
print(
"Key '{}' found within '{}' bounding regions".format(
kv_pair.key.content,
format_bounding_region(kv_pair.key.bounding_regions),
)
)
if kv_pair.value:
print(
"Value '{}' found within '{}' bounding regions\n".format(
kv_pair.value.content,
format_bounding_region(kv_pair.value.bounding_regions),
)
)
print("----Entities found in document----")
for entity in result.entities:
print("Entity of category '{}' with sub-category '{}'".format(entity.category, entity.sub_category))
print("...has content '{}'".format(entity.content))
print("...within '{}' bounding regions".format(format_bounding_region(entity.bounding_regions)))
print("...with confidence {}\n".format(entity.confidence))
for page in result.pages:
print("----Analyzing document from page #{}----".format(page.page_number))
print(
"Page has width: {} and height: {}, measured with unit: {}".format(
page.width, page.height, page.unit
)
)
for line_idx, line in enumerate(page.lines):
print(
"...Line # {} has text content '{}' within bounding box '{}'".format(
line_idx,
line.content,
format_bounding_box(line.bounding_box),
)
)
for word in page.words:
print(
"...Word '{}' has a confidence of {}".format(
word.content, word.confidence
)
)
for selection_mark in page.selection_marks:
print(
"...Selection mark is '{}' within bounding box '{}' and has a confidence of {}".format(
selection_mark.state,
format_bounding_box(selection_mark.bounding_box),
selection_mark.confidence,
)
)
for table_idx, table in enumerate(result.tables):
print(
"Table # {} has {} rows and {} columns".format(
table_idx, table.row_count, table.column_count
)
)
for region in table.bounding_regions:
print(
"Table # {} location on page: {} is {}".format(
table_idx,
region.page_number,
format_bounding_box(region.bounding_box),
)
)
for cell in table.cells:
print(
"...Cell[{}][{}] has content '{}'".format(
cell.row_index,
cell.column_index,
cell.content,
)
)
for region in cell.bounding_regions:
print(
"...content on page {} is within bounding box '{}'\n".format(
region.page_number,
format_bounding_box(region.bounding_box),
)
)
print("----------------------------------------")
if __name__ == "__main__":
analyze_general_documents()
Probeer het: Indelingsmodel
- Voor dit voorbeeld hebt u een formulierdocumentbestand op een URI nodig. U kunt ons voorbeeldformulierdocument gebruiken voor deze snelstart.
- We hebben de bestands-URI-waarde toegevoegd aan de
formUrlvariabele bovenaan het bestand. - Als u een bepaald bestand op een URI wilt analyseren, gebruikt u de methode
begin_analyze_documenten gebruikt u deprebuilt-layoutmodel-id. De geretourneerde waarde is eenresultobject met gegevens over het ingediende document.
Voeg de volgende code toe aan uw indelingstoepassing op de regel onder de key variabele
def format_bounding_box(bounding_box):
if not bounding_box:
return "N/A"
return ", ".join(["[{}, {}]".format(p.x, p.y) for p in bounding_box])
def analyze_layout():
# sample form document
formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-layout", formUrl)
result = poller.result()
for idx, style in enumerate(result.styles):
print(
"Document contains {} content".format(
"handwritten" if style.is_handwritten else "no handwritten"
)
)
Uitproberen: vooraf gebouwd model
In dit voorbeeld wordt gedemonstreerd hoe u gegevens van bepaalde algemene documenttypen kunt analyseren met een vooraf getraind model, met behulp van een factuur als voorbeeld.
- In dit voorbeeld analyseren we een factuurdocument met behulp van een vooraf gebouwd model. U kunt ons voorbeelddocument met facturen gebruiken voor deze quickstart.
- We hebben de bestands-URI-waarde toegevoegd aan de
string fileUrivariabele bovenaan het bestand. - Als u een bepaald bestand op een URI wilt analyseren, gebruikt u de methode
begin_analyze_documenten gebruikt u deprebuilt-invoicemodel-id. De geretourneerde waarde is eenresultobject met gegevens over het ingediende document. - Om het eenvoudig te houden, worden alle sleutel-waardeparen die de service retourneert, hier niet weergegeven. Zie onze pagina Factuurconcept voor een overzicht van alle ondersteunde velden en bijbehorende typen.
De vooraf gebouwde model-id voor facturen kiezen
U bent niet beperkt tot facturen: er zijn verschillende vooraf gebouwde modellen waaruit u kunt kiezen, die elk een eigen set ondersteunde velden hebben. Het model dat voor de analysebewerking moet worden gebruikt, is afhankelijk van het type document dat moet worden geanalyseerd. Dit zijn de model-ID's voor de vooraf gebouwde modellen die momenteel worden ondersteund door de Form Recognizer service:
- vooraf gebouwde factuur:extraheert tekst, selectiemarkeringen, tabellen, sleutel-waardeparen en sleutelgegevens van facturen.
- vooraf gemaakt ontvangstbewijs:extraheert tekst- en sleutelgegevens uit ontvangstbewijzen.
- prebuilt-idDocument:extraheert tekst- en sleutelgegevens uit stuurprogrammalicenties en internationale passports.
- vooraf gebouwde businessCard:extraheert tekst- en sleutelgegevens uit visitekaartjes.
Voeg de volgende code toe aan uw vooraf gebouwde factuurtoepassing onder de key variabele
def format_bounding_region(bounding_regions):
if not bounding_regions:
return "N/A"
return ", ".join("Page #{}: {}".format(region.page_number, format_bounding_box(region.bounding_box)) for region in bounding_regions)
def format_bounding_box(bounding_box):
if not bounding_box:
return "N/A"
return ", ".join(["[{}, {}]".format(p.x, p.y) for p in bounding_box])
def analyze_invoice():
formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"
document_analysis_client = DocumentAnalysisClient(
endpoint=endpoint, credential=AzureKeyCredential(key)
)
poller = document_analysis_client.begin_analyze_document_from_url(
"prebuilt-invoice", formUrl)
invoices = poller.result()
for idx, invoice in enumerate(invoices.documents):
print("--------Recognizing invoice #{}--------".format(idx + 1))
vendor_name = invoice.fields.get("VendorName")
if vendor_name:
print(
"Vendor Name: {} has confidence: {}".format(
vendor_name.value, vendor_name.confidence
)
)
vendor_address = invoice.fields.get("VendorAddress")
if vendor_address:
print(
"Vendor Address: {} has confidence: {}".format(
vendor_address.value, vendor_address.confidence
)
)
vendor_address_recipient = invoice.fields.get("VendorAddressRecipient")
if vendor_address_recipient:
print(
"Vendor Address Recipient: {} has confidence: {}".format(
vendor_address_recipient.value, vendor_address_recipient.confidence
)
)
customer_name = invoice.fields.get("CustomerName")
if customer_name:
print(
"Customer Name: {} has confidence: {}".format(
customer_name.value, customer_name.confidence
)
)
customer_id = invoice.fields.get("CustomerId")
if customer_id:
print(
"Customer Id: {} has confidence: {}".format(
customer_id.value, customer_id.confidence
)
)
customer_address = invoice.fields.get("CustomerAddress")
if customer_address:
print(
"Customer Address: {} has confidence: {}".format(
customer_address.value, customer_address.confidence
)
)
customer_address_recipient = invoice.fields.get("CustomerAddressRecipient")
if customer_address_recipient:
print(
"Customer Address Recipient: {} has confidence: {}".format(
customer_address_recipient.value,
customer_address_recipient.confidence,
)
)
invoice_id = invoice.fields.get("InvoiceId")
if invoice_id:
print(
"Invoice Id: {} has confidence: {}".format(
invoice_id.value, invoice_id.confidence
)
)
invoice_date = invoice.fields.get("InvoiceDate")
if invoice_date:
print(
"Invoice Date: {} has confidence: {}".format(
invoice_date.value, invoice_date.confidence
)
)
invoice_total = invoice.fields.get("InvoiceTotal")
if invoice_total:
print(
"Invoice Total: {} has confidence: {}".format(
invoice_total.value, invoice_total.confidence
)
)
due_date = invoice.fields.get("DueDate")
if due_date:
print(
"Due Date: {} has confidence: {}".format(
due_date.value, due_date.confidence
)
)
purchase_order = invoice.fields.get("PurchaseOrder")
if purchase_order:
print(
"Purchase Order: {} has confidence: {}".format(
purchase_order.value, purchase_order.confidence
)
)
billing_address = invoice.fields.get("BillingAddress")
if billing_address:
print(
"Billing Address: {} has confidence: {}".format(
billing_address.value, billing_address.confidence
)
)
billing_address_recipient = invoice.fields.get("BillingAddressRecipient")
if billing_address_recipient:
print(
"Billing Address Recipient: {} has confidence: {}".format(
billing_address_recipient.value,
billing_address_recipient.confidence,
)
)
shipping_address = invoice.fields.get("ShippingAddress")
if shipping_address:
print(
"Shipping Address: {} has confidence: {}".format(
shipping_address.value, shipping_address.confidence
)
)
shipping_address_recipient = invoice.fields.get("ShippingAddressRecipient")
if shipping_address_recipient:
print(
"Shipping Address Recipient: {} has confidence: {}".format(
shipping_address_recipient.value,
shipping_address_recipient.confidence,
)
)
print("Invoice items:")
for idx, item in enumerate(invoice.fields.get("Items").value):
print("...Item #{}".format(idx + 1))
item_description = item.value.get("Description")
if item_description:
print(
"......Description: {} has confidence: {}".format(
item_description.value, item_description.confidence
)
)
item_quantity = item.value.get("Quantity")
if item_quantity:
print(
"......Quantity: {} has confidence: {}".format(
item_quantity.value, item_quantity.confidence
)
)
unit = item.value.get("Unit")
if unit:
print(
"......Unit: {} has confidence: {}".format(
unit.value, unit.confidence
)
)
unit_price = item.value.get("UnitPrice")
if unit_price:
print(
"......Unit Price: {} has confidence: {}".format(
unit_price.value, unit_price.confidence
)
)
product_code = item.value.get("ProductCode")
if product_code:
print(
"......Product Code: {} has confidence: {}".format(
product_code.value, product_code.confidence
)
)
item_date = item.value.get("Date")
if item_date:
print(
"......Date: {} has confidence: {}".format(
item_date.value, item_date.confidence
)
)
tax = item.value.get("Tax")
if tax:
print(
"......Tax: {} has confidence: {}".format(tax.value, tax.confidence)
)
amount = item.value.get("Amount")
if amount:
print(
"......Amount: {} has confidence: {}".format(
amount.value, amount.confidence
)
)
subtotal = invoice.fields.get("SubTotal")
if subtotal:
print(
"Subtotal: {} has confidence: {}".format(
subtotal.value, subtotal.confidence
)
)
total_tax = invoice.fields.get("TotalTax")
if total_tax:
print(
"Total Tax: {} has confidence: {}".format(
total_tax.value, total_tax.confidence
)
)
previous_unpaid_balance = invoice.fields.get("PreviousUnpaidBalance")
if previous_unpaid_balance:
print(
"Previous Unpaid Balance: {} has confidence: {}".format(
previous_unpaid_balance.value, previous_unpaid_balance.confidence
)
)
amount_due = invoice.fields.get("AmountDue")
if amount_due:
print(
"Amount Due: {} has confidence: {}".format(
amount_due.value, amount_due.confidence
)
)
service_start_date = invoice.fields.get("ServiceStartDate")
if service_start_date:
print(
"Service Start Date: {} has confidence: {}".format(
service_start_date.value, service_start_date.confidence
)
)
service_end_date = invoice.fields.get("ServiceEndDate")
if service_end_date:
print(
"Service End Date: {} has confidence: {}".format(
service_end_date.value, service_end_date.confidence
)
)
service_address = invoice.fields.get("ServiceAddress")
if service_address:
print(
"Service Address: {} has confidence: {}".format(
service_address.value, service_address.confidence
)
)
service_address_recipient = invoice.fields.get("ServiceAddressRecipient")
if service_address_recipient:
print(
"Service Address Recipient: {} has confidence: {}".format(
service_address_recipient.value,
service_address_recipient.confidence,
)
)
remittance_address = invoice.fields.get("RemittanceAddress")
if remittance_address:
print(
"Remittance Address: {} has confidence: {}".format(
remittance_address.value, remittance_address.confidence
)
)
remittance_address_recipient = invoice.fields.get("RemittanceAddressRecipient")
if remittance_address_recipient:
print(
"Remittance Address Recipient: {} has confidence: {}".format(
remittance_address_recipient.value,
remittance_address_recipient.confidence,
)
)
if __name__ == "__main__":
analyze_invoice()
Uw toepassing uitvoeren
Navigeer naar de map waar u het form_recognizer_quickstart.py hebt.
Typ de volgende opdracht in uw terminal:
python form_recognizer_quickstart.py
Gefeliciteerd In deze quickstart hebt u de python Form Recognizer-SDK gebruikt om verschillende formulieren op verschillende manieren te analyseren. Bekijk vervolgens de referentiedocumentatie voor meer informatie over Form Recognizer v3.0-API.