Hızlı başlangıç: Python istemci kitaplığı SDK v 3.0 | Önizleme
Not
Form tanıyıcı v 3.0 şu anda genel önizleme aşamasındadır. Bazı özellikler desteklenmeyebilir veya sınırlı özelliklere sahip olabilir.
Başvuru belgeleri | Kitaplık kaynak kodu | Paket (Pypı) | Örnekler
Python programlama dilini kullanarak Azure form tanıyıcısı 'nı kullanmaya başlayın. Azure form tanıyıcı, belgelerinizdeki form alanlarını, metinleri ve tabloları ayıklamak ve analiz etmek için makine öğrenimi kullanan bulut tabanlı bir Azure uygulanmış AI hizmetidir. İstemci kitaplığı SDK 'larımızı iş akışlarınızla ve uygulamalarınızla tümleştirerek, form tanıyıcı modellerini kolayca çağırabilirsiniz. Teknolojiyi öğrenirken ücretsiz hizmeti kullanmanızı öneririz. Ücretsiz sayfa sayısının ayda 500 ile sınırlı olduğunu unutmayın.
Form tanıyıcı özellikleri ve geliştirme seçenekleri hakkında daha fazla bilgi edinmek için genel bakış sayfamızı ziyaret edin.
Bu hızlı başlangıçta, formlardan ve belgelerden veri ve değerleri çözümlemek ve ayıklamak için aşağıdaki özellikleri kullanacaksınız:
🆕 Genel belge— metni, tabloları, yapıyı, anahtar-değer çiftlerini ve adlandırılmış varlıkları çözümleyin ve ayıklayın.
Düzen: bir modeli eğitmenize gerek kalmadan, form belgelerindeki tablo, çizgi, sözcük ve seçim işaretlerini analiz edin ve ayıklayın.
Önceden oluşturulmuş fatura Önceden eğitilen bir fatura modeli kullanarak faturalardan ortak alanları çözümleyin ve ayıklayın.
Önkoşullar
Azure aboneliği- ücretsiz olarak bir tane oluşturun
-
- Python yüklemeniz PIP'yi içermelidir. Komut satırında komutunu çalıştırarak PIP 'nin yüklenip yüklenmediğini kontrol edebilirsiniz
pip --version. Python 'un en son sürümünü yükleyerek PIP 'yi alın.
- Python yüklemeniz PIP'yi içermelidir. Komut satırında komutunu çalıştırarak PIP 'nin yüklenip yüklenmediğini kontrol edebilirsiniz
Bilişsel hizmetler veya form tanıyıcı kaynağı. Azure aboneliğiniz olduktan sonra, anahtarınızı ve uç noktanızı almak için Azure portal bir tek hizmet veya çok hizmet bir tanıyıcı kaynağı oluşturun.
F0Hizmeti denemek ve daha sonra üretime yönelik ücretli bir katmana yükseltmek için ücretsiz fiyatlandırma katmanını () kullanabilirsiniz.
İpucu
Tek bir uç nokta/anahtar altında birden fazla bilişsel hizmete erişmeyi planlıyorsanız bilişsel hizmetler kaynağı oluşturun. Yalnızca form tanıyıcı erişimi için form tanıyıcı kaynağı oluşturun. Azure Active Directory kimlik doğrulamasıkullanmak istiyorsanız lütfen you'lll tek hizmet kaynağı gerekeceğini unutmayın.
Kaynağınız dağıtıldıktan sonra Kaynağa Git' i seçin. Uygulamanızı form tanıyıcı API 'sine bağlamak için oluşturduğunuz kaynaktaki anahtar ve uç noktanın olması gerekir. Anahtarınızı ve uç noktanızı sonraki hızlı başlangıçta aşağıdaki koda yapıştırmanız gerekir:
Kurulum
Yerel ortamınızda bir Terminal penceresi açın ve PIP ile Python için Azure form tanıyıcı istemci kitaplığı 'nı yüklemelisiniz:
pip install azure-ai-formrecognizer --pre
Yeni Python uygulaması oluşturma
Tercih ettiğiniz düzenleyicide veya IDE 'de form_recognizer_quickstart. Kopyala adlı yeni bir Python uygulaması oluşturun. Ardından aşağıdaki kitaplıkları içeri aktarın:
import os
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
Azure Kaynak uç noktanız ve anahtarınız için değişkenler oluşturma
endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_SUBSCRIPTION_KEY"
Bu noktada, Python uygulamanız aşağıdaki kod satırlarını içermelidir:
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"
Uygulamanıza kopyalayıp yapıştırmak için bir kod örneği seçin:
Önemli
İşiniz bittiğinde kodu koddan kaldırmayı unutmayın ve hiçbir zaman herkese açık bir şekilde nakletmeyin. Üretim için, kimlik bilgilerinizi depolamak ve erişmek üzere güvenli yöntemler kullanın. Daha fazla bilgi için bilişsel Hizmetler güvenlik makalesine bakın.
Deneyin: Genel belge modeli
- Bu örnekte, BIR URI 'de form belge dosyası gerekir. Bu hızlı başlangıç için örnek form belgemizi kullanabilirsiniz.
- Bir URI 'deki belirli bir dosyayı analiz etmek için
begin_analyze_documentyöntemini kullanacaksınız veprebuilt-documentmodel kimliği olarak geçireceğiz. Döndürülen değer,resultgönderilen belge hakkında veri içeren bir nesnedir. - Dosya URI değerini
formUrldosyanın en üstüne yakın olan değişkene ekledik. - Kolaylık olması için, hizmetin döndürdüğü tüm varlık alanları burada gösterilmez. Desteklenen tüm alanların ve karşılık gelen türlerin listesini görmek için bkz. Genel belge kavram sayfamız.
Aşağıdaki kodu, değişkenin altındaki satırda bulunan genel belge uygulamanıza ekleyin key
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()
Deneyin: düzen modeli
- Bu örnekte, BIR URI 'de form belge dosyası gerekir. Bu hızlı başlangıç için örnek form belgemizi kullanabilirsiniz.
- Dosya URI değerini
formUrldosyanın en üstüne yakın olan değişkene ekledik. - Bir URI 'deki belirli bir dosyayı analiz etmek için
begin_analyze_documentyöntemini kullanacaksınız veprebuilt-layoutmodel kimliği olarak geçireceğiz. Döndürülen değer,resultgönderilen belge hakkında veri içeren bir nesnedir.
Aşağıdaki kodu, değişkenin altındaki satırda bulunan düzen uygulamanıza ekleyin key
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"
)
)
Deneyin: önceden oluşturulmuş model
Bu örnek, örnek olarak bir fatura kullanarak, belirli ortak belge türlerindeki verilerin önceden eğitilen bir modelle nasıl çözümlendiğini gösterir.
- Bu örnekte, önceden oluşturulmuş bir model kullanarak bir fatura belgesini bir belge olarak analiz ediyoruz. Bu hızlı başlangıç için örnek fatura belgemizi kullanabilirsiniz.
- Dosyanın üst kısmındaki değişkene dosya URI değeri ekledik
string fileUri. - Bir URI 'deki belirli bir dosyayı analiz etmek için
begin_analyze_documentyöntemini kullanacaksınız veprebuilt-invoicemodel kimliği olarak geçireceğiz. Döndürülen değer,resultgönderilen belge hakkında veri içeren bir nesnedir. - Kolaylık olması için, hizmetin döndürdüğü tüm anahtar-değer çiftleri burada gösterilmez. Desteklenen tüm alanların ve ilgili türlerin listesini görmek için, bkz. Fatura kavram sayfamız.
Fatura önceden oluşturulmuş model KIMLIĞINI seçin
Faturanız sınırlandırmadınız — her birinin, kendi desteklenen alanları kümesine sahip arasından seçim yapabileceğiniz birkaç önceden oluşturulmuş model vardır. Çözümle işlemi için kullanılacak model çözümlenecek belge türüne bağlıdır. Form tanıyıcı hizmeti tarafından şu anda desteklenen önceden oluşturulmuş modellerin model kimlikleri şunlardır:
- önceden oluşturulan-fatura: metin, seçim işaretleri, tablolar, anahtar-değer çiftleri ve faturalardan anahtar bilgilerini ayıklar.
- önceden oluşturulmuş alındı: alındılardan metin ve anahtar bilgilerini ayıklar.
- önceden oluşturulmuş-ıddocument: sürücü lisanlarından ve uluslararası Passport 'tan metin ve anahtar bilgilerini ayıklar.
- önceden oluşturulmuş-businessCard: iş kartlarından metin ve anahtar bilgilerini ayıklar.
Aşağıdaki kodu, önceden oluşturulmuş fatura uygulamanıza değişkenin altına ekleyin key
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()
Uygulamanızı çalıştırma
Form_recognizer_quickstart. Kopyala dosyanızın bulunduğu klasöre gidin.
Terminalinize aşağıdaki komutu yazın:
python form_recognizer_quickstart.py
Tebrikler! Bu hızlı başlangıçta çeşitli formları farklı yollarla analiz etmek için tanıyıcı Python SDK formunu kullandınız. Daha sonra, form tanıyıcı v 3.0 API 'SI hakkında daha fazla bilgi edinmek için başvuru belgelerini inceleyin.