Rychlý Start: sada SDK pro klientské knihovny Pythonu v 3.0 | Tisk
Poznámka
Nástroj pro rozpoznávání formulářů v 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 (PyPi) | Ukázky
Začínáme s nástrojem pro rozpoznávání formulářů Azure pomocí programovacího jazyka Python Nástroj pro rozpoznávání formulářů Azure je cloudová služba používaná v Azure, která využívá Machine Learning k extrakci a analýze polí formuláře, textu a tabulek z vašich dokumentů. Můžete snadno volat modely pro rozpoznávání formulářů integrací sad SDK klientské knihovny do vašich pracovních postupů a aplikací. Při učení technologie doporučujeme používat bezplatnou službu. Mějte na paměti, že počet bezplatných stránek je omezený na 500 za měsíc.
Další informace o funkcích nástroje pro rozpoznávání formulářů a možnostech vývoje najdete na naší stránce s přehledem .
V tomto rychlém startu použijete následující funkce k analýze a extrakci dat a hodnot z formulářů a dokumentů:
🆕 Obecný dokument– Analyzujte a extrahujte text, tabulky, strukturu, páry klíč-hodnota a pojmenované entity.
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ů bez nutnosti vytvořit výuku modelu.
Předem vytvořená faktura Analyzujte a extrahujte společná pole z faktur pomocí předem připraveného modelu faktury.
Požadavky
Předplatné Azure – Vytvořte si ho zdarma .
-
- Instalace Pythonu by měla zahrnovat PIP. Pomocí příkazu na příkazovém řádku můžete zjistit, jestli máte službu PIP nainstalovanou
pip --version. Získejte PIP instalací nejnovější verze Pythonu.
- Instalace Pythonu by měla zahrnovat PIP. Pomocí příkazu na příkazovém řádku můžete zjistit, jestli máte službu PIP nainstalovanou
Prostředek pro rozpoznávání Cognitive Services nebo formuláře. Jakmile budete mít předplatné Azure, vytvořte v Azure Portal prostředek pro rozpoznávání formulářů s jednou službou nebo více službami , abyste získali svůj klíč a koncový bod. K vyzkoušení služby můžete použít bezplatnou cenovou úroveň (
F0) a upgradovat ji později na placenou úroveň pro produkční prostředí.
Tip
Pokud máte v plánu přístup k více službám pro rozpoznávání v rámci jednoho koncového bodu nebo klíče, vytvořte prostředek Cognitive Services. Pro rozpoznávání formulářů jenom přístup, vytvořte prostředek pro rozpoznávání formulářů. upozorňujeme, že you'lll potřebuje prostředek jedné služby, pokud chcete Azure Active Directory ověřovánípoužít.
Po nasazení prostředků vyberte Přejít k prostředku. K připojení aplikace k rozhraní API pro rozpoznávání formulářů budete potřebovat klíč a koncový bod z prostředku, který vytvoříte. Svůj klíč a koncový bod do kódu níže vložíte později v rychlém startu:
Nastavení
Otevřete okno terminálu v místním prostředí a nainstalujte klientskou knihovnu pro rozpoznávání formulářů Azure pro Python s PIP:
pip install azure-ai-formrecognizer --pre
Vytvoření nové aplikace v Pythonu
Vytvořte novou aplikaci v Pythonu s názvem form_recognizer_quickstart. py v upřednostňovaném editoru nebo integrovaném vývojovém prostředí. Pak importujte následující knihovny:
import os
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
Vytvoření proměnných pro svůj koncový bod a klíč prostředku Azure
endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY"
V tomto okamžiku by vaše aplikace Python měla obsahovat následující řádky kódu:
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"
Vyberte ukázku kódu pro zkopírování a vložení do aplikace:
Důležité
Nezapomeňte odebrat klíč z kódu, až budete hotovi, a nikdy ho zveřejnit. V produkčním prostředí používejte zabezpečené metody pro ukládání a přístup k přihlašovacím údajům. Další informace najdete v článku o zabezpečení Cognitive Services.
Zkuste: 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 .
- Chcete-li analyzovat daný soubor v identifikátoru URI, použijte
begin_analyze_documentmetodu a předejteprebuilt-documentji jako ID modelu. Vrácená hodnota jeresultobjekt, který obsahuje data o odeslaném dokumentu. - Do proměnné poblíž horní části souboru jsme přidali hodnotu identifikátoru URI souboru
formUrl. - Pro jednoduchost se tady nezobrazí všechna pole entit, která služba vrací. Seznam všech podporovaných polí a odpovídajících typů zobrazíte na naší stránce Obecné koncept dokumentu .
Přidejte následující kód do vaší obecné aplikace dokumentu na řádku pod key proměnnou
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()
Zkuste: model rozložení
- 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 .
- Do proměnné poblíž horní části souboru jsme přidali hodnotu identifikátoru URI souboru
formUrl. - Chcete-li analyzovat daný soubor v identifikátoru URI, použijte
begin_analyze_documentmetodu a předejteprebuilt-layoutji jako ID modelu. Vrácená hodnota jeresultobjekt, který obsahuje data o odeslaném dokumentu.
Přidejte následující kód do aplikace rozložení na řádku pod key proměnnou
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"
)
)
Vyzkoušet: předem sestavený model
Tato ukázka demonstruje, jak analyzovat data z určitých běžných typů dokumentů s předučeným modelem, jako například pomocí faktury.
- V tomto příkladu jsme pomocí předem připraveného modelu analyzovali dokument faktury. Pro tento rychlý Start můžete použít náš ukázkový dokument faktury .
- Do proměnné v horní části souboru jsme přidali hodnotu identifikátoru URI souboru
string fileUri. - Chcete-li analyzovat daný soubor v identifikátoru URI, použijte
begin_analyze_documentmetodu a předejteprebuilt-invoiceji jako ID modelu. Vrácená hodnota jeresultobjekt, který obsahuje data o odeslaném dokumentu. - Pro jednoduchost se tady nezobrazují všechny páry klíč-hodnota, které služba vrací. Seznam všech podporovaných polí a odpovídajících typů zobrazíte na stránce koncept faktury .
Zvolit předem sestavené ID modelu faktury
Nejste omezeni na faktury – existuje několik předem sestavených modelů, z nichž každý má vlastní sadu podporovaných polí. Model, který se má použít pro operaci analyzovat, závisí na typu dokumentu, který se má analyzovat. Tady jsou ID modelů pro předem připravené modely, které aktuálně podporuje služba pro rozpoznávání formulářů:
- předem vytvořená faktura: extrahuje text, značky výběru, tabulky, páry klíč-hodnota a informace o klíči z faktur.
- předem vytvořená příjem: extrahuje text a klíčové informace z účtenek.
- předem sestavené – idDocument: extrahuje text a klíčové informace z licencí ovladačů a mezinárodních cestovních pasů.
- předem sestavené – businessCard: extrahuje text a klíčové informace z vizitek.
Přidejte následující kód do vaší předem připravené aplikace faktury pod key proměnnou
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()
Spusťte aplikaci
Přejděte do složky, kde máte soubor form_recognizer_quickstart. py .
Do terminálu zadejte následující příkaz:
python form_recognizer_quickstart.py
Gratulujeme! V tomto rychlém startu jste použili sadu SDK pro rozpoznávání formulářů Pythonu k analýze různých forem různými způsoby. Dále si Prozkoumejte referenční dokumentaci, kde najdete další informace o rozhraní API pro rozpoznávání formulářů v 3.0.