Showing posts with label AI. Show all posts
Showing posts with label AI. Show all posts

Friday, June 27, 2025

Create a generative AI app that uses your own data

Create a generative AI app that uses your own data
https://microsoftlearning.github.io/mslearn-ai-studio/Instructions/04-Use-own-data.html

C#:
// rm -r mslearn-ai-foundry -f
// git clone https://github.com/microsoftlearning/mslearn-ai-studio mslearn-ai-foundry
// cd mslearn-ai-foundry/labfiles/rag-app/c-sharp
// dotnet add package Azure.AI.OpenAI
// dotnet run

using System;
using Azure;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Microsoft.Extensions.Configuration;
using Azure.AI.OpenAI;
using System.ClientModel;
using Azure.AI.OpenAI.Chat;
using OpenAI.Chat;

namespace rag_app
{
    class Program
    {
        static void Main(string[] args)
        {
            // Clear the console
            Console.Clear();

            try
            {
// {
//     "OPEN_AI_ENDPOINT": "https://ai-myhub1588559212155.openai.azure.com/",
//     "OPEN_AI_KEY": "31IQTmnEDSqTsGIrEighShdn3VJrFdVF78JD9fgBiPHrcjVy0aG2JQQJ99BF
        ACHYHv6XJ3w3AAAAACOGXGSQ",
//     "CHAT_MODEL": "gpt-4o",
//     "EMBEDDING_MODEL": "text-embedding-ada-002",
//     "SEARCH_ENDPOINT": "https://rg1aisearchservice1.search.windows.net",
//     "SEARCH_KEY": "3JfXmon3dnBbi9UDymp3kmO5fa1cPdGiQDiNG9xjcTAzSeBX8Wkm",
//     "INDEX_NAME": "brochures-index"
// }

                // Get config settings
                IConfigurationBuilder builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json");
                IConfigurationRoot configuration = builder.Build();
                string open_ai_endpoint = configuration["OPEN_AI_ENDPOINT"];
                string open_ai_key = configuration["OPEN_AI_KEY"];
                string chat_model = configuration["CHAT_MODEL"];
                string embedding_model = configuration["EMBEDDING_MODEL"];
                string search_url = configuration["SEARCH_ENDPOINT"];
                string search_key = configuration["SEARCH_KEY"];
                string index_name = configuration["INDEX_NAME"];

                // Get an Azure OpenAI chat client
                AzureOpenAIClient azureClient = new(
                    new Uri(open_ai_endpoint),
                    new AzureKeyCredential(open_ai_key));
                ChatClient chatClient = azureClient.GetChatClient(chat_model);


                // Initialize prompt with system message
                var prompt = new List<ChatMessage>()
                {
                    new SystemChatMessage("You are a travel assistant that provides
                    information on travel services available from Margie's Travel.")
                };

                // Loop until the user types 'quit'
                string input_text = "";
                while (input_text.ToLower() != "quit")
                {
                    // Get user input
                    Console.WriteLine("Enter the prompt (or type 'quit' to exit):");
                    input_text = Console.ReadLine();

                    if (input_text.ToLower() != "quit")
                    {
                        // Add the user input message to the prompt
                        prompt.Add(new UserChatMessage(input_text));

                        // (DataSource is in preview and subject to breaking changes)
                        #pragma warning disable AOAI001

                        // Additional parameters to apply RAG pattern using the
                        AI Search index
                        ChatCompletionOptions options = new();
                        options.AddDataSource(new AzureSearchChatDataSource()
                        {
                            // The following params are used to search the index
                            Endpoint = new Uri(search_url),
                            IndexName = index_name,
                            Authentication = DataSourceAuthentication
                            .FromApiKey(search_key),
                            // The following params are used to vectorize the query
                            QueryType = "vector",
                            VectorizationSource = DataSourceVectorizer
                            .FromDeploymentName(embedding_model),
                        });

                        // Submit the prompt with the data source options and display
                        the response
                        ChatCompletion completion = chatClient.CompleteChat(prompt,
                        options);
                        var completionText = completion.Content[0].Text;
                        Console.WriteLine(completionText);

                        // Add the response to the chat history
                        prompt.Add(new AssistantChatMessage(completionText));

                        #pragma warning restore AOAI001
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


Output:


Python:
# rm -r mslearn-ai-foundry -f
# git clone https://github.com/microsoftlearning/mslearn-ai-studio mslearn-ai-foundry
# cd mslearn-ai-foundry/labfiles/rag-app/python
# python -m venv labenv
# ./labenv/bin/Activate.ps1
# pip install -r requirements.txt openai
# code rag-app.py
# python rag-app.py

import os
from dotenv import load_dotenv
from openai import AzureOpenAI

def main():
    # Clear the console
    os.system('cls' if os.name == 'nt' else 'clear')

# OPEN_AI_ENDPOINT="https://ai-myhub1588559212155.openai.azure.com/"
# OPEN_AI_KEY="31IQTmnEDSqTsGIrEighShdn3VJrFdVF78JD9fgBiPHrcjVy0aG2
    JQQJ99BFACHYHv6XJ3w3AAAAACOGXGSQ"
# CHAT_MODEL="gpt-4o"
# EMBEDDING_MODEL="text-embedding-ada-002"
# SEARCH_ENDPOINT="https://rg1aisearchservice1.search.windows.net"
# SEARCH_KEY="3JfXmon3dnBbi9UDymp3kmO5fa1cPdGiQDiNG9xjcTAzSeBX8Wkm"
# INDEX_NAME="brochures-index"

    try:
        # Get configuration settings
        load_dotenv()
        open_ai_endpoint = os.getenv("OPEN_AI_ENDPOINT")
        open_ai_key = os.getenv("OPEN_AI_KEY")
        chat_model = os.getenv("CHAT_MODEL")
        embedding_model = os.getenv("EMBEDDING_MODEL")
        search_url = os.getenv("SEARCH_ENDPOINT")
        search_key = os.getenv("SEARCH_KEY")
        index_name = os.getenv("INDEX_NAME")

        # Get an Azure OpenAI chat client
        chat_client = AzureOpenAI(
            api_version = "2024-12-01-preview",
            azure_endpoint = open_ai_endpoint,
            api_key = open_ai_key
        )

        # Initialize prompt with system message
        prompt = [
            {"role": "system", "content": "You are a travel assistant that provides
            information on travel services available from Margie's Travel."}
        ]

        # Loop until the user types 'quit'
        while True:
            # Get input text
            input_text = input("Enter the prompt (or type 'quit' to exit): ")
            if input_text.lower() == "quit":
                break
            if len(input_text) == 0:
                print("Please enter a prompt.")
                continue

            # Add the user input message to the prompt
            prompt.append({"role": "user", "content": input_text})

            # Additional parameters to apply RAG pattern using the AI Search index
            rag_params = {
                "data_sources": [
                    {
                        # he following params are used to search the index
                        "type": "azure_search",
                        "parameters": {
                            "endpoint": search_url,
                            "index_name": index_name,
                            "authentication": {
                                "type": "api_key",
                                "key": search_key,
                            },
                            # The following params are used to vectorize the query
                            "query_type": "vector",
                            "embedding_dependency": {
                                "type": "deployment_name",
                                "deployment_name": embedding_model,
                            },
                        }
                    }
                ],
            }

            # Submit the prompt with the data source options and display the response
            response = chat_client.chat.completions.create(
                model=chat_model,
                messages=prompt,
                extra_body=rag_params
            )
            completion = response.choices[0].message.content
            print(completion)

            # Add the response to the chat history
            prompt.append({"role": "assistant", "content": completion})

    except Exception as ex:
        print(ex)

if __name__ == '__main__':
    main()

output:



Tuesday, February 11, 2025

Azure AI services - Detect and Analyze Faces

Azure AI services - Detect and Analyze Faces:

Source: https://github.com/MicrosoftLearning/mslearn-ai-vision

1. Azure AI services multi-service account - Create Azure resource.

Detect Faces:
C# Code:
using System;
using System.Drawing;
using Microsoft.Extensions.Configuration;
using Azure;
using System.IO;

// dotnet add package Azure.AI.Vision.ImageAnalysis -v 1.0.0-beta.3

// Import namespaces
using Azure.AI.Vision.ImageAnalysis;

namespace detect_people
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                // Get config settings from AppSettings
                IConfigurationBuilder builder =
                new ConfigurationBuilder().AddJsonFile("appsettings.json");
                IConfigurationRoot configuration = builder.Build();
                string aiSvcEndpoint =
                "https://sreemultiserviceaccount1.cognitiveservices.azure.com/";
                //configuration["AIServicesEndpoint"];
                string aiSvcKey = "2D9XtWQ0Yfuw3AAAEACOGFMV1"; //configuration["AIServiceKey"];

                // Get image
                string imageFile = "images/people.jpg";
                if (args.Length > 0)
                {
                    imageFile = args[0];
                }

                // Authenticate Azure AI Vision client
                ImageAnalysisClient cvClient = new ImageAnalysisClient(
                    new Uri(aiSvcEndpoint),
                    new AzureKeyCredential(aiSvcKey));

                // Analyze image
                AnalyzeImage(imageFile, cvClient);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        static void AnalyzeImage(string imageFile, ImageAnalysisClient client)
        {
            Console.WriteLine($"\nAnalyzing {imageFile} \n");

            // Use a file stream to pass the image data to the analyze call
            using FileStream stream = new FileStream(imageFile, FileMode.Open);

            // Get result with specified features to be retrieved (PEOPLE)
            ImageAnalysisResult result = client.Analyze(
                BinaryData.FromStream(stream),
                VisualFeatures.People);

            // Close the stream
            stream.Close();

            // Get people in the image
            if (result.People.Values.Count > 0)
            {
                Console.WriteLine($" People:");

                // Prepare image for drawing
                System.Drawing.Image image = System.Drawing.Image.FromFile(imageFile);
                Graphics graphics = Graphics.FromImage(image);
                Pen pen = new Pen(Color.Cyan, 3);

                // Draw bounding box around detected people
                foreach (DetectedPerson person in result.People.Values)
                {
                    if (person.Confidence > 0.5)
                    {
                        // Draw object bounding box
                        var r = person.BoundingBox;
                        Rectangle rect = new Rectangle(r.X, r.Y, r.Width, r.Height);
                        graphics.DrawRectangle(pen, rect);
                    }

                    // Return the confidence of the person detected
                    Console.WriteLine($"   Bounding box {person.BoundingBox.ToString()},
                    Confidence: {person.Confidence:F2}");
                }

                // Save annotated image
                String output_file = "people.jpg";
                image.Save(output_file);
                Console.WriteLine("  Results saved in " + output_file + "\n");
            }
        }
    }
}



OutPut:



Analyze Faces:
C# Code:
using System;
using System.IO;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

// dotnet add package Azure.AI.Vision.Face -v 1.0.0-beta.2

// Import namespaces
using Azure;
using Azure.AI.Vision.Face;

namespace analyze_faces
{
    class Program
    {
        private static FaceClient faceClient;
        static async Task Main(string[] args)
        {
            try
            {
                // Get config settings from AppSettings
                IConfigurationBuilder builder =
                new ConfigurationBuilder().AddJsonFile("appsettings.json");
                IConfigurationRoot configuration = builder.Build();
                string cogSvcEndpoint =
                "https://sreemultiserviceaccount1.cognitiveservices.azure.com/";
                //configuration["AIServicesEndpoint"];
                string cogSvcKey = "2D9XtWQ0Yfuw3AAAEACOGFMV1"; //configuration["AIServiceKey"];

                // Authenticate Face client
                faceClient = new FaceClient(
                    new Uri(cogSvcEndpoint),
                    new AzureKeyCredential(cogSvcKey));

                // Menu for face functions
                Console.WriteLine("1: Detect faces\nAny other key to quit");
                Console.WriteLine("Enter a number:");
                string command = Console.ReadLine();
                switch (command)
                {
                    case "1":
                        await DetectFaces("images/people.jpg");
                        break;
                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        static async Task DetectFaces(string imageFile)
        {
            Console.WriteLine($"Detecting faces in {imageFile}");

            // Specify facial features to be retrieved
            FaceAttributeType[] features = new FaceAttributeType[]
            {
     FaceAttributeType.Detection03.HeadPose,
     FaceAttributeType.Detection03.Blur,
     FaceAttributeType.Detection03.Mask
            };

            // Get faces
            using (var imageData = File.OpenRead(imageFile))
            {
                var response = await faceClient.DetectAsync(
                    BinaryData.FromStream(imageData),
                    FaceDetectionModel.Detection03,
                    FaceRecognitionModel.Recognition04,
                    returnFaceId: false,
                    returnFaceAttributes: features);
                IReadOnlyList<FaceDetectionResult> detected_faces = response.Value;

                if (detected_faces.Count() > 0)
                {
                    Console.WriteLine($"{detected_faces.Count()} faces detected.");

                    // Prepare image for drawing
                    Image image = Image.FromFile(imageFile);
                    Graphics graphics = Graphics.FromImage(image);
                    Pen pen = new Pen(Color.LightGreen, 3);
                    Font font = new Font("Arial", 4);
                    SolidBrush brush = new SolidBrush(Color.White);
                    int faceCount = 0;

                    // Draw and annotate each face
                    foreach (var face in detected_faces)
                    {
                        faceCount++;
                        Console.WriteLine($"\nFace number {faceCount}");

                        // Get face properties
                        Console.WriteLine($" - Head Pose (Yaw): {face.FaceAttributes.HeadPose.Yaw}");
                        Console.WriteLine($" - Head Pose (Pitch):
                        {face.FaceAttributes.HeadPose.Pitch}");
                        Console.WriteLine($" - Head Pose (Roll):
                        {face.FaceAttributes.HeadPose.Roll}");
                        Console.WriteLine($" - Blur: {face.FaceAttributes.Blur.BlurLevel}");
                        Console.WriteLine($" - Mask: {face.FaceAttributes.Mask.Type}");

                        // Draw and annotate face
                        var r = face.FaceRectangle;
                        Rectangle rect = new Rectangle(r.Left, r.Top, r.Width, r.Height);
                        graphics.DrawRectangle(pen, rect);
                        string annotation = $"Face number {faceCount}";
                        graphics.DrawString(annotation, font, brush, r.Left, r.Top);
                    }

                    // Save annotated image
                    String output_file = "detected_faces.jpg";
                    image.Save(output_file);
                    Console.WriteLine(" Results saved in " + output_file);
                }
            }
        }
    }
}


OutPut:



Detect Faces:
Python Code:
from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
import sys
from matplotlib import pyplot as plt
import numpy as np
#pip install azure-ai-vision-imageanalysis==1.0.0b3
# import namespaces
from azure.ai.vision.imageanalysis import ImageAnalysisClient
from azure.ai.vision.imageanalysis.models import VisualFeatures
from azure.core.credentials import AzureKeyCredential

def main():
    global cv_client

    try:
        # Get Configuration Settings
        load_dotenv()
        ai_endpoint = 'https://sreemultiserviceaccount1.cognitiveservices.azure.com/'           #os.getenv('AI_SERVICE_ENDPOINT')
        ai_key = '2D9XtWQ0Yfuw3AAAEACOGFMV1' #os.getenv('AI_SERVICE_KEY')

        # Get image
        image_file = 'images/people.jpg'
        if len(sys.argv) > 1:
            image_file = sys.argv[1]

        with open(image_file, "rb") as f:
            image_data = f.read()

         # Authenticate Azure AI Vision client
        cv_client = ImageAnalysisClient(
            endpoint=ai_endpoint,
            credential=AzureKeyCredential(ai_key)
        )
       
        # Analyze image
        AnalyzeImage(image_file, image_data, cv_client)

    except Exception as ex:
        print(ex)

def AnalyzeImage(filename, image_data, cv_client):
    print('\nAnalyzing ', filename)

     # Get result with specified features to be retrieved (PEOPLE)
    result = cv_client.analyze(
         image_data=image_data,
        visual_features=[
             VisualFeatures.PEOPLE],
    )
   
    # Identify people in the image
    if result.people is not None:
        print("\nPeople in image:")

        # Prepare image for drawing
        image = Image.open(filename)
        fig = plt.figure(figsize=(image.width/100, image.height/100))
        plt.axis('off')
        draw = ImageDraw.Draw(image)
        color = 'cyan'

         # Draw bounding box around detected people
        for detected_people in result.people.list:
            if(detected_people.confidence > 0.5):
                 # Draw object bounding box
                r = detected_people.bounding_box
                bounding_box = ((r.x, r.y), (r.x + r.width, r.y + r.height))
                draw.rectangle(bounding_box, outline=color, width=3)

                # Return the confidence of the person detected
                print(" {} (confidence: {:.2f}%)".format(detected_people.bounding_box,
                detected_people.confidence * 100))

        # Save annotated image
        plt.imshow(image)
        plt.tight_layout(pad=0)
        outputfile = 'people.jpg'
        fig.savefig(outputfile)
        print('  Results saved in', outputfile)

if __name__ == "__main__":
    main()

OutPut:




Analyze Faces:
Python Code:
from dotenv import load_dotenv
import os
from PIL import Image, ImageDraw
from matplotlib import pyplot as plt

#pip install azure-cognitiveservices-vision-face==0.6.0

# Import namespaces
from azure.cognitiveservices.vision.face import FaceClient
from azure.cognitiveservices.vision.face.models import FaceAttributeType
from msrest.authentication import CognitiveServicesCredentials

def main():
    global face_client

    try:
        # Get Configuration Settings
        load_dotenv()
        # cog_endpoint = os.getenv('AI_SERVICE_ENDPOINT')
        # cog_key = os.getenv('AI_SERVICE_KEY')
       
        cog_endpoint = 'https://sreemultiserviceaccount1.cognitiveservices.azure.com/'
        cog_key ='2D9XtWQ0Yfuw3AAAEACOGFMV1'

        # Authenticate Face client
        credentials = CognitiveServicesCredentials(cog_key)
        face_client = FaceClient(cog_endpoint, credentials)

        # Menu for face functions
        print('1: Detect faces\nAny other key to quit')
        command = input('Enter a number:')
        if command == '1':
            DetectFaces(os.path.join('images','people.jpg'))

    except Exception as ex:
        print(ex)

def DetectFaces(image_file):
    print('Detecting faces in', image_file)

    # Specify facial features to be retrieved
    features = [
        FaceAttributeType.occlusion,
        FaceAttributeType.blur,
        FaceAttributeType.glasses
    ]

    # Get faces
    with open(image_file, mode="rb") as image_data:
        detected_faces = face_client.face.detect_with_stream(
        image=image_data,
        return_face_attributes=features,
        return_face_id=False
    )

    if len(detected_faces) > 0:
        print(len(detected_faces), 'faces detected.')

        # Prepare image for drawing
        fig = plt.figure(figsize=(8, 6))
        plt.axis('off')
        image = Image.open(image_file)
        draw = ImageDraw.Draw(image)
        color = 'lightgreen'
        face_count = 0

        # Draw and annotate each face
        for face in detected_faces:
            # Get face properties
            face_count += 1
            print('\nFace number {}'.format(face_count))
            detected_attributes = face.face_attributes.as_dict()

            if 'blur' in detected_attributes:
                print(' - Blur:')
                for blur_name in detected_attributes['blur']:
                    print('   - {}: {}'.format(blur_name, detected_attributes['blur'][blur_name]))

            if 'occlusion' in detected_attributes:
                print(' - Occlusion:')
                for occlusion_name in detected_attributes['occlusion']:
                    print('   - {}: {}'.format(occlusion_name,                         detected_attributes['occlusion'][occlusion_name]))

            if 'glasses' in detected_attributes:
                print(' - Glasses: {}'.format(detected_attributes['glasses']))

            # Draw and annotate face
            r = face.face_rectangle
            bounding_box = ((r.left, r.top), (r.left + r.width, r.top + r.height))
            draw.rectangle(bounding_box, outline=color, width=5)
            annotation = 'Face number {}'.format(face_count)
            plt.annotate(annotation, (r.left, r.top), backgroundcolor=color)

        # Save annotated image
        plt.imshow(image)
        outputfile = 'detected_faces.jpg'
        fig.savefig(outputfile)
        print('\nResults saved in', outputfile)

if __name__ == "__main__":
    main()

OutPut:








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:






Featured Post

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide Version: July 2026 | Audience: Beginners, Citizen Developers, Busine...

Popular posts