Search code examples
c#azure-cognitive-servicesazure-form-recognizer

Azure Cognitive services {body} example


I've been playing around with Azure Cognitive services and have been using the sample code provided to analyse a form. I'm unsure what code to use to populate the {body} part of the code. Can anyone share an example of the code I should use in c#? I'm using the new Form Recogniser API however the code would be the same as the Computer Vision API.

I've been able to successfully do it usign Curl but can't get it to work in C#

curl -X POST "https://westus2.api.cognitive.microsoft.com/formrecognizer/v1.0-preview/custom/models/ff956100-613b-40d3-ae74-58e4fcc76384/analyze" -H "Content-Type: multipart/form-data" -F "form=@\"https://recognizermodelxero.blob.core.windows.net/testinvoices/00046266.pdf\";type=application/pdf" -H "Ocp-Apim-Subscription-Key: 1234567890"

Here is what I have tried ...

  byte[] byteData = Encoding.UTF8.GetBytes(System.IO.File.ReadAllText("test.pdf"));

...

namespace CSHttpClientSample
{
    static class Program
    {
        static void Main()
        {
            MakeRequest();
            Console.WriteLine("Hit ENTER to exit...");
            Console.ReadLine();
        }

        static async void MakeRequest()
        {
            var client = new HttpClient();
            var queryString = HttpUtility.ParseQueryString(string.Empty);

            // Request headers
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "{subscription key}");

            // Request parameters
            queryString["keys"] = "{array}";
            var uri = "https://westus2.api.cognitive.microsoft.com/formrecognizer/v1.0-preview/custom/models/{id}/analyze?" + queryString;

            HttpResponseMessage response;

            // Request body
            byte[] byteData = Encoding.UTF8.GetBytes("{body}");

            using (var content = new ByteArrayContent(byteData))
            {
               content.Headers.ContentType = new MediaTypeHeaderValue("< your content type, i.e. application/json >");
               response = await client.PostAsync(uri, content);
            }

        }
    }
}   

I'm after some example code that would be used in place of {body}


Solution

  • Below is the Python sample code to run the form recognizer cognitive service in which for body tag i passed SAS url:

    ########### Python Form Recognizer Train #############
    from requests import post as http_post
    
    # Endpoint URL
    base_url = r"<Endpoint>" + "/formrecognizer/v1.0-preview/custom"
    source = r"<SAS URL>"
    headers = {
        # Request headers
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': '<Subscription Key>',
    }
    url = base_url + "/train" 
    body = {"source": source}
    try:
        resp = http_post(url = url, json = body, headers = headers)
        print("Response status code: %d" % resp.status_code)
        print("Response body: %s" % resp.json())
    except Exception as e:
        print(str(e))
    

    so to answer your question , you can pass SAS in {body} param. Hope it helps.

    Reference

    https://review.learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/python-train-extract?branch=release-build-cogserv-forms-recognizer

    C#:

    Please utilize below method to get the array of byte for {body} Param

    static byte[] GetImageAsByteArray(string imageFilePath)
    
            {
    
                // Open a read-only file stream for the specified file.
    
                using (FileStream fileStream =
    
                    new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
    
                {
    
                    // Read the file's contents into a byte array.
    
                    BinaryReader binaryReader = new BinaryReader(fileStream);
    
                    return binaryReader.ReadBytes((int)fileStream.Length);
    
                }
    
            }