diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_business_cards_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_business_cards_async.py index c0a3a421c5aa..25e973581fc9 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_business_cards_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_business_cards_async.py @@ -55,103 +55,69 @@ async def analyze_business_card_async(): business_cards = await poller.result() for idx, business_card in enumerate(business_cards.documents): - print("--------Analyzing business card #{}--------".format(idx + 1)) + print(f"--------Analyzing business card #{idx + 1}--------") contact_names = business_card.fields.get("ContactNames") if contact_names: for contact_name in contact_names.value: print( - "Contact First Name: {} has confidence: {}".format( - contact_name.value["FirstName"].value, - contact_name.value[ - "FirstName" - ].confidence, - ) + f"Contact First Name: {contact_name.value['FirstName'].value} " + f"has confidence: {contact_name.value['FirstName'].confidence}" ) print( - "Contact Last Name: {} has confidence: {}".format( - contact_name.value["LastName"].value, - contact_name.value[ - "LastName" - ].confidence, - ) + f"Contact Last Name: {contact_name.value['LastName'].value} has" + f" confidence: {contact_name.value['LastName'].confidence}" ) company_names = business_card.fields.get("CompanyNames") if company_names: for company_name in company_names.value: print( - "Company Name: {} has confidence: {}".format( - company_name.value, company_name.confidence - ) + f"Company Name: {company_name.value} has confidence: {company_name.confidence}" ) departments = business_card.fields.get("Departments") if departments: for department in departments.value: print( - "Department: {} has confidence: {}".format( - department.value, department.confidence - ) + f"Department: {department.value} has confidence: {department.confidence}" ) job_titles = business_card.fields.get("JobTitles") if job_titles: for job_title in job_titles.value: print( - "Job Title: {} has confidence: {}".format( - job_title.value, job_title.confidence - ) + f"Job Title: {job_title.value} has confidence: {job_title.confidence}" ) emails = business_card.fields.get("Emails") if emails: for email in emails.value: - print( - "Email: {} has confidence: {}".format(email.value, email.confidence) - ) + print(f"Email: {email.value} has confidence: {email.confidence}") websites = business_card.fields.get("Websites") if websites: for website in websites.value: - print( - "Website: {} has confidence: {}".format( - website.value, website.confidence - ) - ) + print(f"Website: {website.value} has confidence: {website.confidence}") addresses = business_card.fields.get("Addresses") if addresses: for address in addresses.value: - print( - "Address: {} has confidence: {}".format( - address.value, address.confidence - ) - ) + print(f"Address: {address.value} has confidence: {address.confidence}") mobile_phones = business_card.fields.get("MobilePhones") if mobile_phones: for phone in mobile_phones.value: print( - "Mobile phone number: {} has confidence: {}".format( - phone.content, phone.confidence - ) + f"Mobile phone number: {phone.content} has confidence: {phone.confidence}" ) faxes = business_card.fields.get("Faxes") if faxes: for fax in faxes.value: - print( - "Fax number: {} has confidence: {}".format( - fax.content, fax.confidence - ) - ) + print(f"Fax number: {fax.content} has confidence: {fax.confidence}") work_phones = business_card.fields.get("WorkPhones") if work_phones: for work_phone in work_phones.value: print( - "Work phone number: {} has confidence: {}".format( - work_phone.content, work_phone.confidence - ) + f"Work phone number: {work_phone.content} has confidence: {work_phone.confidence}" ) other_phones = business_card.fields.get("OtherPhones") if other_phones: for other_phone in other_phones.value: print( - "Other phone number: {} has confidence: {}".format( - other_phone.value, other_phone.confidence - ) + f"Other phone number: {other_phone.value} has confidence: {other_phone.confidence}" ) @@ -162,11 +128,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_custom_documents_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_custom_documents_async.py index 10e5c4f8f317..896d3caa2fb7 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_custom_documents_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_custom_documents_async.py @@ -65,43 +65,37 @@ async def analyze_custom_documents_async(custom_model_id): result = await poller.result() for idx, document in enumerate(result.documents): - print("--------Analyzing document #{}--------".format(idx + 1)) - print("Document has type {}".format(document.doc_type)) - print("Document has document type confidence {}".format(document.confidence)) - print("Document was analyzed with model with ID {}".format(result.model_id)) + print(f"--------Analyzing document #{idx + 1}--------") + print(f"Document has type {document.doc_type}") + print(f"Document has document type confidence {document.confidence}") + print(f"Document was analyzed with model with ID {result.model_id}") for name, field in document.fields.items(): field_value = field.value if field.value else field.content - print("......found field of type '{}' with value '{}' and with confidence {}".format(field.value_type, field_value, field.confidence)) + print( + f"......found field of type '{field.value_type}' with value '{field_value}' and with confidence {field.confidence}" + ) # iterate over tables, lines, and selection marks on each page for page in result.pages: - print("\nLines found on page {}".format(page.page_number)) + print(f"\nLines found on page {page.page_number}") for line in page.lines: - print("...Line '{}'".format(line.content)) + print(f"...Line '{line.content}'") for word in page.words: - print( - "...Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) - ) + print(f"...Word '{word.content}' has a confidence of {word.confidence}") if page.selection_marks: - print("\nSelection marks found on page {}".format(page.page_number)) + print(f"\nSelection marks found on page {page.page_number}") for selection_mark in page.selection_marks: print( - "...Selection mark is '{}' and has a confidence of {}".format( - selection_mark.state, selection_mark.confidence - ) + f"...Selection mark is '{selection_mark.state}' and has a confidence of {selection_mark.confidence}" ) for i, table in enumerate(result.tables): - print("\nTable {} can be found on page:".format(i + 1)) + print(f"\nTable {i + 1} can be found on page:") for region in table.bounding_regions: - print("...{}".format(region.page_number)) + print(f"...{region.page_number}") for cell in table.cells: print( - "...Cell[{}][{}] has text '{}'".format( - cell.row_index, cell.column_index, cell.content - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) print("-----------------------------------") # [END analyze_custom_documents_async] @@ -110,7 +104,6 @@ async def analyze_custom_documents_async(custom_model_id): async def main(): model_id = None if os.getenv("CONTAINER_SAS_URL") and not os.getenv("CUSTOM_BUILT_MODEL_ID"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient from azure.ai.formrecognizer import ModelBuildMode @@ -139,11 +132,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_general_documents_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_general_documents_async.py index 21408761972d..8dad47793938 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_general_documents_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_general_documents_async.py @@ -24,15 +24,20 @@ import os import asyncio + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) async def analyze_general_documents(): @@ -66,7 +71,14 @@ async def analyze_general_documents(): 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( + ",".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: @@ -74,82 +86,55 @@ async def analyze_general_documents(): print(f"Common name for key value pair: {kv_pair.common_name}") if kv_pair.key: print( - "Key '{}' found within '{}' bounding regions".format( - kv_pair.key.content, - format_bounding_region(kv_pair.key.bounding_regions), - ) - ) + f"Key '{kv_pair.key.content}' found within " + f"'{format_bounding_region(kv_pair.key.bounding_regions)}' 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), - ) - ) + f"Value '{kv_pair.value.content}' found within " + f"'{format_bounding_region(kv_pair.value.bounding_regions)}' bounding regions\n" + ) for page in result.pages: - print("----Analyzing document from page #{}----".format(page.page_number)) + print(f"----Analyzing document from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has {} words and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line #{line_idx} has {len(words)} words and text '{line.content}' within " + f"bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of " + f"{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 - ) + f"Table # {table_idx} has {table.row_count} rows and {table.column_count} columns" ) for region in table.bounding_regions: print( - "Table # {} location on page: {} is {}".format( - table_idx, - region.page_number, - format_polygon(region.polygon), - ) + f"Table # {table_idx} location on page: {region.page_number} is {format_polygon(region.polygon)}" ) for cell in table.cells: print( - "...Cell[{}][{}] has text '{}'".format( - cell.row_index, - cell.column_index, - cell.content, - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) for region in cell.bounding_regions: print( - "...content on page {} is within bounding polygon '{}'\n".format( - region.page_number, - format_polygon(region.polygon), - ) + f"...content on page {region.page_number} is within bounding polygon '{format_polygon(region.polygon)}'\n" ) print("----------------------------------------") @@ -157,14 +142,18 @@ async def analyze_general_documents(): async def main(): await analyze_general_documents() + if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_identity_documents_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_identity_documents_async.py index b6f5f4d077ac..02a10eb1d41f 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_identity_documents_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_identity_documents_async.py @@ -55,62 +55,42 @@ async def analyze_identity_documents_async(): id_documents = await poller.result() for idx, id_document in enumerate(id_documents.documents): - print("--------Analyzing ID document #{}--------".format(idx + 1)) + print(f"--------Analyzing ID document #{idx + 1}--------") first_name = id_document.fields.get("FirstName") if first_name: print( - "First Name: {} has confidence: {}".format( - first_name.value, first_name.confidence - ) + f"First Name: {first_name.value} has confidence: {first_name.confidence}" ) last_name = id_document.fields.get("LastName") if last_name: print( - "Last Name: {} has confidence: {}".format( - last_name.value, last_name.confidence - ) + f"Last Name: {last_name.value} has confidence: {last_name.confidence}" ) document_number = id_document.fields.get("DocumentNumber") if document_number: print( - "Document Number: {} has confidence: {}".format( - document_number.value, document_number.confidence - ) + f"Document Number: {document_number.value} has confidence: {document_number.confidence}" ) dob = id_document.fields.get("DateOfBirth") if dob: - print( - "Date of Birth: {} has confidence: {}".format(dob.value, dob.confidence) - ) + print(f"Date of Birth: {dob.value} has confidence: {dob.confidence}") doe = id_document.fields.get("DateOfExpiration") if doe: - print( - "Date of Expiration: {} has confidence: {}".format( - doe.value, doe.confidence - ) - ) + print(f"Date of Expiration: {doe.value} has confidence: {doe.confidence}") sex = id_document.fields.get("Sex") if sex: - print("Sex: {} has confidence: {}".format(sex.value, sex.confidence)) + print(f"Sex: {sex.value} has confidence: {sex.confidence}") address = id_document.fields.get("Address") if address: - print( - "Address: {} has confidence: {}".format( - address.value, address.confidence - ) - ) + print(f"Address: {address.value} has confidence: {address.confidence}") country_region = id_document.fields.get("CountryRegion") if country_region: print( - "Country/Region: {} has confidence: {}".format( - country_region.value, country_region.confidence - ) + f"Country/Region: {country_region.value} has confidence: {country_region.confidence}" ) region = id_document.fields.get("Region") if region: - print( - "Region: {} has confidence: {}".format(region.value, region.confidence) - ) + print(f"Region: {region.value} has confidence: {region.confidence}") async def main(): @@ -120,11 +100,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_invoices_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_invoices_async.py index 99b5875d2fec..e166bb030dd7 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_invoices_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_invoices_async.py @@ -56,252 +56,172 @@ async def analyze_invoice_async(): invoices = await poller.result() for idx, invoice in enumerate(invoices.documents): - print("--------Analyzing invoice #{}--------".format(idx + 1)) + print(f"--------Analyzing invoice #{idx + 1}--------") vendor_name = invoice.fields.get("VendorName") if vendor_name: print( - "Vendor Name: {} has confidence: {}".format( - vendor_name.value, vendor_name.confidence - ) + f"Vendor Name: {vendor_name.value} has confidence: {vendor_name.confidence}" ) vendor_address = invoice.fields.get("VendorAddress") if vendor_address: print( - "Vendor Address: {} has confidence: {}".format( - vendor_address.value, vendor_address.confidence - ) + f"Vendor Address: {vendor_address.value} has confidence: {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, - ) + f"Vendor Address Recipient: {vendor_address_recipient.value} has confidence: {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 - ) + f"Customer Name: {customer_name.value} has confidence: {customer_name.confidence}" ) customer_id = invoice.fields.get("CustomerId") if customer_id: print( - "Customer Id: {} has confidence: {}".format( - customer_id.value, customer_id.confidence - ) + f"Customer Id: {customer_id.value} has confidence: {customer_id.confidence}" ) customer_address = invoice.fields.get("CustomerAddress") if customer_address: print( - "Customer Address: {} has confidence: {}".format( - customer_address.value, customer_address.confidence - ) + f"Customer Address: {customer_address.value} has confidence: {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, - ) + f"Customer Address Recipient: {customer_address_recipient.value} has confidence: {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 - ) + f"Invoice Id: {invoice_id.value} has confidence: {invoice_id.confidence}" ) invoice_date = invoice.fields.get("InvoiceDate") if invoice_date: print( - "Invoice Date: {} has confidence: {}".format( - invoice_date.value, invoice_date.confidence - ) + f"Invoice Date: {invoice_date.value} has confidence: {invoice_date.confidence}" ) invoice_total = invoice.fields.get("InvoiceTotal") if invoice_total: print( - "Invoice Total: {} has confidence: {}".format( - invoice_total.value, invoice_total.confidence - ) + f"Invoice Total: {invoice_total.value} has confidence: {invoice_total.confidence}" ) due_date = invoice.fields.get("DueDate") if due_date: - print( - "Due Date: {} has confidence: {}".format( - due_date.value, due_date.confidence - ) - ) + print(f"Due Date: {due_date.value} has confidence: {due_date.confidence}") purchase_order = invoice.fields.get("PurchaseOrder") if purchase_order: print( - "Purchase Order: {} has confidence: {}".format( - purchase_order.value, purchase_order.confidence - ) + f"Purchase Order: {purchase_order.value} has confidence: {purchase_order.confidence}" ) billing_address = invoice.fields.get("BillingAddress") if billing_address: print( - "Billing Address: {} has confidence: {}".format( - billing_address.value, billing_address.confidence - ) + f"Billing Address: {billing_address.value} has confidence: {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, - ) + f"Billing Address Recipient: {billing_address_recipient.value} has confidence: {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 - ) + f"Shipping Address: {shipping_address.value} has confidence: {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, - ) + f"Shipping Address Recipient: {shipping_address_recipient.value} has confidence: {shipping_address_recipient.confidence}" ) print("Invoice items:") for idx, item in enumerate(invoice.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Description: {item_description.value} has confidence: {item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Quantity: {item_quantity.value} has confidence: {item_quantity.confidence}" ) unit = item.value.get("Unit") if unit: - print( - "......Unit: {} has confidence: {}".format( - unit.value, unit.confidence - ) - ) + print(f"......Unit: {unit.value} has confidence: {unit.confidence}") unit_price = item.value.get("UnitPrice") if unit_price: + unit_price_code = unit_price.value.code if unit_price.value.code else "" print( - "......Unit Price: {}{} has confidence: {}".format( - unit_price.value, unit_price.value.code if unit_price.value.code else "", unit_price.confidence - ) + f"......Unit Price: {unit_price.value}{unit_price_code} has confidence: {unit_price.confidence}" ) product_code = item.value.get("ProductCode") if product_code: print( - "......Product Code: {} has confidence: {}".format( - product_code.value, product_code.confidence - ) + f"......Product Code: {product_code.value} has confidence: {product_code.confidence}" ) item_date = item.value.get("Date") if item_date: print( - "......Date: {} has confidence: {}".format( - item_date.value, item_date.confidence - ) + f"......Date: {item_date.value} has confidence: {item_date.confidence}" ) tax = item.value.get("Tax") if tax: - print( - "......Tax: {} has confidence: {}".format(tax.value, tax.confidence) - ) + print(f"......Tax: {tax.value} has confidence: {tax.confidence}") amount = item.value.get("Amount") if amount: print( - "......Amount: {} has confidence: {}".format( - amount.value, amount.confidence - ) + f"......Amount: {amount.value} has confidence: {amount.confidence}" ) subtotal = invoice.fields.get("SubTotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") total_tax = invoice.fields.get("TotalTax") if total_tax: print( - "Total Tax: {} has confidence: {}".format( - total_tax.value, total_tax.confidence - ) + f"Total Tax: {total_tax.value} has confidence: {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, - ) + f"Previous Unpaid Balance: {previous_unpaid_balance.value} has confidence: {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 - ) + f"Amount Due: {amount_due.value} has confidence: {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 - ) + f"Service Start Date: {service_start_date.value} has confidence: {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 - ) + f"Service End Date: {service_end_date.value} has confidence: {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 - ) + f"Service Address: {service_address.value} has confidence: {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, - ) + f"Service Address Recipient: {service_address_recipient.value} has confidence: {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 - ) + f"Remittance Address: {remittance_address.value} has confidence: {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, - ) + f"Remittance Address Recipient: {remittance_address_recipient.value} has confidence: {remittance_address_recipient.confidence}" ) # [END analyze_invoices_async] @@ -313,11 +233,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_layout_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_layout_async.py index aebf44d398db..3291fb4728bd 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_layout_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_layout_async.py @@ -32,7 +32,7 @@ def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) async def analyze_layout_async(): @@ -62,76 +62,51 @@ async def analyze_layout_async(): ) result = await poller.result() - for idx, style in enumerate(result.styles): + for style in result.styles: print( - "Document contains {} content".format( - "handwritten" if style.is_handwritten else "no handwritten" - ) + f"Document contains {'handwritten' if style.is_handwritten else 'no handwritten'} content" ) - for idx, page in enumerate(result.pages): - print("----Analyzing layout from page #{}----".format(idx + 1)) + for page in result.pages: + print(f"----Analyzing layout from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' " + f"within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of {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 - ) + f"Table # {table_idx} has {table.row_count} rows and " + f"{table.column_count} columns" ) for region in table.bounding_regions: print( - "Table # {} location on page: {} is {}".format( - table_idx, - region.page_number, - format_polygon(region.polygon), - ) + f"Table # {table_idx} location on page: {region.page_number} is {format_polygon(region.polygon)}" ) for cell in table.cells: print( - "...Cell[{}][{}] has text '{}'".format( - cell.row_index, - cell.column_index, - cell.content, - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) for region in cell.bounding_regions: print( - "...content on page {} is within bounding polygon '{}'".format( - region.page_number, - format_polygon(region.polygon), - ) + f"...content on page {region.page_number} is within bounding polygon '{format_polygon(region.polygon)}'" ) print("----------------------------------------") @@ -144,11 +119,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_read_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_read_async.py index 52dabc44051e..ef5b38d10408 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_read_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_read_async.py @@ -24,15 +24,21 @@ import os import asyncio + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) + async def analyze_read(): path_to_sample_documents = os.path.abspath( @@ -55,7 +61,7 @@ async def analyze_read(): document_analysis_client = DocumentAnalysisClient( endpoint=endpoint, credential=AzureKeyCredential(key) ) - + async with document_analysis_client: with open(path_to_sample_documents, "rb") as f: poller = await document_analysis_client.begin_analyze_document( @@ -65,57 +71,65 @@ async def analyze_read(): print("----Languages detected in the document----") for language in result.languages: - print("Language code: '{}' with confidence {}".format(language.locale, language.confidence)) + print( + f"Language code: '{language.locale}' with confidence {language.confidence}" + ) print("----Styles detected in the document----") for style in result.styles: if style.is_handwritten: print("Found the following handwritten content: ") - print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans])) + print( + ",".join( + [ + result.content[span.offset : span.offset + span.length] + for span in style.spans + ] + ) + ) if style.font_style: - print(f"The document contains '{style.font_style}' font style, applied to the following text: ") - print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans])) + print( + f"The document contains '{style.font_style}' font style, applied to the following text: " + ) + print( + ",".join( + [ + result.content[span.offset : span.offset + span.length] + for span in style.spans + ] + ) + ) for page in result.pages: - print("----Analyzing document from page #{}----".format(page.page_number)) + print(f"----Analyzing document from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has {} words and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has {len(words)} words and text '{line.content}' within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"...Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of {selection_mark.confidence}" ) if len(result.paragraphs) > 0: - print("----Detected #{} paragraphs in the document----".format(len(result.paragraphs))) + print(f"----Detected #{len(result.paragraphs)} paragraphs in the document----") for paragraph in result.paragraphs: - print("Found paragraph with role: '{}' within {} bounding region".format(paragraph.role, format_bounding_region(paragraph.bounding_regions))) - print("...with content: '{}'".format(paragraph.content)) + print( + f"Found paragraph with role: '{paragraph.role}' within {format_bounding_region(paragraph.bounding_regions)} bounding region" + ) + print(f"...with content: '{paragraph.content}'") print("----------------------------------------") @@ -123,14 +137,18 @@ async def analyze_read(): async def main(): await analyze_read() + if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_async.py index 8ae758c3ccd6..dd18b79a51db 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_async.py @@ -56,70 +56,60 @@ async def analyze_receipts_async(): receipts = await poller.result() for idx, receipt in enumerate(receipts.documents): - print("--------Analysis of receipt #{}--------".format(idx + 1)) - print("Receipt type: {}".format(receipt.doc_type or "N/A")) + print(f"--------Analysis of receipt #{idx + 1}--------") + print(f"Receipt type: {receipt.doc_type if receipt.doc_type else 'N/A'}") merchant_name = receipt.fields.get("MerchantName") if merchant_name: print( - "Merchant Name: {} has confidence: {}".format( - merchant_name.value, merchant_name.confidence - ) + f"Merchant Name: {merchant_name.value} has confidence: " + f"{merchant_name.confidence}" ) transaction_date = receipt.fields.get("TransactionDate") if transaction_date: print( - "Transaction Date: {} has confidence: {}".format( - transaction_date.value, transaction_date.confidence - ) + f"Transaction Date: {transaction_date.value} has confidence: " + f"{transaction_date.confidence}" ) if receipt.fields.get("Items"): print("Receipt items:") for idx, item in enumerate(receipt.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Item Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Item Description: {item_description.value} has confidence: " + f"{item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Item Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Item Quantity: {item_quantity.value} has confidence: " + f"{item_quantity.confidence}" ) item_price = item.value.get("Price") if item_price: print( - "......Individual Item Price: {} has confidence: {}".format( - item_price.value, item_price.confidence - ) + f"......Individual Item Price: {item_price.value} has confidence: " + f"{item_price.confidence}" ) item_total_price = item.value.get("TotalPrice") if item_total_price: print( - "......Total Item Price: {} has confidence: {}".format( - item_total_price.value, item_total_price.confidence - ) + f"......Total Item Price: {item_total_price.value} has confidence: " + f"{item_total_price.confidence}" ) subtotal = receipt.fields.get("Subtotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") tax = receipt.fields.get("TotalTax") if tax: - print("Total tax: {} has confidence: {}".format(tax.value, tax.confidence)) + print(f"Total tax: {tax.value} has confidence: {tax.confidence}") tip = receipt.fields.get("Tip") if tip: - print("Tip: {} has confidence: {}".format(tip.value, tip.confidence)) + print(f"Tip: {tip.value} has confidence: {tip.confidence}") total = receipt.fields.get("Total") if total: - print("Total: {} has confidence: {}".format(total.value, total.confidence)) + print(f"Total: {total.value} has confidence: {total.confidence}") print("--------------------------------------") @@ -130,11 +120,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_from_url_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_from_url_async.py index 657d7e6fe682..fe93cd09df49 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_from_url_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_receipts_from_url_async.py @@ -47,70 +47,60 @@ async def analyze_receipts_from_url_async(): receipts = await poller.result() for idx, receipt in enumerate(receipts.documents): - print("--------Analysis of receipt #{}--------".format(idx + 1)) - print("Receipt type: {}".format(receipt.doc_type or "N/A")) + print(f"--------Analysis of receipt #{idx + 1}--------") + print(f"Receipt type: {receipt.doc_type if receipt.doc_type else 'N/A'}") merchant_name = receipt.fields.get("MerchantName") if merchant_name: print( - "Merchant Name: {} has confidence: {}".format( - merchant_name.value, merchant_name.confidence - ) + f"Merchant Name: {merchant_name.value} has confidence: " + f"{merchant_name.confidence}" ) transaction_date = receipt.fields.get("TransactionDate") if transaction_date: print( - "Transaction Date: {} has confidence: {}".format( - transaction_date.value, transaction_date.confidence - ) + f"Transaction Date: {transaction_date.value} has confidence: " + f"{transaction_date.confidence}" ) if receipt.fields.get("Items"): print("Receipt items:") for idx, item in enumerate(receipt.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Item Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Item Description: {item_description.value} has confidence: " + f"{item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Item Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Item Quantity: {item_quantity.value} has confidence: " + f"{item_quantity.confidence}" ) item_price = item.value.get("Price") if item_price: print( - "......Individual Item Price: {} has confidence: {}".format( - item_price.value, item_price.confidence - ) + f"......Individual Item Price: {item_price.value} has confidence: " + f"{item_price.confidence}" ) item_total_price = item.value.get("TotalPrice") if item_total_price: print( - "......Total Item Price: {} has confidence: {}".format( - item_total_price.value, item_total_price.confidence - ) + f"......Total Item Price: {item_total_price.value} has confidence: " + f"{item_total_price.confidence}" ) subtotal = receipt.fields.get("Subtotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") tax = receipt.fields.get("TotalTax") if tax: - print("Total tax: {} has confidence: {}".format(tax.value, tax.confidence)) + print(f"Total tax: {tax.value} has confidence: {tax.confidence}") tip = receipt.fields.get("Tip") if tip: - print("Tip: {} has confidence: {}".format(tip.value, tip.confidence)) + print(f"Tip: {tip.value} has confidence: {tip.confidence}") total = receipt.fields.get("Total") if total: - print("Total: {} has confidence: {}".format(total.value, total.confidence)) + print(f"Total: {total.value} has confidence: {total.confidence}") print("--------------------------------------") # [END analyze_receipts_from_url_async] @@ -122,11 +112,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_tax_us_w2_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_tax_us_w2_async.py index b65be4e07b2a..c960fa634664 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_tax_us_w2_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_analyze_tax_us_w2_async.py @@ -28,7 +28,8 @@ def format_address_value(address_value): - return f'\n......House/building number: {address_value.house_number}\n......Road: {address_value.road}\n......City: {address_value.city}\n......State: {address_value.state}\n......Postal code: {address_value.postal_code}' + return f"\n......House/building number: {address_value.house_number}\n......Road: {address_value.road}\n......City: {address_value.city}\n......State: {address_value.state}\n......Postal code: {address_value.postal_code}" + async def analyze_tax_us_w2_async(): path_to_sample_documents = os.path.abspath( @@ -58,170 +59,131 @@ async def analyze_tax_us_w2_async(): w2s = await poller.result() for idx, w2 in enumerate(w2s.documents): - print("--------Analyzing US Tax W-2 Form #{}--------".format(idx + 1)) + print(f"--------Analyzing US Tax W-2 Form #{idx + 1}--------") form_variant = w2.fields.get("W2FormVariant") if form_variant: print( - "Form variant: {} has confidence: {}".format( - form_variant.value, form_variant.confidence - ) + f"Form variant: {form_variant.value} has confidence: " + f"{form_variant.confidence}" ) tax_year = w2.fields.get("TaxYear") if tax_year: - print( - "Tax year: {} has confidence: {}".format( - tax_year.value, tax_year.confidence - ) - ) + print(f"Tax year: {tax_year.value} has confidence: {tax_year.confidence}") w2_copy = w2.fields.get("W2Copy") if w2_copy: - print( - "W-2 Copy: {} has confidence: {}".format( - w2_copy.value, - w2_copy.confidence, - ) - ) + print(f"W-2 Copy: {w2_copy.value} has confidence: {w2_copy.confidence}") employee = w2.fields.get("Employee") if employee: print("Employee data:") employee_name = employee.value.get("Name") if employee_name: - print("...Name: {} has confidence: {}".format( - employee_name.value, employee_name.confidence - ) + print( + f"...Name: {employee_name.value} has confidence: {employee_name.confidence}" ) employee_ssn = employee.value.get("SocialSecurityNumber") if employee_ssn: - print("...SSN: {} has confidence: {}".format( - employee_ssn.value, employee_ssn.confidence - ) + print( + f"...SSN: {employee_ssn.value} has confidence: {employee_ssn.confidence}" ) employee_address = employee.value.get("Address") if employee_address: - print("...Address: {}\n......has confidence: {}".format( - format_address_value(employee_address.value), employee_address.confidence - ) - ) + print(f"...Address: {format_address_value(employee_address.value)}") + print(f"......has confidence: {employee_address.confidence}") employee_zipcode = employee.value.get("ZipCode") if employee_zipcode: - print("...Zipcode: {} has confidence: {}".format( - employee_zipcode.value, employee_zipcode.confidence - ) + print( + f"...Zipcode: {employee_zipcode.value} has confidence: " + f"{employee_zipcode.confidence}" ) control_number = w2.fields.get("ControlNumber") if control_number: print( - "Control Number: {} has confidence: {}".format( - control_number.value, control_number.confidence - ) + f"Control Number: {control_number.value} has confidence: " + f"{control_number.confidence}" ) employer = w2.fields.get("Employer") if employer: print("Employer data:") employer_name = employer.value.get("Name") if employer_name: - print("...Name: {} has confidence: {}".format( - employer_name.value, employer_name.confidence - ) + print( + f"...Name: {employer_name.value} has confidence: {employer_name.confidence}" ) employer_id = employer.value.get("IdNumber") if employer_id: - print("...ID Number: {} has confidence: {}".format( - employer_id.value, employer_id.confidence - ) + print( + f"...ID Number: {employer_id.value} has confidence: {employer_id.confidence}" ) employer_address = employer.value.get("Address") if employer_address: - print("...Address: {}\n......has confidence: {}".format( - format_address_value(employer_address.value), employer_address.confidence - ) - ) + print(f"...Address: {format_address_value(employer_address.value)}") + print(f"\n......has confidence: {employer_address.confidence}") employer_zipcode = employer.value.get("ZipCode") if employer_zipcode: - print("...Zipcode: {} has confidence: {}".format( - employer_zipcode.value, employer_zipcode.confidence - ) + print( + f"...Zipcode: {employer_zipcode.value} has confidence: {employer_zipcode.confidence}" ) wages_tips = w2.fields.get("WagesTipsAndOtherCompensation") if wages_tips: print( - "Wages, tips, and other compensation: {} has confidence: {}".format( - wages_tips.value, - wages_tips.confidence, - ) + f"Wages, tips, and other compensation: {wages_tips.value} " + f"has confidence: {wages_tips.confidence}" ) fed_income_tax_withheld = w2.fields.get("FederalIncomeTaxWithheld") if fed_income_tax_withheld: print( - "Federal income tax withheld: {} has confidence: {}".format( - fed_income_tax_withheld.value, fed_income_tax_withheld.confidence - ) + f"Federal income tax withheld: {fed_income_tax_withheld.value} has " + f"confidence: {fed_income_tax_withheld.confidence}" ) social_security_wages = w2.fields.get("SocialSecurityWages") if social_security_wages: print( - "Social Security wages: {} has confidence: {}".format( - social_security_wages.value, social_security_wages.confidence - ) + f"Social Security wages: {social_security_wages.value} has confidence: " + f"{social_security_wages.confidence}" ) social_security_tax_withheld = w2.fields.get("SocialSecurityTaxWithheld") if social_security_tax_withheld: print( - "Social Security tax withheld: {} has confidence: {}".format( - social_security_tax_withheld.value, social_security_tax_withheld.confidence - ) + f"Social Security tax withheld: {social_security_tax_withheld.value} " + f"has confidence: {social_security_tax_withheld.confidence}" ) medicare_wages_tips = w2.fields.get("MedicareWagesAndTips") if medicare_wages_tips: print( - "Medicare wages and tips: {} has confidence: {}".format( - medicare_wages_tips.value, medicare_wages_tips.confidence - ) + f"Medicare wages and tips: {medicare_wages_tips.value} has confidence: " + f"{medicare_wages_tips.confidence}" ) medicare_tax_withheld = w2.fields.get("MedicareTaxWithheld") if medicare_tax_withheld: print( - "Medicare tax withheld: {} has confidence: {}".format( - medicare_tax_withheld.value, medicare_tax_withheld.confidence - ) + f"Medicare tax withheld: {medicare_tax_withheld.value} has confidence: " + f"{medicare_tax_withheld.confidence}" ) social_security_tips = w2.fields.get("SocialSecurityTips") if social_security_tips: print( - "Social Security tips: {} has confidence: {}".format( - social_security_tips.value, social_security_tips.confidence - ) + f"Social Security tips: {social_security_tips.value} has confidence: " + f"{social_security_tips.confidence}" ) allocated_tips = w2.fields.get("AllocatedTips") if allocated_tips: print( - "Allocated tips: {} has confidence: {}".format( - allocated_tips.value, - allocated_tips.confidence, - ) + f"Allocated tips: {allocated_tips.value} has confidence: {allocated_tips.confidence}" ) verification_code = w2.fields.get("VerificationCode") if verification_code: print( - "Verification code: {} has confidence: {}".format( - verification_code.value, verification_code.confidence - ) + f"Verification code: {verification_code.value} has confidence: {verification_code.confidence}" ) dependent_care_benefits = w2.fields.get("DependentCareBenefits") if dependent_care_benefits: print( - "Dependent care benefits: {} has confidence: {}".format( - dependent_care_benefits.value, - dependent_care_benefits.confidence, - ) + f"Dependent care benefits: {dependent_care_benefits.value} has confidence: {dependent_care_benefits.confidence}" ) non_qualified_plans = w2.fields.get("NonQualifiedPlans") if non_qualified_plans: print( - "Non-qualified plans: {} has confidence: {}".format( - non_qualified_plans.value, - non_qualified_plans.confidence, - ) + f"Non-qualified plans: {non_qualified_plans.value} has confidence: {non_qualified_plans.confidence}" ) additional_info = w2.fields.get("AdditionalInfo") if additional_info: @@ -230,45 +192,32 @@ async def analyze_tax_us_w2_async(): letter_code = item.value.get("LetterCode") if letter_code: print( - "...Letter code: {} has confidence: {}".format( - letter_code.value, letter_code.confidence - ) + f"...Letter code: {letter_code.value} has confidence: {letter_code.confidence}" ) amount = item.value.get("Amount") if amount: print( - "...Amount: {} has confidence: {}".format( - amount.value, amount.confidence - ) + f"...Amount: {amount.value} has confidence: {amount.confidence}" ) is_statutory_employee = w2.fields.get("IsStatutoryEmployee") if is_statutory_employee: print( - "Is statutory employee: {} has confidence: {}".format( - is_statutory_employee.value, is_statutory_employee.confidence - ) + f"Is statutory employee: {is_statutory_employee.value} has confidence: {is_statutory_employee.confidence}" ) is_retirement_plan = w2.fields.get("IsRetirementPlan") if is_retirement_plan: print( - "Is retirement plan: {} has confidence: {}".format( - is_retirement_plan.value, is_retirement_plan.confidence - ) + f"Is retirement plan: {is_retirement_plan.value} has confidence: {is_retirement_plan.confidence}" ) third_party_sick_pay = w2.fields.get("IsThirdPartySickPay") if third_party_sick_pay: print( - "Is third party sick pay: {} has confidence: {}".format( - third_party_sick_pay.value, third_party_sick_pay.confidence - ) + f"Is third party sick pay: {third_party_sick_pay.value} has confidence: {third_party_sick_pay.confidence}" ) other_info = w2.fields.get("Other") if other_info: print( - "Other information: {} has confidence: {}".format( - other_info.value, - other_info.confidence, - ) + f"Other information: {other_info.value} has confidence: {other_info.confidence}" ) state_tax_info = w2.fields.get("StateTaxInfos") if state_tax_info: @@ -276,56 +225,46 @@ async def analyze_tax_us_w2_async(): for tax in state_tax_info.value: state = tax.value.get("State") if state: - print( - "...State: {} has confidence: {}".format( - state.value, state.confidence - ) - ) + print(f"...State: {state.value} has confidence: {state.confidence}") employer_state_id_number = tax.value.get("EmployerStateIdNumber") if employer_state_id_number: print( - "...Employer state ID number: {} has confidence: {}".format( - employer_state_id_number.value, employer_state_id_number.confidence - ) + f"...Employer state ID number: {employer_state_id_number.value} has " + f"confidence: {employer_state_id_number.confidence}" ) - state_wages_tips = tax.value.get("StateWagesTipsEtc") + state_wages_tips = tax.value.get("StateWagesTipsEtc") if state_wages_tips: print( - "...State wages, tips, etc: {} has confidence: {}".format( - state_wages_tips.value, state_wages_tips.confidence - ) + f"...State wages, tips, etc: {state_wages_tips.value} has confidence: " + f"{state_wages_tips.confidence}" ) - state_income_tax = tax.value.get("StateIncomeTax") + state_income_tax = tax.value.get("StateIncomeTax") if state_income_tax: print( - "...State income tax: {} has confidence: {}".format( - state_income_tax.value, state_income_tax.confidence - ) + f"...State income tax: {state_income_tax.value} has confidence: " + f"{state_income_tax.confidence}" ) local_tax_info = w2.fields.get("LocalTaxInfos") if local_tax_info: print("Local Tax info:") for tax in local_tax_info.value: - local_wages_tips = tax.value.get("LocalWagesTipsEtc") + local_wages_tips = tax.value.get("LocalWagesTipsEtc") if local_wages_tips: print( - "...Local wages, tips, etc: {} has confidence: {}".format( - local_wages_tips.value, local_wages_tips.confidence - ) + f"...Local wages, tips, etc: {local_wages_tips.value} has confidence: " + f"{local_wages_tips.confidence}" ) - local_income_tax = tax.value.get("LocalIncomeTax") + local_income_tax = tax.value.get("LocalIncomeTax") if local_income_tax: print( - "...Local income tax: {} has confidence: {}".format( - local_income_tax.value, local_income_tax.confidence - ) + f"...Local income tax: {local_income_tax.value} has confidence: " + f"{local_income_tax.confidence}" ) - locality_name = tax.value.get("LocalityName") + locality_name = tax.value.get("LocalityName") if locality_name: print( - "...Locality name: {} has confidence: {}".format( - locality_name.value, locality_name.confidence - ) + f"...Locality name: {locality_name.value} has confidence: " + f"{locality_name.confidence}" ) @@ -336,11 +275,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_authentication_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_authentication_async.py index 2906b62a6e35..c0ed9a310f87 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_authentication_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_authentication_async.py @@ -81,7 +81,9 @@ async def authentication_with_api_key_credential_document_model_admin_client_asy endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, AzureKeyCredential(key) + ) # [END create_dt_client_with_key_async] async with document_model_admin_client: info = await document_model_admin_client.get_resource_details() @@ -98,7 +100,9 @@ async def authentication_with_azure_active_directory_document_model_admin_client endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] credential = DefaultAzureCredential() - document_model_admin_client = DocumentModelAdministrationClient(endpoint, credential) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, credential + ) # [END create_dt_client_with_aad_async] async with document_model_admin_client: info = await document_model_admin_client.get_resource_details() @@ -114,11 +118,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_classifier_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_classifier_async.py index 2833f94870c2..a6d73837f612 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_classifier_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_classifier_async.py @@ -35,7 +35,7 @@ async def sample_build_classifier_async(): from azure.ai.formrecognizer import ( ClassifierDocumentTypeDetails, AzureBlobContentSource, - AzureBlobFileListSource + AzureBlobFileListSource, ) from azure.core.credentials import AzureKeyCredential @@ -43,7 +43,9 @@ async def sample_build_classifier_async(): key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CLASSIFIER_CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) async with document_model_admin_client: # pass either a azure_blob_source or azure_blob_file_list_source @@ -51,18 +53,16 @@ async def sample_build_classifier_async(): doc_types={ "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-A/train" + container_url=container_sas_url, prefix="IRS-1040-A/train" ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_file_list_source=AzureBlobFileListSource( - container_url=container_sas_url, - file_list="IRS-1040-D.jsonl" + container_url=container_sas_url, file_list="IRS-1040-D.jsonl" ) ), }, - description="IRS document classifier" + description="IRS document classifier", ) result = await poller.result() print(f"Classifier ID: {result.classifier_id}") @@ -71,7 +71,11 @@ async def sample_build_classifier_async(): print(f"Document classes used for training the model:") for doc_type, source in result.doc_types.items(): print(f"Document type: {doc_type}") - blob_source = source.azure_blob_source if source.azure_blob_source else source.azure_blob_file_list_source + blob_source = ( + source.azure_blob_source + if source.azure_blob_source + else source.azure_blob_file_list_source + ) print(f"Container source: {blob_source.container_url}\n") # [END build_classifier_async] @@ -80,5 +84,5 @@ async def main(): await sample_build_classifier_async() -if __name__ == '__main__': +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_model_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_model_async.py index 367de7dccaa4..0a0626d45205 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_model_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_build_model_async.py @@ -39,38 +39,49 @@ async def sample_build_model_async(): key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, AzureKeyCredential(key) + ) async with document_model_admin_client: poller = await document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=container_sas_url, description="my model description" + ModelBuildMode.TEMPLATE, + blob_container_url=container_sas_url, + description="my model description", ) model = await poller.result() - print("Model ID: {}".format(model.model_id)) - print("Description: {}".format(model.description)) - print("Model created on: {}\n".format(model.created_on)) - print("Model expires on: {}".format(model.expires_on)) + print(f"Model ID: {model.model_id}") + print(f"Description: {model.description}") + print(f"Model created on: {model.created_on}") + print(f"Model expires on: {model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in model.doc_types.items(): - print("\nDoc Type: '{}' built with '{}' mode which has the following fields:".format(name, doc_type.build_mode)) + print( + f"Doc Type: '{name}' built with '{doc_type.build_mode}' mode which has the following fields:" + ) for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END build_model_async] async def main(): await sample_build_model_async() -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_async.py index d840a2160542..5b8b699bb7af 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_async.py @@ -63,20 +63,21 @@ async def classify_document_async(classifier_id): print("----Classified documents----") for doc in result.documents: - print(f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " - f"the following pages: {[region.page_number for region in doc.bounding_regions]}") + print( + f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " + f"the following pages: {[region.page_number for region in doc.bounding_regions]}" + ) # [END classify_document_async] async def main(): classifier_id = None if os.getenv("CLASSIFIER_CONTAINER_SAS_URL") and not os.getenv("CLASSIFIER_ID"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient from azure.ai.formrecognizer import ( ClassifierDocumentTypeDetails, - AzureBlobContentSource + AzureBlobContentSource, ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] @@ -92,13 +93,13 @@ async def main(): "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-A/train" + prefix="IRS-1040-A/train", ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-D/train" + prefix="IRS-1040-D/train", ) ), }, @@ -108,13 +109,17 @@ async def main(): await classify_document_async(classifier_id) -if __name__ == '__main__': + +if __name__ == "__main__": from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_from_url_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_from_url_async.py index c5f508b723cd..9e4775d42c58 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_from_url_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_classify_document_from_url_async.py @@ -31,6 +31,7 @@ import os import asyncio + async def classify_document_from_url_async(classifier_id): # [START classify_document_from_url_async] from azure.core.credentials import AzureKeyCredential @@ -53,20 +54,21 @@ async def classify_document_from_url_async(classifier_id): print("----Classified documents----") for doc in result.documents: - print(f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " - f"the following pages: {[region.page_number for region in doc.bounding_regions]}") + print( + f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " + f"the following pages: {[region.page_number for region in doc.bounding_regions]}" + ) # [END classify_document_from_url_async] async def main(): classifier_id = None if os.getenv("CLASSIFIER_CONTAINER_SAS_URL") and not os.getenv("CLASSIFIER_ID"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient from azure.ai.formrecognizer import ( ClassifierDocumentTypeDetails, - AzureBlobContentSource + AzureBlobContentSource, ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] @@ -82,13 +84,13 @@ async def main(): "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-A/train" + prefix="IRS-1040-A/train", ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-D/train" + prefix="IRS-1040-D/train", ) ), }, @@ -98,13 +100,17 @@ async def main(): await classify_document_from_url_async(classifier_id) -if __name__ == '__main__': + +if __name__ == "__main__": from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_compose_model_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_compose_model_async.py index e757afb307ce..e49934b36099 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_compose_model_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_compose_model_async.py @@ -47,24 +47,36 @@ async def sample_compose_model_async(): endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - po_supplies = os.environ['PURCHASE_ORDER_OFFICE_SUPPLIES_SAS_URL'] - po_equipment = os.environ['PURCHASE_ORDER_OFFICE_EQUIPMENT_SAS_URL'] - po_furniture = os.environ['PURCHASE_ORDER_OFFICE_FURNITURE_SAS_URL'] - po_cleaning_supplies = os.environ['PURCHASE_ORDER_OFFICE_CLEANING_SUPPLIES_SAS_URL'] - - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + po_supplies = os.environ["PURCHASE_ORDER_OFFICE_SUPPLIES_SAS_URL"] + po_equipment = os.environ["PURCHASE_ORDER_OFFICE_EQUIPMENT_SAS_URL"] + po_furniture = os.environ["PURCHASE_ORDER_OFFICE_FURNITURE_SAS_URL"] + po_cleaning_supplies = os.environ["PURCHASE_ORDER_OFFICE_CLEANING_SUPPLIES_SAS_URL"] + + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) async with document_model_admin_client: supplies_poller = await document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_supplies, description="Purchase order-Office supplies" + ModelBuildMode.TEMPLATE, + blob_container_url=po_supplies, + description="Purchase order-Office supplies", ) equipment_poller = await document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_equipment, description="Purchase order-Office Equipment" + ModelBuildMode.TEMPLATE, + blob_container_url=po_equipment, + description="Purchase order-Office Equipment", ) furniture_poller = await document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_furniture, description="Purchase order-Furniture" + ModelBuildMode.TEMPLATE, + blob_container_url=po_furniture, + description="Purchase order-Furniture", ) - cleaning_supplies_poller = await document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_cleaning_supplies, description="Purchase order-Cleaning Supplies" + cleaning_supplies_poller = ( + await document_model_admin_client.begin_build_document_model( + ModelBuildMode.TEMPLATE, + blob_container_url=po_cleaning_supplies, + description="Purchase order-Cleaning Supplies", + ) ) supplies_model = await supplies_poller.result() equipment_model = await equipment_poller.result() @@ -75,7 +87,7 @@ async def sample_compose_model_async(): supplies_model.model_id, equipment_model.model_id, furniture_model.model_id, - cleaning_supplies_model.model_id + cleaning_supplies_model.model_id, ] poller = await document_model_admin_client.begin_compose_document_model( @@ -84,31 +96,36 @@ async def sample_compose_model_async(): model = await poller.result() print("Office Supplies Composed Model Info:") - print("Model ID: {}".format(model.model_id)) - print("Description: {}".format(model.description)) - print("Model created on: {}\n".format(model.created_on)) - print("Model expires on: {}".format(model.expires_on)) + print(f"Model ID: {model.model_id}") + print(f"Description: {model.description}") + print(f"Model created on: {model.created_on}") + print(f"Model expires on: {model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in model.doc_types.items(): - print("\nDoc Type: '{}' which has the following fields:".format(name)) + print(f"Doc Type: '{name}' which has the following fields:") for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END composed_model_async] async def main(): await sample_compose_model_async() -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_convert_to_and_from_dict_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_convert_to_and_from_dict_async.py index ae43bff95dc6..5891f5efb2ba 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_convert_to_and_from_dict_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_convert_to_and_from_dict_async.py @@ -26,6 +26,7 @@ import json import asyncio + async def convert_to_and_from_dict_async(): path_to_sample_documents = os.path.abspath( os.path.join( @@ -61,7 +62,7 @@ async def convert_to_and_from_dict_async(): # save the dictionary as JSON content in a JSON file, use the AzureJSONEncoder # to help make types, such as dates, JSON serializable # NOTE: AzureJSONEncoder is only available with azure.core>=1.18.0. - with open('data.json', 'w') as output_file: + with open("data.json", "w") as output_file: json.dump(analyze_result_dict, output_file, cls=AzureJSONEncoder) # convert the dictionary back to the original model @@ -69,9 +70,9 @@ async def convert_to_and_from_dict_async(): # use the model as normal print("----Converted from dictionary AnalyzeResult----") - print("Model ID: '{}'".format(model.model_id)) - print("Number of pages analyzed {}".format(len(model.pages))) - print("API version used: {}".format(model.api_version)) + print(f"Model ID: '{model.model_id}'") + print(f"Number of pages analyzed {len(model.pages)}") + print(f"API version used: {model.api_version}") print("----------------------------------------") @@ -80,14 +81,17 @@ async def main(): await convert_to_and_from_dict_async() -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_copy_model_to_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_copy_model_to_async.py index 33f14d272a69..17a7908bcdb0 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_copy_model_to_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_copy_model_to_async.py @@ -45,38 +45,42 @@ async def sample_copy_model_to_async(custom_model_id): target_key = os.environ["AZURE_FORM_RECOGNIZER_TARGET_KEY"] source_model_id = os.getenv("AZURE_SOURCE_MODEL_ID", custom_model_id) - target_client = DocumentModelAdministrationClient(endpoint=target_endpoint, credential=AzureKeyCredential(target_key)) + target_client = DocumentModelAdministrationClient( + endpoint=target_endpoint, credential=AzureKeyCredential(target_key) + ) async with target_client: target = await target_client.get_copy_authorization( description="model copied from other resource" ) - source_client = DocumentModelAdministrationClient(endpoint=source_endpoint, credential=AzureKeyCredential(source_key)) + source_client = DocumentModelAdministrationClient( + endpoint=source_endpoint, credential=AzureKeyCredential(source_key) + ) async with source_client: poller = await source_client.begin_copy_document_model_to( model_id=source_model_id, - target=target # output from target client's call to get_copy_authorization() + target=target, # output from target client's call to get_copy_authorization() ) copied_over_model = await poller.result() - print("Model ID: {}".format(copied_over_model.model_id)) - print("Description: {}".format(copied_over_model.description)) - print("Model created on: {}\n".format(copied_over_model.created_on)) - print("Model expires on: {}".format(copied_over_model.expires_on)) + print(f"Model ID: {copied_over_model.model_id}") + print(f"Description: {copied_over_model.description}") + print(f"Model created on: {copied_over_model.created_on}") + print(f"Model expires on: {copied_over_model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in copied_over_model.doc_types.items(): - print("\nDoc Type: '{}' which has the following fields:".format(name)) + print(f"Doc Type: '{name}' which has the following fields:") for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END begin_copy_document_model_to_async] async def main(): model_id = None if os.getenv("CONTAINER_SAS_URL"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient from azure.ai.formrecognizer import ModelBuildMode @@ -94,20 +98,27 @@ async def main(): blob_container_sas_url = os.getenv("CONTAINER_SAS_URL") if blob_container_sas_url is not None: model = await ( - await document_model_admin_client.begin_build_document_model(ModelBuildMode.TEMPLATE, blob_container_url=blob_container_sas_url) + await document_model_admin_client.begin_build_document_model( + ModelBuildMode.TEMPLATE, + blob_container_url=blob_container_sas_url, + ) ).result() model_id = model.model_id await sample_copy_model_to_async(model_id) -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_elements_with_spans_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_elements_with_spans_async.py index 1fa03ed6d833..66b3ff09a264 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_elements_with_spans_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_elements_with_spans_async.py @@ -26,6 +26,7 @@ import os import asyncio + def get_styles(element_spans, styles): result = [] for span in element_spans: @@ -37,6 +38,7 @@ def get_styles(element_spans, styles): result.append(style) return result + def get_lines(element_spans, document_page): result = [] for span in element_spans: @@ -48,12 +50,14 @@ def get_lines(element_spans, document_page): result.append(line) return result + def get_page(page_number, pages): for page in pages: if page.page_number == page_number: return page raise ValueError("could not find the requested page") + async def get_elements_with_spans_async(): path_to_sample_documents = os.path.abspath( os.path.join( @@ -89,30 +93,24 @@ async def get_elements_with_spans_async(): if result.tables is not None: for table_idx, table in enumerate(result.tables): print( - "Table # {} has {} rows and {} columns".format( - table_idx, table.row_count, table.column_count - ) + f"Table # {table_idx} has {table.row_count} rows and {table.column_count} columns" ) lines = [] if table.bounding_regions is not None: for region in table.bounding_regions: - print( - "Table # {} location on page: {}".format( - table_idx, - region.page_number, + print(f"Table # {table_idx} location on page: {region.page_number}") + lines.extend( + get_lines( + table.spans, get_page(region.page_number, result.pages) ) ) - lines.extend(get_lines(table.spans, get_page(region.page_number, result.pages))) - print("Found # {} lines in the table".format(len(lines))) + print(f"Found # {len(lines)} lines in the table") for line in lines: print( - "...Line '{}' is within bounding polygon: '{}'".format( - line.content, - line.polygon, - ) + f"...Line '{line.content}' is within bounding polygon: '{line.polygon}'" ) # Below is a method to search for the style of a particular element by using spans. @@ -121,20 +119,12 @@ async def get_elements_with_spans_async(): if result.pages[0].lines is not None: for line in result.pages[0].lines: styles = get_styles(line.spans, result.styles) - print( - "Found line '{}' with style:".format( - line.content - ) - ) + print(f"Found line '{line.content}' with style:") if not styles: - print( - "...no handwritten text found" - ) + print("...no handwritten text found") for style in styles: if style.is_handwritten: - print( - "...handwritten with confidence {}".format(style.confidence) - ) + print(f"...handwritten with confidence {style.confidence}") print("----------------------------------------") @@ -142,14 +132,17 @@ async def main(): await get_elements_with_spans_async() -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_operations_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_operations_async.py index 37fdaa177004..dbc64f403c78 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_operations_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_operations_async.py @@ -35,60 +35,70 @@ async def sample_get_operations_async(): endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) async with document_model_admin_client: operations = document_model_admin_client.list_operations() print("The following document model operations exist under my resource:") async for operation in operations: - print("\nOperation ID: {}".format(operation.operation_id)) - print("Operation kind: {}".format(operation.kind)) - print("Operation status: {}".format(operation.status)) - print("Operation percent completed: {}".format(operation.percent_completed)) - print("Operation created on: {}".format(operation.created_on)) - print("Operation last updated on: {}".format(operation.last_updated_on)) - print("Resource location of successful operation: {}".format(operation.resource_location)) - # [END list_operations_async] + print(f"\nOperation ID: {operation.operation_id}") + print(f"Operation kind: {operation.kind}") + print(f"Operation status: {operation.status}") + print(f"Operation percent completed: {operation.percent_completed}") + print(f"Operation created on: {operation.created_on}") + print(f"Operation last updated on: {operation.last_updated_on}") + print( + f"Resource location of successful operation: {operation.resource_location}" + ) + # [END list_operations_async] # [START get_operation_async] # Get an operation by ID try: first_operation = await operations.__anext__() - print("\nGetting operation info by ID: {}".format(first_operation.operation_id)) - operation_info = await document_model_admin_client.get_operation(first_operation.operation_id) + print(f"\nGetting operation info by ID: {first_operation.operation_id}") + operation_info = await document_model_admin_client.get_operation( + first_operation.operation_id + ) if operation_info.status == "succeeded": - print("My {} operation is completed.".format(operation_info.kind)) + print(f"My {operation_info.kind} operation is completed.") result = operation_info.result if result is not None: if operation_info.kind == "documentClassifierBuild": print(f"Classifier ID: {result.classifier_id}") else: - print("Model ID: {}".format(result.model_id)) + print(f"Model ID: {result.model_id}") elif operation_info.status == "failed": - print("My {} operation failed.".format(operation_info.kind)) + print(f"My {operation_info.kind} operation failed.") error = operation_info.error if error is not None: - print("{}: {}".format(error.code, error.message)) + print(f"{error.code}: {error.message}") else: - print("My operation status is {}".format(operation_info.status)) + print(f"My operation status is {operation_info.status}") except StopAsyncIteration: print("No operations found.") # [END get_operation_async] + async def main(): await sample_get_operations_async() -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_words_on_document_line_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_words_on_document_line_async.py index fb91ddb08985..ca3f4fc50476 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_words_on_document_line_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_get_words_on_document_line_async.py @@ -25,15 +25,20 @@ import os import asyncio + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) async def get_words_on_document_line_async(): @@ -63,31 +68,23 @@ async def get_words_on_document_line_async(): ) result = await poller.result() - for idx, page in enumerate(result.pages): - print("----Analyzing lines and words from page #{}----".format(idx + 1)) + for page in result.pages: + print(f"----Analyzing lines and words from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) if page.lines is not None: for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' " + f"within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) print("----------------------------------------") @@ -100,11 +97,14 @@ async def main(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_classifiers_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_classifiers_async.py index fdd24a65f6cd..62376b8ea989 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_classifiers_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_classifiers_async.py @@ -30,13 +30,18 @@ async def sample_manage_classifiers_async(): from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import ResourceNotFoundError from azure.ai.formrecognizer.aio import DocumentModelAdministrationClient - from azure.ai.formrecognizer import ClassifierDocumentTypeDetails, AzureBlobContentSource + from azure.ai.formrecognizer import ( + ClassifierDocumentTypeDetails, + AzureBlobContentSource, + ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CLASSIFIER_CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) async with document_model_admin_client: # build a document classifier @@ -44,16 +49,14 @@ async def sample_manage_classifiers_async(): doc_types={ "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-A/train" + container_url=container_sas_url, prefix="IRS-1040-A/train" ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-D/train" + container_url=container_sas_url, prefix="IRS-1040-D/train" ) - ) + ), }, ) classifier_model = await poller.result() @@ -65,38 +68,50 @@ async def sample_manage_classifiers_async(): print("We have the following 'ready' models with IDs and descriptions:") async for classifier in classifiers: - print("{} | {}".format(classifier.classifier_id, classifier.description)) + print(f"{classifier.classifier_id} | {classifier.description}") # [END list_document_classifiers_async] # [START get_document_classifier_async] - my_classifier = await document_model_admin_client.get_document_classifier(classifier_id=classifier_model.classifier_id) - print("\nClassifier ID: {}".format(my_classifier.classifier_id)) - print("Description: {}".format(my_classifier.description)) - print("Classifier created on: {}".format(my_classifier.created_on)) + my_classifier = await document_model_admin_client.get_document_classifier( + classifier_id=classifier_model.classifier_id + ) + print(f"\nClassifier ID: {my_classifier.classifier_id}") + print(f"Description: {my_classifier.description}") + print(f"Classifier created on: {my_classifier.created_on}") # [END get_document_classifier_async] # Finally, we will delete this classifier by ID # [START delete_document_classifier_async] - await document_model_admin_client.delete_document_classifier(classifier_id=my_classifier.classifier_id) + await document_model_admin_client.delete_document_classifier( + classifier_id=my_classifier.classifier_id + ) try: - await document_model_admin_client.get_document_classifier(classifier_id=my_classifier.classifier_id) + await document_model_admin_client.get_document_classifier( + classifier_id=my_classifier.classifier_id + ) except ResourceNotFoundError: - print("Successfully deleted classifier with ID {}".format(my_classifier.classifier_id)) + print( + f"Successfully deleted classifier with ID {my_classifier.classifier_id}" + ) # [END delete_document_classifier_async] async def main(): await sample_manage_classifiers_async() -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_models_async.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_models_async.py index 9fa7e42484f8..3de0bdce33b0 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_models_async.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/async_samples/sample_manage_models_async.py @@ -37,16 +37,21 @@ async def sample_manage_models_async(): container_sas_url = os.environ["CONTAINER_SAS_URL"] # [START get_resource_details_async] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) async with document_model_admin_client: account_details = await document_model_admin_client.get_resource_details() - print("Our resource has {} custom models, and we can have at most {} custom models\n".format( - account_details.custom_document_models.count, account_details.custom_document_models.limit - )) + print( + f"Our resource has {account_details.custom_document_models.count} custom models, " + f"and we can have at most {account_details.custom_document_models.limit} custom models" + ) neural_models = account_details.custom_neural_document_model_builds - print(f"The quota limit for custom neural document models is {neural_models.quota} and the resource has" - f"used {neural_models.used}. The resource quota will reset on {neural_models.quota_resets_on}") + print( + f"The quota limit for custom neural document models is {neural_models.quota} and the resource has" + f"used {neural_models.used}. The resource quota will reset on {neural_models.quota_resets_on}" + ) # [END get_resource_details_async] # Next, we get a paged list of all of our custom models @@ -55,43 +60,57 @@ async def sample_manage_models_async(): print("We have the following 'ready' models with IDs and descriptions:") async for model in models: - print("{} | {}".format(model.model_id, model.description)) + print(f"{model.model_id} | {model.description}") # [END list_document_models_async] # let's build a model to use for this sample - poller = await document_model_admin_client.begin_build_document_model(ModelBuildMode.TEMPLATE, blob_container_url=container_sas_url, description="model for sample") + poller = await document_model_admin_client.begin_build_document_model( + ModelBuildMode.TEMPLATE, + blob_container_url=container_sas_url, + description="model for sample", + ) model = await poller.result() # [START get_document_model_async] - my_model = await document_model_admin_client.get_document_model(model_id=model.model_id) - print("\nModel ID: {}".format(my_model.model_id)) - print("Description: {}".format(my_model.description)) - print("Model created on: {}".format(my_model.created_on)) - print("Model expires on: {}".format(my_model.expires_on)) + my_model = await document_model_admin_client.get_document_model( + model_id=model.model_id + ) + print(f"\nModel ID: {my_model.model_id}") + print(f"Description: {my_model.description}") + print(f"Model created on: {my_model.created_on}") + print(f"Model expires on: {my_model.expires_on}") # [END get_document_model_async] # Finally, we will delete this model by ID # [START delete_document_model_async] - await document_model_admin_client.delete_document_model(model_id=my_model.model_id) + await document_model_admin_client.delete_document_model( + model_id=my_model.model_id + ) try: - await document_model_admin_client.get_document_model(model_id=my_model.model_id) + await document_model_admin_client.get_document_model( + model_id=my_model.model_id + ) except ResourceNotFoundError: - print("Successfully deleted model with ID {}".format(my_model.model_id)) + print(f"Successfully deleted model with ID {my_model.model_id}") # [END delete_document_model_async] async def main(): await sample_manage_models_async() -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: asyncio.run(main()) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_business_cards.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_business_cards.py index 3a2b899e7a78..7680471ee735 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_business_cards.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_business_cards.py @@ -52,114 +52,83 @@ def analyze_business_card(): business_cards = poller.result() for idx, business_card in enumerate(business_cards.documents): - print("--------Analyzing business card #{}--------".format(idx + 1)) + print(f"--------Analyzing business card #{idx + 1}--------") contact_names = business_card.fields.get("ContactNames") if contact_names: for contact_name in contact_names.value: print( - "Contact First Name: {} has confidence: {}".format( - contact_name.value["FirstName"].value, - contact_name.value[ - "FirstName" - ].confidence, - ) + f"Contact First Name: {contact_name.value['FirstName'].value} " + f"has confidence: {contact_name.value['FirstName'].confidence}" ) print( - "Contact Last Name: {} has confidence: {}".format( - contact_name.value["LastName"].value, - contact_name.value[ - "LastName" - ].confidence, - ) + f"Contact Last Name: {contact_name.value['LastName'].value} has" + f" confidence: {contact_name.value['LastName'].confidence}" ) company_names = business_card.fields.get("CompanyNames") if company_names: for company_name in company_names.value: print( - "Company Name: {} has confidence: {}".format( - company_name.value, company_name.confidence - ) + f"Company Name: {company_name.value} has confidence: {company_name.confidence}" ) departments = business_card.fields.get("Departments") if departments: for department in departments.value: print( - "Department: {} has confidence: {}".format( - department.value, department.confidence - ) + f"Department: {department.value} has confidence: {department.confidence}" ) job_titles = business_card.fields.get("JobTitles") if job_titles: for job_title in job_titles.value: print( - "Job Title: {} has confidence: {}".format( - job_title.value, job_title.confidence - ) + f"Job Title: {job_title.value} has confidence: {job_title.confidence}" ) emails = business_card.fields.get("Emails") if emails: for email in emails.value: - print( - "Email: {} has confidence: {}".format(email.value, email.confidence) - ) + print(f"Email: {email.value} has confidence: {email.confidence}") websites = business_card.fields.get("Websites") if websites: for website in websites.value: - print( - "Website: {} has confidence: {}".format( - website.value, website.confidence - ) - ) + print(f"Website: {website.value} has confidence: {website.confidence}") addresses = business_card.fields.get("Addresses") if addresses: for address in addresses.value: - print( - "Address: {} has confidence: {}".format( - address.value, address.confidence - ) - ) + print(f"Address: {address.value} has confidence: {address.confidence}") mobile_phones = business_card.fields.get("MobilePhones") if mobile_phones: for phone in mobile_phones.value: print( - "Mobile phone number: {} has confidence: {}".format( - phone.content, phone.confidence - ) + f"Mobile phone number: {phone.content} has confidence: {phone.confidence}" ) faxes = business_card.fields.get("Faxes") if faxes: for fax in faxes.value: - print( - "Fax number: {} has confidence: {}".format( - fax.content, fax.confidence - ) - ) + print(f"Fax number: {fax.content} has confidence: {fax.confidence}") work_phones = business_card.fields.get("WorkPhones") if work_phones: for work_phone in work_phones.value: print( - "Work phone number: {} has confidence: {}".format( - work_phone.content, work_phone.confidence - ) + f"Work phone number: {work_phone.content} has confidence: {work_phone.confidence}" ) other_phones = business_card.fields.get("OtherPhones") if other_phones: for other_phone in other_phones.value: print( - "Other phone number: {} has confidence: {}".format( - other_phone.value, other_phone.confidence - ) + f"Other phone number: {other_phone.value} has confidence: {other_phone.confidence}" ) if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_business_card() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_custom_documents.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_custom_documents.py index f53a1bf1b792..a6f9fdf74317 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_custom_documents.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_custom_documents.py @@ -59,42 +59,37 @@ def analyze_custom_documents(custom_model_id): result = poller.result() for idx, document in enumerate(result.documents): - print("--------Analyzing document #{}--------".format(idx + 1)) - print("Document has type {}".format(document.doc_type)) - print("Document has confidence {}".format(document.confidence)) - print("Document was analyzed by model with ID {}".format(result.model_id)) + print(f"--------Analyzing document #{idx + 1}--------") + print(f"Document has type {document.doc_type}") + print(f"Document has document type confidence {document.confidence}") + print(f"Document was analyzed with model with ID {result.model_id}") for name, field in document.fields.items(): field_value = field.value if field.value else field.content - print("......found field of type '{}' with value '{}' and with confidence {}".format(field.value_type, field_value, field.confidence)) - + print( + f"......found field of type '{field.value_type}' with value '{field_value}' and with confidence {field.confidence}" + ) # iterate over tables, lines, and selection marks on each page for page in result.pages: - print("\nLines found on page {}".format(page.page_number)) + print(f"\nLines found on page {page.page_number}") for line in page.lines: - print("...Line '{}'".format(line.content)) + print(f"...Line '{line.content}'") 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 '{}' and has a confidence of {}".format( - selection_mark.state, selection_mark.confidence + print(f"...Word '{word.content}' has a confidence of {word.confidence}") + if page.selection_marks: + print(f"\nSelection marks found on page {page.page_number}") + for selection_mark in page.selection_marks: + print( + f"...Selection mark is '{selection_mark.state}' and has a confidence of {selection_mark.confidence}" ) - ) for i, table in enumerate(result.tables): - print("\nTable {} can be found on page:".format(i + 1)) + print(f"\nTable {i + 1} can be found on page:") for region in table.bounding_regions: - print("...{}".format(region.page_number)) + print(f"...{region.page_number}") for cell in table.cells: print( - "...Cell[{}][{}] has content '{}'".format( - cell.row_index, cell.column_index, cell.content - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) print("-----------------------------------") # [END analyze_custom_documents] @@ -103,17 +98,23 @@ def analyze_custom_documents(custom_model_id): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: model_id = None if os.getenv("CONTAINER_SAS_URL") and not os.getenv("CUSTOM_BUILT_MODEL_ID"): from azure.core.credentials import AzureKeyCredential - from azure.ai.formrecognizer import DocumentModelAdministrationClient, ModelBuildMode + from azure.ai.formrecognizer import ( + DocumentModelAdministrationClient, + ModelBuildMode, + ) endpoint = os.getenv("AZURE_FORM_RECOGNIZER_ENDPOINT") key = os.getenv("AZURE_FORM_RECOGNIZER_KEY") if not endpoint or not key: - raise ValueError("Please provide endpoint and API key to run the samples.") + raise ValueError( + "Please provide endpoint and API key to run the samples." + ) document_model_admin_client = DocumentModelAdministrationClient( endpoint=endpoint, credential=AzureKeyCredential(key) @@ -126,8 +127,10 @@ def analyze_custom_documents(custom_model_id): model_id = model.model_id analyze_custom_documents(model_id) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_general_documents.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_general_documents.py index 6ac4b0f79d8b..9b141674a7e5 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_general_documents.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_general_documents.py @@ -23,15 +23,20 @@ import os + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) def analyze_general_documents(): @@ -63,7 +68,14 @@ def analyze_general_documents(): 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( + ",".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: @@ -71,82 +83,55 @@ def analyze_general_documents(): print(f"Common name for key value pair: {kv_pair.common_name}") if kv_pair.key: print( - "Key '{}' found within '{}' bounding regions".format( - kv_pair.key.content, - format_bounding_region(kv_pair.key.bounding_regions), - ) - ) + f"Key '{kv_pair.key.content}' found within " + f"'{format_bounding_region(kv_pair.key.bounding_regions)}' 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), - ) - ) + f"Value '{kv_pair.value.content}' found within " + f"'{format_bounding_region(kv_pair.value.bounding_regions)}' bounding regions\n" + ) for page in result.pages: - print("----Analyzing document from page #{}----".format(page.page_number)) + print(f"----Analyzing document from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has {} words and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line #{line_idx} has {len(words)} words and text '{line.content}' within " + f"bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of " + f"{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 - ) + f"Table # {table_idx} has {table.row_count} rows and {table.column_count} columns" ) for region in table.bounding_regions: print( - "Table # {} location on page: {} is {}".format( - table_idx, - region.page_number, - format_polygon(region.polygon), - ) + f"Table # {table_idx} location on page: {region.page_number} is {format_polygon(region.polygon)}" ) for cell in table.cells: print( - "...Cell[{}][{}] has content '{}'".format( - cell.row_index, - cell.column_index, - cell.content, - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) for region in cell.bounding_regions: print( - "...content on page {} is within bounding polygon '{}'\n".format( - region.page_number, - format_polygon(region.polygon), - ) + f"...content on page {region.page_number} is within bounding polygon '{format_polygon(region.polygon)}'\n" ) print("----------------------------------------") # [END analyze_general_documents] @@ -155,11 +140,14 @@ def analyze_general_documents(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_general_documents() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_identity_documents.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_identity_documents.py index 0225504d2383..08b6857aaf30 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_identity_documents.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_identity_documents.py @@ -52,72 +52,55 @@ def analyze_identity_documents(): id_documents = poller.result() for idx, id_document in enumerate(id_documents.documents): - print("--------Analyzing ID document #{}--------".format(idx + 1)) + print(f"--------Analyzing ID document #{idx + 1}--------") first_name = id_document.fields.get("FirstName") if first_name: print( - "First Name: {} has confidence: {}".format( - first_name.value, first_name.confidence - ) + f"First Name: {first_name.value} has confidence: {first_name.confidence}" ) last_name = id_document.fields.get("LastName") if last_name: print( - "Last Name: {} has confidence: {}".format( - last_name.value, last_name.confidence - ) + f"Last Name: {last_name.value} has confidence: {last_name.confidence}" ) document_number = id_document.fields.get("DocumentNumber") if document_number: print( - "Document Number: {} has confidence: {}".format( - document_number.value, document_number.confidence - ) + f"Document Number: {document_number.value} has confidence: {document_number.confidence}" ) dob = id_document.fields.get("DateOfBirth") if dob: - print( - "Date of Birth: {} has confidence: {}".format(dob.value, dob.confidence) - ) + print(f"Date of Birth: {dob.value} has confidence: {dob.confidence}") doe = id_document.fields.get("DateOfExpiration") if doe: - print( - "Date of Expiration: {} has confidence: {}".format( - doe.value, doe.confidence - ) - ) + print(f"Date of Expiration: {doe.value} has confidence: {doe.confidence}") sex = id_document.fields.get("Sex") if sex: - print("Sex: {} has confidence: {}".format(sex.value, sex.confidence)) + print(f"Sex: {sex.value} has confidence: {sex.confidence}") address = id_document.fields.get("Address") if address: - print( - "Address: {} has confidence: {}".format( - address.value, address.confidence - ) - ) + print(f"Address: {address.value} has confidence: {address.confidence}") country_region = id_document.fields.get("CountryRegion") if country_region: print( - "Country/Region: {} has confidence: {}".format( - country_region.value, country_region.confidence - ) + f"Country/Region: {country_region.value} has confidence: {country_region.confidence}" ) region = id_document.fields.get("Region") if region: - print( - "Region: {} has confidence: {}".format(region.value, region.confidence) - ) + print(f"Region: {region.value} has confidence: {region.confidence}") if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_identity_documents() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_invoices.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_invoices.py index 1fbdb1008f9c..7d07064e0d5b 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_invoices.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_invoices.py @@ -53,250 +53,172 @@ def analyze_invoice(): invoices = poller.result() for idx, invoice in enumerate(invoices.documents): - print("--------Analyzing invoice #{}--------".format(idx + 1)) + print(f"--------Analyzing invoice #{idx + 1}--------") vendor_name = invoice.fields.get("VendorName") if vendor_name: print( - "Vendor Name: {} has confidence: {}".format( - vendor_name.value, vendor_name.confidence - ) + f"Vendor Name: {vendor_name.value} has confidence: {vendor_name.confidence}" ) vendor_address = invoice.fields.get("VendorAddress") if vendor_address: print( - "Vendor Address: {} has confidence: {}".format( - vendor_address.value, vendor_address.confidence - ) + f"Vendor Address: {vendor_address.value} has confidence: {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 - ) + f"Vendor Address Recipient: {vendor_address_recipient.value} has confidence: {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 - ) + f"Customer Name: {customer_name.value} has confidence: {customer_name.confidence}" ) customer_id = invoice.fields.get("CustomerId") if customer_id: print( - "Customer Id: {} has confidence: {}".format( - customer_id.value, customer_id.confidence - ) + f"Customer Id: {customer_id.value} has confidence: {customer_id.confidence}" ) customer_address = invoice.fields.get("CustomerAddress") if customer_address: print( - "Customer Address: {} has confidence: {}".format( - customer_address.value, customer_address.confidence - ) + f"Customer Address: {customer_address.value} has confidence: {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, - ) + f"Customer Address Recipient: {customer_address_recipient.value} has confidence: {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 - ) + f"Invoice Id: {invoice_id.value} has confidence: {invoice_id.confidence}" ) invoice_date = invoice.fields.get("InvoiceDate") if invoice_date: print( - "Invoice Date: {} has confidence: {}".format( - invoice_date.value, invoice_date.confidence - ) + f"Invoice Date: {invoice_date.value} has confidence: {invoice_date.confidence}" ) invoice_total = invoice.fields.get("InvoiceTotal") if invoice_total: print( - "Invoice Total: {} has confidence: {}".format( - invoice_total.value, invoice_total.confidence - ) + f"Invoice Total: {invoice_total.value} has confidence: {invoice_total.confidence}" ) due_date = invoice.fields.get("DueDate") if due_date: - print( - "Due Date: {} has confidence: {}".format( - due_date.value, due_date.confidence - ) - ) + print(f"Due Date: {due_date.value} has confidence: {due_date.confidence}") purchase_order = invoice.fields.get("PurchaseOrder") if purchase_order: print( - "Purchase Order: {} has confidence: {}".format( - purchase_order.value, purchase_order.confidence - ) + f"Purchase Order: {purchase_order.value} has confidence: {purchase_order.confidence}" ) billing_address = invoice.fields.get("BillingAddress") if billing_address: print( - "Billing Address: {} has confidence: {}".format( - billing_address.value, billing_address.confidence - ) + f"Billing Address: {billing_address.value} has confidence: {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, - ) + f"Billing Address Recipient: {billing_address_recipient.value} has confidence: {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 - ) + f"Shipping Address: {shipping_address.value} has confidence: {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, - ) + f"Shipping Address Recipient: {shipping_address_recipient.value} has confidence: {shipping_address_recipient.confidence}" ) print("Invoice items:") for idx, item in enumerate(invoice.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Description: {item_description.value} has confidence: {item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Quantity: {item_quantity.value} has confidence: {item_quantity.confidence}" ) unit = item.value.get("Unit") if unit: - print( - "......Unit: {} has confidence: {}".format( - unit.value, unit.confidence - ) - ) + print(f"......Unit: {unit.value} has confidence: {unit.confidence}") unit_price = item.value.get("UnitPrice") if unit_price: + unit_price_code = unit_price.value.code if unit_price.value.code else "" print( - "......Unit Price: {}{} has confidence: {}".format( - unit_price.value, unit_price.value.code if unit_price.value.code else "", unit_price.confidence - ) + f"......Unit Price: {unit_price.value}{unit_price_code} has confidence: {unit_price.confidence}" ) product_code = item.value.get("ProductCode") if product_code: print( - "......Product Code: {} has confidence: {}".format( - product_code.value, product_code.confidence - ) + f"......Product Code: {product_code.value} has confidence: {product_code.confidence}" ) item_date = item.value.get("Date") if item_date: print( - "......Date: {} has confidence: {}".format( - item_date.value, item_date.confidence - ) + f"......Date: {item_date.value} has confidence: {item_date.confidence}" ) tax = item.value.get("Tax") if tax: - print( - "......Tax: {} has confidence: {}".format(tax.value, tax.confidence) - ) + print(f"......Tax: {tax.value} has confidence: {tax.confidence}") amount = item.value.get("Amount") if amount: print( - "......Amount: {} has confidence: {}".format( - amount.value, amount.confidence - ) + f"......Amount: {amount.value} has confidence: {amount.confidence}" ) subtotal = invoice.fields.get("SubTotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") total_tax = invoice.fields.get("TotalTax") if total_tax: print( - "Total Tax: {} has confidence: {}".format( - total_tax.value, total_tax.confidence - ) + f"Total Tax: {total_tax.value} has confidence: {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 - ) + f"Previous Unpaid Balance: {previous_unpaid_balance.value} has confidence: {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 - ) + f"Amount Due: {amount_due.value} has confidence: {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 - ) + f"Service Start Date: {service_start_date.value} has confidence: {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 - ) + f"Service End Date: {service_end_date.value} has confidence: {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 - ) + f"Service Address: {service_address.value} has confidence: {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, - ) + f"Service Address Recipient: {service_address_recipient.value} has confidence: {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 - ) + f"Remittance Address: {remittance_address.value} has confidence: {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, - ) + f"Remittance Address Recipient: {remittance_address_recipient.value} has confidence: {remittance_address_recipient.confidence}" ) # [END analyze_invoices] @@ -304,11 +226,14 @@ def analyze_invoice(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_invoice() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_layout.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_layout.py index c00c5aa1914a..9f655a43109b 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_layout.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_layout.py @@ -31,7 +31,7 @@ def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) def analyze_layout(): @@ -60,76 +60,51 @@ def analyze_layout(): ) result = poller.result() - for idx, style in enumerate(result.styles): + for style in result.styles: print( - "Document contains {} content".format( - "handwritten" if style.is_handwritten else "no handwritten" - ) + f"Document contains {'handwritten' if style.is_handwritten else 'no handwritten'} content" ) for page in result.pages: - print("----Analyzing layout from page #{}----".format(page.page_number)) + print(f"----Analyzing layout from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' " + f"within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of {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 - ) + f"Table # {table_idx} has {table.row_count} rows and " + f"{table.column_count} columns" ) for region in table.bounding_regions: print( - "Table # {} location on page: {} is {}".format( - table_idx, - region.page_number, - format_polygon(region.polygon), - ) + f"Table # {table_idx} location on page: {region.page_number} is {format_polygon(region.polygon)}" ) for cell in table.cells: print( - "...Cell[{}][{}] has content '{}'".format( - cell.row_index, - cell.column_index, - cell.content, - ) + f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'" ) for region in cell.bounding_regions: print( - "...content on page {} is within bounding polygon '{}'".format( - region.page_number, - format_polygon(region.polygon), - ) + f"...content on page {region.page_number} is within bounding polygon '{format_polygon(region.polygon)}'" ) print("----------------------------------------") @@ -139,11 +114,14 @@ def analyze_layout(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_layout() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_read.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_read.py index 196177c77c62..e90c0859beb7 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_read.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_read.py @@ -23,15 +23,21 @@ import os + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) + def analyze_read(): path_to_sample_documents = os.path.abspath( @@ -60,57 +66,65 @@ def analyze_read(): print("----Languages detected in the document----") for language in result.languages: - print("Language code: '{}' with confidence {}".format(language.locale, language.confidence)) + print( + f"Language code: '{language.locale}' with confidence {language.confidence}" + ) print("----Styles detected in the document----") for style in result.styles: if style.is_handwritten: print("Found the following handwritten content: ") - print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans])) + print( + ",".join( + [ + result.content[span.offset : span.offset + span.length] + for span in style.spans + ] + ) + ) if style.font_style: - print(f"The document contains '{style.font_style}' font style, applied to the following text: ") - print(",".join([result.content[span.offset:span.offset + span.length] for span in style.spans])) + print( + f"The document contains '{style.font_style}' font style, applied to the following text: " + ) + print( + ",".join( + [ + result.content[span.offset : span.offset + span.length] + for span in style.spans + ] + ) + ) for page in result.pages: - print("----Analyzing document from page #{}----".format(page.page_number)) + print(f"----Analyzing document from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has {} words and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has {len(words)} words and text '{line.content}' within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) for selection_mark in page.selection_marks: print( - "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format( - selection_mark.state, - format_polygon(selection_mark.polygon), - selection_mark.confidence, - ) + f"...Selection mark is '{selection_mark.state}' within bounding polygon " + f"'{format_polygon(selection_mark.polygon)}' and has a confidence of {selection_mark.confidence}" ) if len(result.paragraphs) > 0: - print("----Detected #{} paragraphs in the document----".format(len(result.paragraphs))) + print(f"----Detected #{len(result.paragraphs)} paragraphs in the document----") for paragraph in result.paragraphs: - print("Found paragraph with role: '{}' within {} bounding region".format(paragraph.role, format_bounding_region(paragraph.bounding_regions))) - print("...with content: '{}'".format(paragraph.content)) + print( + f"Found paragraph with role: '{paragraph.role}' within {format_bounding_region(paragraph.bounding_regions)} bounding region" + ) + print(f"...with content: '{paragraph.content}'") print("----------------------------------------") @@ -118,11 +132,14 @@ def analyze_read(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_read() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts.py index 25dfd65e81e4..69da3a02f316 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts.py @@ -54,70 +54,60 @@ def analyze_receipts(): receipts = poller.result() for idx, receipt in enumerate(receipts.documents): - print("--------Analysis of receipt #{}--------".format(idx + 1)) - print("Receipt type: {}".format(receipt.doc_type or "N/A")) + print(f"--------Analysis of receipt #{idx + 1}--------") + print(f"Receipt type: {receipt.doc_type if receipt.doc_type else 'N/A'}") merchant_name = receipt.fields.get("MerchantName") if merchant_name: print( - "Merchant Name: {} has confidence: {}".format( - merchant_name.value, merchant_name.confidence - ) + f"Merchant Name: {merchant_name.value} has confidence: " + f"{merchant_name.confidence}" ) transaction_date = receipt.fields.get("TransactionDate") if transaction_date: print( - "Transaction Date: {} has confidence: {}".format( - transaction_date.value, transaction_date.confidence - ) + f"Transaction Date: {transaction_date.value} has confidence: " + f"{transaction_date.confidence}" ) if receipt.fields.get("Items"): print("Receipt items:") for idx, item in enumerate(receipt.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Item Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Item Description: {item_description.value} has confidence: " + f"{item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Item Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Item Quantity: {item_quantity.value} has confidence: " + f"{item_quantity.confidence}" ) item_price = item.value.get("Price") if item_price: print( - "......Individual Item Price: {} has confidence: {}".format( - item_price.value, item_price.confidence - ) + f"......Individual Item Price: {item_price.value} has confidence: " + f"{item_price.confidence}" ) item_total_price = item.value.get("TotalPrice") if item_total_price: print( - "......Total Item Price: {} has confidence: {}".format( - item_total_price.value, item_total_price.confidence - ) + f"......Total Item Price: {item_total_price.value} has confidence: " + f"{item_total_price.confidence}" ) subtotal = receipt.fields.get("Subtotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") tax = receipt.fields.get("TotalTax") if tax: - print("Total tax: {} has confidence: {}".format(tax.value, tax.confidence)) + print(f"Total tax: {tax.value} has confidence: {tax.confidence}") tip = receipt.fields.get("Tip") if tip: - print("Tip: {} has confidence: {}".format(tip.value, tip.confidence)) + print(f"Tip: {tip.value} has confidence: {tip.confidence}") total = receipt.fields.get("Total") if total: - print("Total: {} has confidence: {}".format(total.value, total.confidence)) + print(f"Total: {total.value} has confidence: {total.confidence}") print("--------------------------------------") # [END analyze_receipts] @@ -125,11 +115,14 @@ def analyze_receipts(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_receipts() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts_from_url.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts_from_url.py index ec5f2eb0eb3e..b9502396e044 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts_from_url.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_receipts_from_url.py @@ -45,70 +45,60 @@ def analyze_receipts_from_url(): receipts = poller.result() for idx, receipt in enumerate(receipts.documents): - print("--------Analysis of receipt #{}--------".format(idx + 1)) - print("Receipt type: {}".format(receipt.doc_type or "N/A")) + print(f"--------Analysis of receipt #{idx + 1}--------") + print(f"Receipt type: {receipt.doc_type if receipt.doc_type else 'N/A'}") merchant_name = receipt.fields.get("MerchantName") if merchant_name: print( - "Merchant Name: {} has confidence: {}".format( - merchant_name.value, merchant_name.confidence - ) + f"Merchant Name: {merchant_name.value} has confidence: " + f"{merchant_name.confidence}" ) transaction_date = receipt.fields.get("TransactionDate") if transaction_date: print( - "Transaction Date: {} has confidence: {}".format( - transaction_date.value, transaction_date.confidence - ) + f"Transaction Date: {transaction_date.value} has confidence: " + f"{transaction_date.confidence}" ) if receipt.fields.get("Items"): print("Receipt items:") for idx, item in enumerate(receipt.fields.get("Items").value): - print("...Item #{}".format(idx + 1)) + print(f"...Item #{idx + 1}") item_description = item.value.get("Description") if item_description: print( - "......Item Description: {} has confidence: {}".format( - item_description.value, item_description.confidence - ) + f"......Item Description: {item_description.value} has confidence: " + f"{item_description.confidence}" ) item_quantity = item.value.get("Quantity") if item_quantity: print( - "......Item Quantity: {} has confidence: {}".format( - item_quantity.value, item_quantity.confidence - ) + f"......Item Quantity: {item_quantity.value} has confidence: " + f"{item_quantity.confidence}" ) item_price = item.value.get("Price") if item_price: print( - "......Individual Item Price: {} has confidence: {}".format( - item_price.value, item_price.confidence - ) + f"......Individual Item Price: {item_price.value} has confidence: " + f"{item_price.confidence}" ) item_total_price = item.value.get("TotalPrice") if item_total_price: print( - "......Total Item Price: {} has confidence: {}".format( - item_total_price.value, item_total_price.confidence - ) + f"......Total Item Price: {item_total_price.value} has confidence: " + f"{item_total_price.confidence}" ) subtotal = receipt.fields.get("Subtotal") if subtotal: - print( - "Subtotal: {} has confidence: {}".format( - subtotal.value, subtotal.confidence - ) - ) + print(f"Subtotal: {subtotal.value} has confidence: {subtotal.confidence}") tax = receipt.fields.get("TotalTax") if tax: - print("Total tax: {} has confidence: {}".format(tax.value, tax.confidence)) + print(f"Total tax: {tax.value} has confidence: {tax.confidence}") tip = receipt.fields.get("Tip") if tip: - print("Tip: {} has confidence: {}".format(tip.value, tip.confidence)) + print(f"Tip: {tip.value} has confidence: {tip.confidence}") total = receipt.fields.get("Total") if total: - print("Total: {} has confidence: {}".format(total.value, total.confidence)) + print(f"Total: {total.value} has confidence: {total.confidence}") print("--------------------------------------") # [END analyze_receipts_from_url] @@ -116,11 +106,14 @@ def analyze_receipts_from_url(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_receipts_from_url() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_tax_us_w2.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_tax_us_w2.py index 198458545b84..dc15358cae11 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_tax_us_w2.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_analyze_tax_us_w2.py @@ -25,8 +25,10 @@ import os + def format_address_value(address_value): - return f'\n......House/building number: {address_value.house_number}\n......Road: {address_value.road}\n......City: {address_value.city}\n......State: {address_value.state}\n......Postal code: {address_value.postal_code}' + return f"\n......House/building number: {address_value.house_number}\n......Road: {address_value.road}\n......City: {address_value.city}\n......State: {address_value.state}\n......Postal code: {address_value.postal_code}" + def analyze_tax_us_w2(): path_to_sample_documents = os.path.abspath( @@ -54,170 +56,131 @@ def analyze_tax_us_w2(): w2s = poller.result() for idx, w2 in enumerate(w2s.documents): - print("--------Analyzing US Tax W-2 Form #{}--------".format(idx + 1)) + print(f"--------Analyzing US Tax W-2 Form #{idx + 1}--------") form_variant = w2.fields.get("W2FormVariant") if form_variant: print( - "Form variant: {} has confidence: {}".format( - form_variant.value, form_variant.confidence - ) + f"Form variant: {form_variant.value} has confidence: " + f"{form_variant.confidence}" ) tax_year = w2.fields.get("TaxYear") if tax_year: - print( - "Tax year: {} has confidence: {}".format( - tax_year.value, tax_year.confidence - ) - ) + print(f"Tax year: {tax_year.value} has confidence: {tax_year.confidence}") w2_copy = w2.fields.get("W2Copy") if w2_copy: - print( - "W-2 Copy: {} has confidence: {}".format( - w2_copy.value, - w2_copy.confidence, - ) - ) + print(f"W-2 Copy: {w2_copy.value} has confidence: {w2_copy.confidence}") employee = w2.fields.get("Employee") if employee: print("Employee data:") employee_name = employee.value.get("Name") if employee_name: - print("...Name: {} has confidence: {}".format( - employee_name.value, employee_name.confidence - ) + print( + f"...Name: {employee_name.value} has confidence: {employee_name.confidence}" ) employee_ssn = employee.value.get("SocialSecurityNumber") if employee_ssn: - print("...SSN: {} has confidence: {}".format( - employee_ssn.value, employee_ssn.confidence - ) + print( + f"...SSN: {employee_ssn.value} has confidence: {employee_ssn.confidence}" ) employee_address = employee.value.get("Address") if employee_address: - print("...Address: {}\n......has confidence: {}".format( - format_address_value(employee_address.value), employee_address.confidence - ) - ) + print(f"...Address: {format_address_value(employee_address.value)}") + print(f"......has confidence: {employee_address.confidence}") employee_zipcode = employee.value.get("ZipCode") if employee_zipcode: - print("...Zipcode: {} has confidence: {}".format( - employee_zipcode.value, employee_zipcode.confidence - ) + print( + f"...Zipcode: {employee_zipcode.value} has confidence: " + f"{employee_zipcode.confidence}" ) control_number = w2.fields.get("ControlNumber") if control_number: print( - "Control Number: {} has confidence: {}".format( - control_number.value, control_number.confidence - ) + f"Control Number: {control_number.value} has confidence: " + f"{control_number.confidence}" ) employer = w2.fields.get("Employer") if employer: print("Employer data:") employer_name = employer.value.get("Name") if employer_name: - print("...Name: {} has confidence: {}".format( - employer_name.value, employer_name.confidence - ) + print( + f"...Name: {employer_name.value} has confidence: {employer_name.confidence}" ) employer_id = employer.value.get("IdNumber") if employer_id: - print("...ID Number: {} has confidence: {}".format( - employer_id.value, employer_id.confidence - ) + print( + f"...ID Number: {employer_id.value} has confidence: {employer_id.confidence}" ) employer_address = employer.value.get("Address") if employer_address: - print("...Address: {}\n......has confidence: {}".format( - format_address_value(employer_address.value), employer_address.confidence - ) - ) + print(f"...Address: {format_address_value(employer_address.value)}") + print(f"\n......has confidence: {employer_address.confidence}") employer_zipcode = employer.value.get("ZipCode") if employer_zipcode: - print("...Zipcode: {} has confidence: {}".format( - employer_zipcode.value, employer_zipcode.confidence - ) + print( + f"...Zipcode: {employer_zipcode.value} has confidence: {employer_zipcode.confidence}" ) wages_tips = w2.fields.get("WagesTipsAndOtherCompensation") if wages_tips: print( - "Wages, tips, and other compensation: {} has confidence: {}".format( - wages_tips.value, - wages_tips.confidence, - ) + f"Wages, tips, and other compensation: {wages_tips.value} " + f"has confidence: {wages_tips.confidence}" ) fed_income_tax_withheld = w2.fields.get("FederalIncomeTaxWithheld") if fed_income_tax_withheld: print( - "Federal income tax withheld: {} has confidence: {}".format( - fed_income_tax_withheld.value, fed_income_tax_withheld.confidence - ) + f"Federal income tax withheld: {fed_income_tax_withheld.value} has " + f"confidence: {fed_income_tax_withheld.confidence}" ) social_security_wages = w2.fields.get("SocialSecurityWages") if social_security_wages: print( - "Social Security wages: {} has confidence: {}".format( - social_security_wages.value, social_security_wages.confidence - ) + f"Social Security wages: {social_security_wages.value} has confidence: " + f"{social_security_wages.confidence}" ) social_security_tax_withheld = w2.fields.get("SocialSecurityTaxWithheld") if social_security_tax_withheld: print( - "Social Security tax withheld: {} has confidence: {}".format( - social_security_tax_withheld.value, social_security_tax_withheld.confidence - ) + f"Social Security tax withheld: {social_security_tax_withheld.value} " + f"has confidence: {social_security_tax_withheld.confidence}" ) medicare_wages_tips = w2.fields.get("MedicareWagesAndTips") if medicare_wages_tips: print( - "Medicare wages and tips: {} has confidence: {}".format( - medicare_wages_tips.value, medicare_wages_tips.confidence - ) + f"Medicare wages and tips: {medicare_wages_tips.value} has confidence: " + f"{medicare_wages_tips.confidence}" ) medicare_tax_withheld = w2.fields.get("MedicareTaxWithheld") if medicare_tax_withheld: print( - "Medicare tax withheld: {} has confidence: {}".format( - medicare_tax_withheld.value, medicare_tax_withheld.confidence - ) + f"Medicare tax withheld: {medicare_tax_withheld.value} has confidence: " + f"{medicare_tax_withheld.confidence}" ) social_security_tips = w2.fields.get("SocialSecurityTips") if social_security_tips: print( - "Social Security tips: {} has confidence: {}".format( - social_security_tips.value, social_security_tips.confidence - ) + f"Social Security tips: {social_security_tips.value} has confidence: " + f"{social_security_tips.confidence}" ) allocated_tips = w2.fields.get("AllocatedTips") if allocated_tips: print( - "Allocated tips: {} has confidence: {}".format( - allocated_tips.value, - allocated_tips.confidence, - ) + f"Allocated tips: {allocated_tips.value} has confidence: {allocated_tips.confidence}" ) verification_code = w2.fields.get("VerificationCode") if verification_code: print( - "Verification code: {} has confidence: {}".format( - verification_code.value, verification_code.confidence - ) + f"Verification code: {verification_code.value} has confidence: {verification_code.confidence}" ) dependent_care_benefits = w2.fields.get("DependentCareBenefits") if dependent_care_benefits: print( - "Dependent care benefits: {} has confidence: {}".format( - dependent_care_benefits.value, - dependent_care_benefits.confidence, - ) + f"Dependent care benefits: {dependent_care_benefits.value} has confidence: {dependent_care_benefits.confidence}" ) non_qualified_plans = w2.fields.get("NonQualifiedPlans") if non_qualified_plans: print( - "Non-qualified plans: {} has confidence: {}".format( - non_qualified_plans.value, - non_qualified_plans.confidence, - ) + f"Non-qualified plans: {non_qualified_plans.value} has confidence: {non_qualified_plans.confidence}" ) additional_info = w2.fields.get("AdditionalInfo") if additional_info: @@ -226,45 +189,32 @@ def analyze_tax_us_w2(): letter_code = item.value.get("LetterCode") if letter_code: print( - "...Letter code: {} has confidence: {}".format( - letter_code.value, letter_code.confidence - ) + f"...Letter code: {letter_code.value} has confidence: {letter_code.confidence}" ) amount = item.value.get("Amount") if amount: print( - "...Amount: {} has confidence: {}".format( - amount.value, amount.confidence - ) + f"...Amount: {amount.value} has confidence: {amount.confidence}" ) is_statutory_employee = w2.fields.get("IsStatutoryEmployee") if is_statutory_employee: print( - "Is statutory employee: {} has confidence: {}".format( - is_statutory_employee.value, is_statutory_employee.confidence - ) + f"Is statutory employee: {is_statutory_employee.value} has confidence: {is_statutory_employee.confidence}" ) is_retirement_plan = w2.fields.get("IsRetirementPlan") if is_retirement_plan: print( - "Is retirement plan: {} has confidence: {}".format( - is_retirement_plan.value, is_retirement_plan.confidence - ) + f"Is retirement plan: {is_retirement_plan.value} has confidence: {is_retirement_plan.confidence}" ) third_party_sick_pay = w2.fields.get("IsThirdPartySickPay") if third_party_sick_pay: print( - "Is third party sick pay: {} has confidence: {}".format( - third_party_sick_pay.value, third_party_sick_pay.confidence - ) + f"Is third party sick pay: {third_party_sick_pay.value} has confidence: {third_party_sick_pay.confidence}" ) other_info = w2.fields.get("Other") if other_info: print( - "Other information: {} has confidence: {}".format( - other_info.value, - other_info.confidence, - ) + f"Other information: {other_info.value} has confidence: {other_info.confidence}" ) state_tax_info = w2.fields.get("StateTaxInfos") if state_tax_info: @@ -272,67 +222,60 @@ def analyze_tax_us_w2(): for tax in state_tax_info.value: state = tax.value.get("State") if state: - print( - "...State: {} has confidence: {}".format( - state.value, state.confidence - ) - ) + print(f"...State: {state.value} has confidence: {state.confidence}") employer_state_id_number = tax.value.get("EmployerStateIdNumber") if employer_state_id_number: print( - "...Employer state ID number: {} has confidence: {}".format( - employer_state_id_number.value, employer_state_id_number.confidence - ) + f"...Employer state ID number: {employer_state_id_number.value} has " + f"confidence: {employer_state_id_number.confidence}" ) - state_wages_tips = tax.value.get("StateWagesTipsEtc") + state_wages_tips = tax.value.get("StateWagesTipsEtc") if state_wages_tips: print( - "...State wages, tips, etc: {} has confidence: {}".format( - state_wages_tips.value, state_wages_tips.confidence - ) + f"...State wages, tips, etc: {state_wages_tips.value} has confidence: " + f"{state_wages_tips.confidence}" ) - state_income_tax = tax.value.get("StateIncomeTax") + state_income_tax = tax.value.get("StateIncomeTax") if state_income_tax: print( - "...State income tax: {} has confidence: {}".format( - state_income_tax.value, state_income_tax.confidence - ) + f"...State income tax: {state_income_tax.value} has confidence: " + f"{state_income_tax.confidence}" ) local_tax_info = w2.fields.get("LocalTaxInfos") if local_tax_info: print("Local Tax info:") for tax in local_tax_info.value: - local_wages_tips = tax.value.get("LocalWagesTipsEtc") + local_wages_tips = tax.value.get("LocalWagesTipsEtc") if local_wages_tips: print( - "...Local wages, tips, etc: {} has confidence: {}".format( - local_wages_tips.value, local_wages_tips.confidence - ) + f"...Local wages, tips, etc: {local_wages_tips.value} has confidence: " + f"{local_wages_tips.confidence}" ) - local_income_tax = tax.value.get("LocalIncomeTax") + local_income_tax = tax.value.get("LocalIncomeTax") if local_income_tax: print( - "...Local income tax: {} has confidence: {}".format( - local_income_tax.value, local_income_tax.confidence - ) + f"...Local income tax: {local_income_tax.value} has confidence: " + f"{local_income_tax.confidence}" ) - locality_name = tax.value.get("LocalityName") + locality_name = tax.value.get("LocalityName") if locality_name: print( - "...Locality name: {} has confidence: {}".format( - locality_name.value, locality_name.confidence - ) + f"...Locality name: {locality_name.value} has confidence: " + f"{locality_name.confidence}" ) if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: analyze_tax_us_w2() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_authentication.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_authentication.py index eb148b789a8b..b9dff863ceca 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_authentication.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_authentication.py @@ -78,7 +78,9 @@ def authentication_with_api_key_credential_document_model_admin_client(): endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, AzureKeyCredential(key) + ) # [END create_dt_client_with_key] info = document_model_admin_client.get_resource_details() @@ -94,7 +96,9 @@ def authentication_with_azure_active_directory_document_model_admin_client(): endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] credential = DefaultAzureCredential() - document_model_admin_client = DocumentModelAdministrationClient(endpoint, credential) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, credential + ) # [END create_dt_client_with_aad] info = document_model_admin_client.get_resource_details() @@ -102,14 +106,17 @@ def authentication_with_azure_active_directory_document_model_admin_client(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: authentication_with_api_key_credential_document_analysis_client() authentication_with_azure_active_directory_document_analysis_client() authentication_with_api_key_credential_document_model_admin_client() authentication_with_azure_active_directory_document_model_admin_client() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_classifier.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_classifier.py index c5668e2c923c..70fd3237684b 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_classifier.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_classifier.py @@ -33,7 +33,7 @@ def sample_build_classifier(): DocumentModelAdministrationClient, ClassifierDocumentTypeDetails, AzureBlobContentSource, - AzureBlobFileListSource + AzureBlobFileListSource, ) from azure.core.credentials import AzureKeyCredential @@ -41,25 +41,25 @@ def sample_build_classifier(): key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CLASSIFIER_CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) # pass either a azure_blob_source or azure_blob_file_list_source poller = document_model_admin_client.begin_build_document_classifier( doc_types={ "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-A/train" + container_url=container_sas_url, prefix="IRS-1040-A/train" ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_file_list_source=AzureBlobFileListSource( - container_url=container_sas_url, - file_list="IRS-1040-D.jsonl" + container_url=container_sas_url, file_list="IRS-1040-D.jsonl" ) ), }, - description="IRS document classifier" + description="IRS document classifier", ) result = poller.result() print(f"Classifier ID: {result.classifier_id}") @@ -68,10 +68,14 @@ def sample_build_classifier(): print(f"Document classes used for training the model:") for doc_type, source in result.doc_types.items(): print(f"Document type: {doc_type}") - blob_source = source.azure_blob_source if source.azure_blob_source else source.azure_blob_file_list_source + blob_source = ( + source.azure_blob_source + if source.azure_blob_source + else source.azure_blob_file_list_source + ) print(f"Container source: {blob_source.container_url}\n") # [END build_classifier] -if __name__ == '__main__': +if __name__ == "__main__": sample_build_classifier() diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_model.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_model.py index cfd813142b5c..681f7cf5c0b3 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_model.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_build_model.py @@ -30,41 +30,54 @@ def sample_build_model(): # [START build_model] - from azure.ai.formrecognizer import DocumentModelAdministrationClient, ModelBuildMode + from azure.ai.formrecognizer import ( + DocumentModelAdministrationClient, + ModelBuildMode, + ) from azure.core.credentials import AzureKeyCredential endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint, AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint, AzureKeyCredential(key) + ) poller = document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=container_sas_url, description="my model description" + ModelBuildMode.TEMPLATE, + blob_container_url=container_sas_url, + description="my model description", ) model = poller.result() - print("Model ID: {}".format(model.model_id)) - print("Description: {}".format(model.description)) - print("Model created on: {}\n".format(model.created_on)) - print("Model expires on: {}\n".format(model.expires_on)) + print(f"Model ID: {model.model_id}") + print(f"Description: {model.description}") + print(f"Model created on: {model.created_on}") + print(f"Model expires on: {model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in model.doc_types.items(): - print("\nDoc Type: '{}' built with '{}' mode which has the following fields:".format(name, doc_type.build_mode)) + print( + f"Doc Type: '{name}' built with '{doc_type.build_mode}' mode which has the following fields:" + ) for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END build_model] -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: sample_build_model() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document.py index d90059d57728..16ceb8d1a729 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document.py @@ -60,22 +60,24 @@ def classify_document(classifier_id): print("----Classified documents----") for doc in result.documents: - print(f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " - f"the following pages: {[region.page_number for region in doc.bounding_regions]}") + print( + f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " + f"the following pages: {[region.page_number for region in doc.bounding_regions]}" + ) # [END classify_document] if __name__ == "__main__": from azure.core.exceptions import HttpResponseError + try: classifier_id = None if os.getenv("CLASSIFIER_CONTAINER_SAS_URL") and not os.getenv("CLASSIFIER_ID"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer import ( DocumentModelAdministrationClient, ClassifierDocumentTypeDetails, - AzureBlobContentSource + AzureBlobContentSource, ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] @@ -91,13 +93,13 @@ def classify_document(classifier_id): "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-A/train" + prefix="IRS-1040-A/train", ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-D/train" + prefix="IRS-1040-D/train", ) ), }, @@ -106,8 +108,10 @@ def classify_document(classifier_id): classifier_id = classifier.classifier_id classify_document(classifier_id) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document_from_url.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document_from_url.py index fdfa796a7384..9b39be3bcffd 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document_from_url.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_classify_document_from_url.py @@ -30,6 +30,7 @@ import os + def classify_document_from_url(classifier_id): # [START classify_document_from_url] from azure.core.credentials import AzureKeyCredential @@ -52,22 +53,24 @@ def classify_document_from_url(classifier_id): print("----Classified documents----") for doc in result.documents: - print(f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " - f"the following pages: {[region.page_number for region in doc.bounding_regions]}") + print( + f"Found document of type '{doc.doc_type or 'N/A'}' with a confidence of {doc.confidence} contained on " + f"the following pages: {[region.page_number for region in doc.bounding_regions]}" + ) # [END classify_document_from_url] -if __name__ == '__main__': +if __name__ == "__main__": from azure.core.exceptions import HttpResponseError + try: classifier_id = None if os.getenv("CLASSIFIER_CONTAINER_SAS_URL") and not os.getenv("CLASSIFIER_ID"): - from azure.core.credentials import AzureKeyCredential from azure.ai.formrecognizer import ( DocumentModelAdministrationClient, ClassifierDocumentTypeDetails, - AzureBlobContentSource + AzureBlobContentSource, ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] @@ -83,13 +86,13 @@ def classify_document_from_url(classifier_id): "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-A/train" + prefix="IRS-1040-A/train", ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( container_url=blob_container_sas_url, - prefix="IRS-1040-D/train" + prefix="IRS-1040-D/train", ) ), }, @@ -98,8 +101,10 @@ def classify_document_from_url(classifier_id): classifier_id = classifier.classifier_id classify_document_from_url(classifier_id) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_compose_model.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_compose_model.py index d60a0ca6bfa9..001779971487 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_compose_model.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_compose_model.py @@ -41,27 +41,40 @@ def sample_compose_model(): # [START composed_model] from azure.core.credentials import AzureKeyCredential - from azure.ai.formrecognizer import DocumentModelAdministrationClient, ModelBuildMode + from azure.ai.formrecognizer import ( + DocumentModelAdministrationClient, + ModelBuildMode, + ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - po_supplies = os.environ['PURCHASE_ORDER_OFFICE_SUPPLIES_SAS_URL'] - po_equipment = os.environ['PURCHASE_ORDER_OFFICE_EQUIPMENT_SAS_URL'] - po_furniture = os.environ['PURCHASE_ORDER_OFFICE_FURNITURE_SAS_URL'] - po_cleaning_supplies = os.environ['PURCHASE_ORDER_OFFICE_CLEANING_SUPPLIES_SAS_URL'] + po_supplies = os.environ["PURCHASE_ORDER_OFFICE_SUPPLIES_SAS_URL"] + po_equipment = os.environ["PURCHASE_ORDER_OFFICE_EQUIPMENT_SAS_URL"] + po_furniture = os.environ["PURCHASE_ORDER_OFFICE_FURNITURE_SAS_URL"] + po_cleaning_supplies = os.environ["PURCHASE_ORDER_OFFICE_CLEANING_SUPPLIES_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) supplies_poller = document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_supplies, description="Purchase order-Office supplies" + ModelBuildMode.TEMPLATE, + blob_container_url=po_supplies, + description="Purchase order-Office supplies", ) equipment_poller = document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_equipment, description="Purchase order-Office Equipment" + ModelBuildMode.TEMPLATE, + blob_container_url=po_equipment, + description="Purchase order-Office Equipment", ) furniture_poller = document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_furniture, description="Purchase order-Furniture" + ModelBuildMode.TEMPLATE, + blob_container_url=po_furniture, + description="Purchase order-Furniture", ) cleaning_supplies_poller = document_model_admin_client.begin_build_document_model( - ModelBuildMode.TEMPLATE, blob_container_url=po_cleaning_supplies, description="Purchase order-Cleaning Supplies" + ModelBuildMode.TEMPLATE, + blob_container_url=po_cleaning_supplies, + description="Purchase order-Cleaning Supplies", ) supplies_model = supplies_poller.result() equipment_model = equipment_poller.result() @@ -72,7 +85,7 @@ def sample_compose_model(): supplies_model.model_id, equipment_model.model_id, furniture_model.model_id, - cleaning_supplies_model.model_id + cleaning_supplies_model.model_id, ] poller = document_model_admin_client.begin_compose_document_model( @@ -81,28 +94,32 @@ def sample_compose_model(): model = poller.result() print("Office Supplies Composed Model Info:") - print("Model ID: {}".format(model.model_id)) - print("Description: {}".format(model.description)) - print("Model created on: {}\n".format(model.created_on)) - print("Model expires on: {}\n".format(model.expires_on)) + print(f"Model ID: {model.model_id}") + print(f"Description: {model.description}") + print(f"Model created on: {model.created_on}") + print(f"Model expires on: {model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in model.doc_types.items(): - print("\nDoc Type: '{}' which has the following fields:".format(name)) + print(f"Doc Type: '{name}' which has the following fields:") for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END composed_model] -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: sample_compose_model() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_convert_to_and_from_dict.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_convert_to_and_from_dict.py index 176e6ad9cf37..dbfd9745daba 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_convert_to_and_from_dict.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_convert_to_and_from_dict.py @@ -25,6 +25,7 @@ import os import json + def convert_to_and_from_dict(): path_to_sample_documents = os.path.abspath( os.path.join( @@ -57,7 +58,7 @@ def convert_to_and_from_dict(): # save the dictionary as JSON content in a JSON file, use the AzureJSONEncoder # to help make types, such as dates, JSON serializable # NOTE: AzureJSONEncoder is only available with azure.core>=1.18.0. - with open('data.json', 'w') as output_file: + with open("data.json", "w") as output_file: json.dump(analyze_result_dict, output_file, cls=AzureJSONEncoder) # convert the dictionary back to the original model @@ -65,9 +66,9 @@ def convert_to_and_from_dict(): # use the model as normal print("----Converted from dictionary AnalyzeResult----") - print("Model ID: '{}'".format(model.model_id)) - print("Number of pages analyzed {}".format(len(model.pages))) - print("API version used: {}".format(model.api_version)) + print(f"Model ID: '{model.model_id}'") + print(f"Number of pages analyzed {len(model.pages)}") + print(f"API version used: {model.api_version}") print("----------------------------------------") @@ -75,11 +76,14 @@ def convert_to_and_from_dict(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: convert_to_and_from_dict() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_copy_model_to.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_copy_model_to.py index f0b0c996a24e..29d6f4b9acc9 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_copy_model_to.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_copy_model_to.py @@ -32,6 +32,7 @@ import os + def sample_copy_model_to(custom_model_id): # [START begin_copy_document_model_to] from azure.core.credentials import AzureKeyCredential @@ -43,61 +44,75 @@ def sample_copy_model_to(custom_model_id): target_key = os.environ["AZURE_FORM_RECOGNIZER_TARGET_KEY"] source_model_id = os.getenv("AZURE_SOURCE_MODEL_ID", custom_model_id) - target_client = DocumentModelAdministrationClient(endpoint=target_endpoint, credential=AzureKeyCredential(target_key)) + target_client = DocumentModelAdministrationClient( + endpoint=target_endpoint, credential=AzureKeyCredential(target_key) + ) target = target_client.get_copy_authorization( description="model copied from other resource" ) - source_client = DocumentModelAdministrationClient(endpoint=source_endpoint, credential=AzureKeyCredential(source_key)) + source_client = DocumentModelAdministrationClient( + endpoint=source_endpoint, credential=AzureKeyCredential(source_key) + ) poller = source_client.begin_copy_document_model_to( model_id=source_model_id, - target=target # output from target client's call to get_copy_authorization() + target=target, # output from target client's call to get_copy_authorization() ) copied_over_model = poller.result() - print("Model ID: {}".format(copied_over_model.model_id)) - print("Description: {}".format(copied_over_model.description)) - print("Model created on: {}\n".format(copied_over_model.created_on)) - print("Model expires on: {}\n".format(copied_over_model.expires_on)) + print(f"Model ID: {copied_over_model.model_id}") + print(f"Description: {copied_over_model.description}") + print(f"Model created on: {copied_over_model.created_on}") + print(f"Model expires on: {copied_over_model.expires_on}") print("Doc types the model can recognize:") for name, doc_type in copied_over_model.doc_types.items(): - print("\nDoc Type: '{}' which has the following fields:".format(name)) + print(f"Doc Type: '{name}' which has the following fields:") for field_name, field in doc_type.field_schema.items(): - print("Field: '{}' has type '{}' and confidence score {}".format( - field_name, field["type"], doc_type.field_confidence[field_name] - )) + print( + f"Field: '{field_name}' has type '{field['type']}' and confidence score " + f"{doc_type.field_confidence[field_name]}" + ) # [END begin_copy_document_model_to] -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: model_id = None if os.getenv("CONTAINER_SAS_URL"): - from azure.core.credentials import AzureKeyCredential - from azure.ai.formrecognizer import DocumentModelAdministrationClient, ModelBuildMode + from azure.ai.formrecognizer import ( + DocumentModelAdministrationClient, + ModelBuildMode, + ) endpoint = os.getenv("AZURE_FORM_RECOGNIZER_SOURCE_ENDPOINT") key = os.getenv("AZURE_FORM_RECOGNIZER_SOURCE_KEY") if not endpoint or not key: - raise ValueError("Please provide endpoint and API key to run the samples.") + raise ValueError( + "Please provide endpoint and API key to run the samples." + ) document_model_admin_client = DocumentModelAdministrationClient( endpoint=endpoint, credential=AzureKeyCredential(key) ) blob_container_sas_url = os.getenv("CONTAINER_SAS_URL") if blob_container_sas_url is not None: - model = document_model_admin_client.begin_build_document_model(ModelBuildMode.TEMPLATE, blob_container_url=blob_container_sas_url).result() + model = document_model_admin_client.begin_build_document_model( + ModelBuildMode.TEMPLATE, blob_container_url=blob_container_sas_url + ).result() model_id = model.model_id sample_copy_model_to(model_id) except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_elements_with_spans.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_elements_with_spans.py index ac3bf26d647a..c2fd88704017 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_elements_with_spans.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_elements_with_spans.py @@ -25,6 +25,7 @@ import os + def get_styles(element_spans, styles): result = [] for span in element_spans: @@ -36,6 +37,7 @@ def get_styles(element_spans, styles): result.append(style) return result + def get_lines(element_spans, document_page): result = [] for span in element_spans: @@ -47,12 +49,14 @@ def get_lines(element_spans, document_page): result.append(line) return result + def get_page(page_number, pages): for page in pages: if page.page_number == page_number: return page raise ValueError("could not find the requested page") + def get_elements_with_spans(): path_to_sample_documents = os.path.abspath( os.path.join( @@ -86,30 +90,24 @@ def get_elements_with_spans(): if result.tables is not None: for table_idx, table in enumerate(result.tables): print( - "Table # {} has {} rows and {} columns".format( - table_idx, table.row_count, table.column_count - ) + f"Table # {table_idx} has {table.row_count} rows and {table.column_count} columns" ) lines = [] if table.bounding_regions is not None: for region in table.bounding_regions: - print( - "Table # {} location on page: {}".format( - table_idx, - region.page_number, + print(f"Table # {table_idx} location on page: {region.page_number}") + lines.extend( + get_lines( + table.spans, get_page(region.page_number, result.pages) ) ) - lines.extend(get_lines(table.spans, get_page(region.page_number, result.pages))) - print("Found # {} lines in the table".format(len(lines))) + print(f"Found # {len(lines)} lines in the table") for line in lines: print( - "...Line '{}' is within bounding polygon: '{}'".format( - line.content, - line.polygon, - ) + f"...Line '{line.content}' is within bounding polygon: '{line.polygon}'" ) # Below is a method to search for the style of a particular element by using spans. @@ -118,31 +116,26 @@ def get_elements_with_spans(): if result.pages[0].lines is not None: for line in result.pages[0].lines: styles = get_styles(line.spans, result.styles) - print( - "Found line '{}' with style:".format( - line.content - ) - ) + print(f"Found line '{line.content}' with style:") if not styles: - print( - "...no handwritten text found" - ) + print("...no handwritten text found") for style in styles: if style.is_handwritten: - print( - "...handwritten with confidence {}".format(style.confidence) - ) + print(f"...handwritten with confidence {style.confidence}") print("----------------------------------------") if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: get_elements_with_spans() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_operations.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_operations.py index a1b3bf294a02..1cecb014b731 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_operations.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_operations.py @@ -34,53 +34,63 @@ def sample_get_operations(): endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) operations = list(document_model_admin_client.list_operations()) print("The following document model operations exist under my resource:") for operation in operations: - print("\nOperation ID: {}".format(operation.operation_id)) - print("Operation kind: {}".format(operation.kind)) - print("Operation status: {}".format(operation.status)) - print("Operation percent completed: {}".format(operation.percent_completed)) - print("Operation created on: {}".format(operation.created_on)) - print("Operation last updated on: {}".format(operation.last_updated_on)) - print("Resource location of successful operation: {}".format(operation.resource_location)) + print(f"\nOperation ID: {operation.operation_id}") + print(f"Operation kind: {operation.kind}") + print(f"Operation status: {operation.status}") + print(f"Operation percent completed: {operation.percent_completed}") + print(f"Operation created on: {operation.created_on}") + print(f"Operation last updated on: {operation.last_updated_on}") + print( + f"Resource location of successful operation: {operation.resource_location}" + ) # [END list_operations] # [START get_operation] # Get an operation by ID if operations: - print("\nGetting operation info by ID: {}".format(operations[0].operation_id)) - operation_info = document_model_admin_client.get_operation(operations[0].operation_id) + print(f"\nGetting operation info by ID: {operations[0].operation_id}") + operation_info = document_model_admin_client.get_operation( + operations[0].operation_id + ) if operation_info.status == "succeeded": - print("My {} operation is completed.".format(operation_info.kind)) + print(f"My {operation_info.kind} operation is completed.") result = operation_info.result if result is not None: if operation_info.kind == "documentClassifierBuild": print(f"Classifier ID: {result.classifier_id}") else: - print("Model ID: {}".format(result.model_id)) + print(f"Model ID: {result.model_id}") elif operation_info.status == "failed": - print("My {} operation failed.".format(operation_info.kind)) + print(f"My {operation_info.kind} operation failed.") error = operation_info.error if error is not None: - print("{}: {}".format(error.code, error.message)) + print(f"{error.code}: {error.message}") else: - print("My operation status is {}".format(operation_info.status)) + print(f"My operation status is {operation_info.status}") else: print("No operations found.") # [END get_operation] -if __name__ == '__main__': + +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: sample_get_operations() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_words_on_document_line.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_words_on_document_line.py index 54721d81f12b..fe33fb74a7b8 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_words_on_document_line.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_get_words_on_document_line.py @@ -24,15 +24,20 @@ import os + def format_bounding_region(bounding_regions): if not bounding_regions: return "N/A" - return ", ".join("Page #{}: {}".format(region.page_number, format_polygon(region.polygon)) for region in bounding_regions) + return ", ".join( + f"Page #{region.page_number}: {format_polygon(region.polygon)}" + for region in bounding_regions + ) + def format_polygon(polygon): if not polygon: return "N/A" - return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon]) + return ", ".join([f"[{p.x}, {p.y}]" for p in polygon]) def get_words_on_document_line(): @@ -60,31 +65,23 @@ def get_words_on_document_line(): ) result = poller.result() - for idx, page in enumerate(result.pages): - print("----Analyzing lines and words from page #{}----".format(idx + 1)) + for page in result.pages: + print(f"----Analyzing lines and words from page #{page.page_number}----") print( - "Page has width: {} and height: {}, measured with unit: {}".format( - page.width, page.height, page.unit - ) + f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}" ) if page.lines is not None: for line_idx, line in enumerate(page.lines): words = line.get_words() print( - "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format( - line_idx, - len(words), - line.content, - format_polygon(line.polygon), - ) + f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' " + f"within bounding polygon '{format_polygon(line.polygon)}'" ) for word in words: print( - "......Word '{}' has a confidence of {}".format( - word.content, word.confidence - ) + f"......Word '{word.content}' has a confidence of {word.confidence}" ) print("----------------------------------------") @@ -93,11 +90,14 @@ def get_words_on_document_line(): if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: get_words_on_document_line() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_classifiers.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_classifiers.py index 51a3c010e102..f38dfbb24c9e 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_classifiers.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_classifiers.py @@ -38,23 +38,23 @@ def sample_manage_classifiers(): key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CLASSIFIER_CONTAINER_SAS_URL"] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) # build a document classifier poller = document_model_admin_client.begin_build_document_classifier( doc_types={ "IRS-1040-A": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-A/train" + container_url=container_sas_url, prefix="IRS-1040-A/train" ) ), "IRS-1040-D": ClassifierDocumentTypeDetails( azure_blob_source=AzureBlobContentSource( - container_url=container_sas_url, - prefix="IRS-1040-D/train" + container_url=container_sas_url, prefix="IRS-1040-D/train" ) - ) + ), }, ) classifier_model = poller.result() @@ -66,35 +66,44 @@ def sample_manage_classifiers(): print("We have the following 'ready' models with IDs and descriptions:") for classifier in classifiers: - print("{} | {}".format(classifier.classifier_id, classifier.description)) + print(f"{classifier.classifier_id} | {classifier.description}") # [END list_document_classifiers] # [START get_document_classifier] - my_classifier = document_model_admin_client.get_document_classifier(classifier_id=classifier_model.classifier_id) - print("\nClassifier ID: {}".format(my_classifier.classifier_id)) - print("Description: {}".format(my_classifier.description)) - print("Classifier created on: {}".format(my_classifier.created_on)) + my_classifier = document_model_admin_client.get_document_classifier( + classifier_id=classifier_model.classifier_id + ) + print(f"\nClassifier ID: {my_classifier.classifier_id}") + print(f"Description: {my_classifier.description}") + print(f"Classifier created on: {my_classifier.created_on}") # [END get_document_classifier] # Finally, we will delete this classifier by ID # [START delete_document_classifier] - document_model_admin_client.delete_document_classifier(classifier_id=my_classifier.classifier_id) + document_model_admin_client.delete_document_classifier( + classifier_id=my_classifier.classifier_id + ) try: - document_model_admin_client.get_document_classifier(classifier_id=my_classifier.classifier_id) + document_model_admin_client.get_document_classifier( + classifier_id=my_classifier.classifier_id + ) except ResourceNotFoundError: - print("Successfully deleted classifier with ID {}".format(my_classifier.classifier_id)) + print(f"Successfully deleted classifier with ID {my_classifier.classifier_id}") # [END delete_document_classifier] -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: sample_manage_classifiers() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: diff --git a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_models.py b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_models.py index f6bdb5df1cc7..3e6f23b66b97 100644 --- a/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_models.py +++ b/sdk/formrecognizer/azure-ai-formrecognizer/samples/v3.2/sample_manage_models.py @@ -28,22 +28,30 @@ def sample_manage_models(): from azure.core.credentials import AzureKeyCredential from azure.core.exceptions import ResourceNotFoundError - from azure.ai.formrecognizer import DocumentModelAdministrationClient, ModelBuildMode + from azure.ai.formrecognizer import ( + DocumentModelAdministrationClient, + ModelBuildMode, + ) endpoint = os.environ["AZURE_FORM_RECOGNIZER_ENDPOINT"] key = os.environ["AZURE_FORM_RECOGNIZER_KEY"] container_sas_url = os.environ["CONTAINER_SAS_URL"] # [START get_resource_details] - document_model_admin_client = DocumentModelAdministrationClient(endpoint=endpoint, credential=AzureKeyCredential(key)) + document_model_admin_client = DocumentModelAdministrationClient( + endpoint=endpoint, credential=AzureKeyCredential(key) + ) account_details = document_model_admin_client.get_resource_details() - print("Our resource has {} custom models, and we can have at most {} custom models".format( - account_details.custom_document_models.count, account_details.custom_document_models.limit - )) + print( + f"Our resource has {account_details.custom_document_models.count} custom models, " + f"and we can have at most {account_details.custom_document_models.limit} custom models" + ) neural_models = account_details.custom_neural_document_model_builds - print(f"The quota limit for custom neural document models is {neural_models.quota} and the resource has" - f"used {neural_models.used}. The resource quota will reset on {neural_models.quota_resets_on}") + print( + f"The quota limit for custom neural document models is {neural_models.quota} and the resource has" + f"used {neural_models.used}. The resource quota will reset on {neural_models.quota_resets_on}" + ) # [END get_resource_details] # Next, we get a paged list of all of our custom models @@ -52,19 +60,23 @@ def sample_manage_models(): print("We have the following 'ready' models with IDs and descriptions:") for model in models: - print("{} | {}".format(model.model_id, model.description)) + print(f"{model.model_id} | {model.description}") # [END list_document_models] # let's build a model to use for this sample - poller = document_model_admin_client.begin_build_document_model(ModelBuildMode.TEMPLATE, blob_container_url=container_sas_url, description="model for sample") + poller = document_model_admin_client.begin_build_document_model( + ModelBuildMode.TEMPLATE, + blob_container_url=container_sas_url, + description="model for sample", + ) model = poller.result() # [START get_document_model] my_model = document_model_admin_client.get_document_model(model_id=model.model_id) - print("\nModel ID: {}".format(my_model.model_id)) - print("Description: {}".format(my_model.description)) - print("Model created on: {}".format(my_model.created_on)) - print("Model expires on: {}".format(my_model.expires_on)) + print(f"\nModel ID: {my_model.model_id}") + print(f"Description: {my_model.description}") + print(f"Model created on: {my_model.created_on}") + print(f"Model expires on: {my_model.expires_on}") # [END get_document_model] # Finally, we will delete this model by ID @@ -74,18 +86,21 @@ def sample_manage_models(): try: document_model_admin_client.get_document_model(model_id=my_model.model_id) except ResourceNotFoundError: - print("Successfully deleted model with ID {}".format(my_model.model_id)) + print(f"Successfully deleted model with ID {my_model.model_id}") # [END delete_document_model] -if __name__ == '__main__': +if __name__ == "__main__": import sys from azure.core.exceptions import HttpResponseError + try: sample_manage_models() except HttpResponseError as error: - print("For more information about troubleshooting errors, see the following guide: " - "https://aka.ms/azsdk/python/formrecognizer/troubleshooting") + print( + "For more information about troubleshooting errors, see the following guide: " + "https://aka.ms/azsdk/python/formrecognizer/troubleshooting" + ) # Examples of how to check an HttpResponseError # Check by error code: if error.error is not None: