Showing posts with label Document Intelligence Studio. Show all posts
Showing posts with label Document Intelligence Studio. Show all posts

Friday, January 24, 2025

Azure AI services - Document intelligence - Extract Data from Forms

 Azure AI services - Document intelligence - Extract Data from Forms:

Source:
https://microsoftlearning.github.io/AI-102-AIEngineer/
https://github.com/MicrosoftLearning/AI-102-AIEngineer

1. Create Azure AI services - Document intelligence in Azure Portal
2. Run Powershell script to create Storage account
3. Train the Model
4. Test the Model 

Required Dlls;
dotnet add package Azure.Core --version 1.44.1
dotnet add package Azure.AI.FormRecognizer --version 4.1.0
dotnet add package Azure.AI.FormRecognizer --version 3.0.0
dotnet add package Tabulate.NET --version 1.0.5

2. Run Powershell script to create Storage account

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

rem Set variable values
set subscription_id=129b2bb6-asdf-asdf-83ba-85bf570bebca
set resource_group=rg1
set location=eastus
set expiry_date=2026-01-01T00:00:00Z

rem Get random numbers to create unique resource names
set unique_id=!random!!random!

rem Create a storage account in your Azure resource group
echo Creating storage...
call az storage account create --name ai102form!unique_id! --subscription !subscription_id! --resource-group !resource_group! --location !location! --sku Standard_LRS --encryption-services blob --default-action Allow --output none --allow-blob-public-access true

echo Uploading files...
rem Get storage key to create a container in the storage account
for /f "tokens=*" %%a in (
'az storage account keys list --subscription !subscription_id! --resource-group !resource_group! --account-name ai102form!unique_id! --query "[?keyName=='key1'].{keyName:keyName, permissions:permissions, value:value}"'
) do (
set key_json=!key_json!%%a
)
set key_string=!key_json:[ { "keyName": "key1", "permissions": "Full", "value": "=!
set AZURE_STORAGE_KEY=!key_string:" } ]=!
rem Create container
call az storage container create --account-name ai102form!unique_id! --name sampleforms --auth-mode key --account-key %AZURE_STORAGE_KEY% --output none
rem Upload files from your local sampleforms folder to a container called sampleforms in the storage account
rem Each file is uploaded as a blob
call az storage blob upload-batch -d sampleforms -s ./sample-forms --account-name ai102form!unique_id! --auth-mode key --account-key %AZURE_STORAGE_KEY%  --output none
rem Set a variable value for future use
set STORAGE_ACCT_NAME=ai102form!unique_id!

rem Get a Shared Access Signature (a signed URI that points to one or more storage resources) for the blobs in sampleforms  
for /f "tokens=*" %%a in (
'az storage container generate-sas --account-name ai102form!unique_id! --name sampleforms --expiry !expiry_date! --permissions rwl'
) do (
set SAS_TOKEN=%%a
set SAS_TOKEN=!SAS_TOKEN:~1,-1!
)
set URI=https://!STORAGE_ACCT_NAME!.blob.core.windows.net/sampleforms?!SAS_TOKEN!

rem Print the generated Shared Access Signature URI, which is used by Azure Storage to authorize access to the storage resource
echo -------------------------------------
echo SAS URI: !URI!


Run the code : dotnet run

OutPut:


3. Train the Model

using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

// import namespaces
using Azure;
using Azure.AI.FormRecognizer;
using Azure.AI.FormRecognizer.Models;
using Azure.AI.FormRecognizer.Training;

namespace train_model
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                // Get configuration settings
                // IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
                // IConfigurationRoot configuration = builder.Build();
                // string formEndpoint = configuration["FormEndpoint"];
                // string formKey = configuration["FormKey"];
                // string trainingStorageUri = configuration["StorageUri"];

                // "YOUR_FORM_RECOGNIZER_ENDPOINT"
                string formEndpoint = "https://a.cognitiveservices.azure.com/";
                // "YOUR_FORM_RECOGNIZER_KEY"
                string formKey = "1E7gEDsZ2pUAiximoBAACYeBjFXJ3w3AAALACOGu5mm";
                // "YOUR_SAS_URI"
                string trainingStorageUri = "https://8IqQY2WOeCJRHTPFg%3D";

                // Authenticate Form Training Client
                var credential = new AzureKeyCredential(formKey);
                var trainingClient = new FormTrainingClient(new Uri(formEndpoint), credential);

                // Train model
                CustomFormModel model = await trainingClient
                .StartTrainingAsync(new Uri(trainingStorageUri), useTrainingLabels: true)
                .WaitForCompletionAsync();

                // Get model info
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"    Model Id: {model.ModelId}");
                Console.WriteLine($"    Model Status: {model.Status}");
                Console.WriteLine($"    Training model started on: {model.TrainingStartedOn}");
                Console.WriteLine($"    Training model completed on: {model.TrainingCompletedOn}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


Run the code : dotnet run

OutPut:


4. Test the Model 

using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

// import namespaces
using Azure;
using Azure.AI.FormRecognizer;
using Azure.AI.FormRecognizer.Models;
using Azure.AI.FormRecognizer.Training;

namespace test_model
{
    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                // Get configuration settings from AppSettings
                // IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
                // IConfigurationRoot configuration = builder.Build();
                // string formEndpoint = configuration["FormEndpoint"];
                // string formKey = configuration["FormKey"];
                // string modelId = configuration["ModelId"];

                // "YOUR_FORM_RECOGNIZER_ENDPOINT";                 string formEndpoint = "https://a.cognitiveservices.azure.com/";
                // "YOUR_FORM_RECOGNIZER_KEY";                 string formKey = "1E7gEDsZ2pUAiximAAALACOGu5mm";
                // "YOUR_MODEL_ID";
                string modelId = "7891e019-9cc2-48a9-a9e6-08ac408484c5";

                // Authenticate Azure AI Document Intelligence Client
                var credential = new AzureKeyCredential(formKey);
                var recognizerClient = new FormRecognizerClient(new Uri(formEndpoint), credential);

                // Get form url for testing  
                string image_file = "test1.jpg";
                using (var image_data = File.OpenRead(image_file))
                {
                    // Use trained model with new form
                    RecognizedFormCollection forms = await recognizerClient
                    .StartRecognizeCustomForms(modelId, image_data)
                    .WaitForCompletionAsync();

                    foreach (RecognizedForm form in forms)
                    {
                        Console.WriteLine($"Form of type: {form.FormType}");
                        foreach (FormField field in form.Fields.Values)
                        {
                            Console.WriteLine($"Field '{field.Name}':");

                            if (field.LabelData != null)
                            {
                                Console.WriteLine($"    Label: '{field.LabelData.Text}'");
                            }

                            Console.WriteLine($"    Value: '{field.ValueData.Text}'");
                            Console.WriteLine($"    Confidence: {field.Confidence}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

OutPut:






Wednesday, January 22, 2025

Azure AI services - Extract form data in Document Intelligence Studio

Azure AI services - Extract form data in Document Intelligence Studio:
C# Code:




using Azure;
using Azure.AI.DocumentIntelligence;
 
public class Program
{
    public static async Task Main(string[] args)
    {
        string endpoint = "https://dir1.cognitiveservices.azure.com/"; // "YOUR_FORM_RECOGNIZER_ENDPOINT";
        string apiKey = "60c7be9d64fa32764c98b6xbx8x9xd6"; //"YOUR_FORM_RECOGNIZER_KEY";
        AzureKeyCredential credential = new AzureKeyCredential(apiKey);
        DocumentIntelligenceClient client = new DocumentIntelligenceClient(new Uri(endpoint), credential);
        Uri receiptUri = new Uri("https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png");
        Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-receipt", receiptUri);
        AnalyzeResult receipts = operation.Value;
        foreach (AnalyzedDocument receipt in receipts.Documents)
        {
            if (receipt.Fields.TryGetValue("MerchantName", out DocumentField merchantNameField))
            {
                if (merchantNameField.FieldType == DocumentFieldType.String)
                {
                    string merchantName = merchantNameField.ValueString;
                    Console.WriteLine($"Merchant Name: '{merchantName}', with confidence {merchantNameField.Confidence}");
                }
            }
            if (receipt.Fields.TryGetValue("TransactionDate", out DocumentField transactionDateField))
            {
                if (transactionDateField.FieldType == DocumentFieldType.Date)
                {
                    DateTimeOffset? transactionDate = transactionDateField.ValueDate;
                    Console.WriteLine($"Transaction Date: '{transactionDate}', with confidence {transactionDateField.Confidence}");
                }
            }
            if (receipt.Fields.TryGetValue("Items", out DocumentField itemsField))
            {
                if (itemsField.FieldType == DocumentFieldType.List)
                {
                    foreach (DocumentField itemField in itemsField.ValueList)
                    {
                        Console.WriteLine("Item:");
                        if (itemField.FieldType == DocumentFieldType.Dictionary)
                        {
                            IReadOnlyDictionary<string, DocumentField> itemFields = itemField.ValueDictionary;
                            if (itemFields.TryGetValue("Description", out DocumentField itemDescriptionField))
                            {
                                if (itemDescriptionField.FieldType == DocumentFieldType.String)
                                {
                                    string itemDescription = itemDescriptionField.ValueString;
 
                                    Console.WriteLine($"  Description: '{itemDescription}', with confidence {itemDescriptionField.Confidence}");
                                }
                            }
                            if (itemFields.TryGetValue("TotalPrice", out DocumentField itemTotalPriceField))
                            {
                                if (itemTotalPriceField.FieldType == DocumentFieldType.Currency)
                                {
                                    double? itemTotalPrice = itemTotalPriceField.ValueCurrency.Amount;
                                    Console.WriteLine($"  Total Price: '{itemTotalPrice}', with confidence {itemTotalPriceField.Confidence}");
                                }
                            }
                        }
                    }
                }
            }
            if (receipt.Fields.TryGetValue("Total", out DocumentField totalField))
            {
                if (totalField.FieldType == DocumentFieldType.Currency)
                {
                    double total = totalField.ValueCurrency.Amount;
 
                    Console.WriteLine($"Total: '{total}', with confidence '{totalField.Confidence}'");
                }
            }
        }
        Console.ReadKey();
    }
}

Output:



Python Code:

# pip install azure-ai-documentintelligence==1.0.0b4
 
from azure.core.credentials import AzureKeyCredential
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.ai.documentintelligence.models import AnalyzeDocumentRequest
 
endpoint = "https://documentintelligence1.cognitiveservices.azure.com/"
key = "8ajYtpyzoJtV0bddxOpfZkmooJJQQJ99BAACYeBjFXJ3w3AAALACOGwbWr"
 
url = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/main/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/receipt/contoso-receipt.png"
 
document_intelligence_client = DocumentIntelligenceClient(
    endpoint = endpoint, credential = AzureKeyCredential(key)
)
 
poller = document_intelligence_client.begin_analyze_document(
    "prebuilt-receipt", AnalyzeDocumentRequest(url_source = url)
)
receipts = poller.result()
 
for idx, receipt in enumerate(receipts.documents):
    print("--------Recognizing receipt #{}--------".format(idx + 1))
    receipt_type = receipt.doc_type
    if receipt_type:
        print(
            "Receipt Type: {}".format(receipt_type)
        )
    merchant_name = receipt.fields.get("MerchantName")
    if merchant_name:
        print(
            "Merchant Name: {} has confidence: {}".format(
                merchant_name.value_string, merchant_name.confidence
            )
        )
    transaction_date = receipt.fields.get("TransactionDate")
    if transaction_date:
        print(
            "Transaction Date: {} has confidence: {}".format(
                transaction_date.value_date, transaction_date.confidence
            )
        )
    if receipt.fields.get("Items"):
        print("Receipt items:")
        for idx, item in enumerate(receipt.fields.get("Items").value_array):
            print("...Item #{}".format(idx + 1))
            item_description = item.value_object.get("Description")
            if item_description:
                print(
                    "......Item Description: {} has confidence: {}".format(
                        item_description.value_string, item_description.confidence
                    )
                )
            item_quantity = item.value_object.get("Quantity")
            if item_quantity:
                print(
                    "......Item Quantity: {} has confidence: {}".format(
                        item_quantity.value_number, item_quantity.confidence
                    )
                )
            item_price = item.value_object.get("Price")
            if item_price:
                print(
                    "......Individual Item Price: {} has confidence: {}".format(
                        item_price.value_currency.amount, item_price.confidence
                    )
                )
            item_total_price = item.value_object.get("TotalPrice")
            if item_total_price:
                print(
                    "......Total Item Price: {} has confidence: {}".format(
                        item_total_price.value_currency.amount, item_total_price.confidence
                    )
                )
    subtotal = receipt.fields.get("Subtotal")
    if subtotal:
        print(
            "Subtotal: {} has confidence: {}".format(
                subtotal.value_currency.amount, subtotal.confidence
            )
        )
    tax = receipt.fields.get("TotalTax")
    if tax:
        print("Tax: {} has confidence: {}".format(tax.value_currency.amount, tax.confidence))
    tip = receipt.fields.get("Tip")
    if tip:
        print("Tip: {} has confidence: {}".format(tip.value_currency.amount, tip.confidence))
    total = receipt.fields.get("Total")
    if total:
        print("Total: {} has confidence: {}".format(total.value_currency.amount, total.confidence))
    print("--------------------------------------")
 
OutPut:



Featured Post

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API

Reassign a Copilot Studio Agent Owner Using PowerShell and the Dataverse Web API Every Copilot Studio agent is a row in the Dataverse bot t...

Popular posts