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:



Tuesday, August 20, 2024

Mention a Channel or Team – Power Automate

Mention a Channel or Team – Power Automate

graph.microsoft.com/v1.0/teams/{teamId}/channels/{channelId}/messages

Channel:
----------
{
  "body": {
    "contentType": "html",
    "content": "<at id=\"0\">General</at> This is a channel alert! 🔔"
  },
  "mentions": [
    {
      "id": 0,
      "mentionText": "General",
      "mentioned": {
        "conversation": {
          "id": "@{outputs('ChannelID')}",
          "displayName": "General",
          "@odata.type": "microsoft.graph.teamworkConversationIdentity",
          "conversationIdentityType": "channel"
        }
      }
    }
  ]
}


Team:
----------
{
  "body": {
    "contentType": "html",
    "content": "<at id=\"0\">TheWholeTeam</at> Hello Team! 😉"
  },
  "mentions": [
    {
      "id": 0,
      "mentionText": "TheWholeTeam",
      "mentioned": {
        "conversation": {
          "id": "@{outputs('GroupTeamID')}",
          "displayName": "TheWholeTeam",
          "@odata.type": "microsoft.graph.teamworkConversationIdentity",
          "conversationIdentityType": "team"
        }
      }
    }
  ]
}


https://damobird365.com/mention-a-channel-or-team-power-automate/#:~:text=Via%20Microsoft%20Teams%2C%20you%20can,you%20are%20familiar%20with%20Graph.
https://manish-solanki.com/how-to-mention-a-teams-or-channel-in-channel-message-using-power-automate/

==============================================
Send a Microsoft Graph HTTP request: Adaptive card and MS Teams Mention in same HTTP request.

URL: https://graph.microsoft.com/v1.0/teams/ad538402-ad01-4a18-a6b3-78b6893e40a5/channels/19:9PcW21v4L5Z5IHj60yJ74mS5-Ov50zoWo3sEszQ3R7w1@thread.tacv2/messages

Method: POST

BODY:
{  
    "subject": null,  
    "body": {  
        "contentType": "html",  
        "content": "<attachment id=\"1\"></attachment><at id=\"2\">TestSite</at>"  
    },  
    "attachments": [          {  
            "id": "1",  
            "contentType": "application/vnd.microsoft.card.thumbnail",  
            "contentUrl": null,  
            "content": "{\r\n  \"title\": \" Title @{outputs('Get_user_profile_(V2)_-_User')?['body/displayName']}    !\",\r\n  \"subtitle\": \"<h3>sub title </h3>\",\r\n  \"text\": \" sample text  ; ; ; \r\\n \r\\n   <img src=\\\"@{variables('randomImages')[rand(0, length(variables('randomImages')))]}\\\">   \"}",  
            "name": null,  
            "thumbnailUrl": null  
        }    ],
 "mentions": [      {
      "id": 2,
      "mentionText": "TestSite",
      "mentioned": {
        "conversation": {
          "id": "ad344409-a404-4a58-a673-7286850367a5",
          "displayName": "TestSite",
          "@odata.type": "microsoft.graph.teamworkConversationIdentity",
          "conversationIdentityType": "team"
        }      }    }  ] } 






















































==============================================




Top 6 Most Popular API Architecture Styles

Top 6 Most Popular API Architecture Styles
Source: ByteByteGo



Wednesday, June 19, 2024

Azure Scripts

 Azure Scripts:
Azure > Storage account > File shares > SMB File share
To connect to this Azure file share from Windows, run the PowerShell commands from a normal (not elevated) PowerShell terminal:
$connectTestResult = Test-NetConnection -ComputerName mystorageaccsree.file.core.windows.net -Port 445
if ($connectTestResult.TcpTestSucceeded) {
   
# Save the password so the drive will persist on reboot
 cmd.exe /C "cmdkey /add:`"mystorageaccsree.file.core.windows.net`" /user:`"localhost\mystorageaccsree`" /pass:`"zmKoauV41A9Lt9PUwt+xTSDeQaySe2yfldlhJPVU2gYfY0KWL7VB+OXvtO73WQTUkm7GRXmwC90j+ASt7Vdj/Q==`""
    
# Mount the drive
 New-PSDrive -Name Z -PSProvider FileSystem -Root "\\mystorageaccsree.file.core.windows.net\myfile123" -Persist
} else {  
Write-Error -Message "Unable to reach the Azure storage account via port 445. Check to make sure your organization or ISP is not blocking port 445, or use Azure P2S VPN, Azure S2S VPN, or Express Route to tunnel SMB traffic over a different port."
}
###


###
#AZURE BASH SCRIPT:
#Create a blob storage using CLI:
#az storage account create -n <storage account name> -g <resource group name> -l westus --sku Standard_LRS
az storage account create -n storageaccountsree123 -g rg_eastus_52415_1_171886025677 -l westus --sku Standard_LRS
 
#Create a Container using CLI:
#az storage container create --account-name <storage account name> --name <container name>
az storage container create --account-name storageaccountsree123 --name containersree123
 
#Upload a blob on to storage account:
echo This is a sample html file > sample.html
#az storage blob upload --account-name <storage account name> --container-name <container name> --name sample.html --file sample.html
az storage blob upload --account-name storageaccountsree123 --container-name containersree123 --name sample.html --file sample.html
 
#Give public access to the blob file:
#az storage container set-permission --account-name <storage account name> --name <container name> --public-access blob
az storage container set-permission --account-name storageaccountsree123 --name containersree123 --public-access blob
 
#List and download the blob using CLI:
#az storage blob list --account-name <storage account name> --container-name <container name> --output table
az storage blob list --account-name storageaccountsree123 --container-name containersree123 --output table
 
#az storage blob download --account-name <storage account name> --container-name <container name> --name sample.html --file sample2.html
az storage blob download --account-name storageaccountsree123 --container-name containersree123 --name sample.html --file sample2.html

###

 Azure AZ Copy:
#Download AzCopy and upload your data to Blob storage:
#https://aka.ms/downloadazcopy-v10-windows
azcopy login
 
#azcopy copy "<local-folder-path>" "https://<storage-account-name>.blob.core.windows.net/<container-name>" --recursive=true
azcopy copy "C:\testfolder1" "https://whizstoragesree123.blob.core.windows.net/democontainer" --recursive=true
 
#azcopy sync "<local-folder-path>" "https://<storage-account-name>.blob.core.windows.net/<container-name>" --recursive=true
azcopy sync "C:\testfolder1" "https://whizstoragesree123.blob.core.windows.net/democontainer" --recursive=true
 
#Create a scheduled task:
schtasks /CREATE /SC minute /MO 5 /TN "AzCopy Script" /TR C:\testfolder1\script.bat

###


###
###
###
###
###
###
###
 
 
 

Featured Post

Extract Power Automate Desktop Flow Code from a Solution Export with PowerShell

Reviewing Power Automate Desktop (PAD) flows is harder than reviewing normal code. The logic lives inside the designer, spread across Main a...

Popular posts