public void StartTrainingArgumentValidation()
        {
            FormTrainingClient client = CreateInstrumentedClient();

            Assert.ThrowsAsync <UriFormatException>(() => client.StartTrainingAsync(new Uri(string.Empty), useTrainingLabels: false));
            Assert.ThrowsAsync <ArgumentNullException>(() => client.StartTrainingAsync((Uri)null, useTrainingLabels: false));
        }
        private static async Task <string> TrainModelWithLabelsAsync(
            FormTrainingClient trainingClient, string trainingFileUrl)
        {
            CustomFormModel model = await trainingClient
                                    .StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : true).WaitForCompletionAsync();

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"    Model Id: {model.ModelId}");
            Console.WriteLine($"    Model Status: {model.Status}");
            Console.WriteLine($"    Requested on: {model.TrainingStartedOn}");
            Console.WriteLine($"    Completed on: {model.TrainingCompletedOn}");
            foreach (CustomFormSubmodel submodel in model.Submodels)
            {
                Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
                foreach (CustomFormModelField field in submodel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Accuracy != null)
                    {
                        Console.Write($", Accuracy: {field.Accuracy}");
                    }
                    Console.WriteLine("");
                }
            }
            return(model.ModelId);
        }
        public async Task OutputModelsTrainedWithoutLabels()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;
            string formFilePath    = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg");

            FormRecognizerClient client         = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            FormTrainingClient   trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Model trained without labels
            CustomFormModel modelTrainedWithoutLabels = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false).WaitForCompletionAsync();

            using (FileStream stream = new FileStream(formFilePath, FileMode.Open))
            {
                RecognizedFormCollection forms = await client.StartRecognizeCustomFormsAsync(modelTrainedWithoutLabels.ModelId, stream).WaitForCompletionAsync();

                // With a form recognized by a model trained without labels, the 'field.Name' property will be denoted
                // by a numeric index. To look for the labels identified during the training step,
                // use the `field.LabelText` property.
                Console.WriteLine("---------Recognizing forms using models trained without labels---------");
                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}");
                    }
                }

                // Find the value of unlabeled fields.
                foreach (RecognizedForm form in forms)
                {
                    // Find the value of a specific unlabeled field.
                    Console.WriteLine("Find the value for a specific unlabeled field:");
                    foreach (FormField field in form.Fields.Values)
                    {
                        if (field.LabelData != null && field.LabelData.Text == "Vendor Name:")
                        {
                            Console.WriteLine($"The Vendor Name is {field.ValueData.Text}");
                        }
                    }

                    // Find the value of unlabeled fields with specific words
                    Console.WriteLine("Find the value for labeled field with specific words:");
                    form.Fields.Values.Where(field => field.LabelData.Text.StartsWith("Ven"))
                    .ToList().ForEach(v => Console.WriteLine($"{v.LabelData.Text} is {v.ValueData.Text}"));
                    form.Fields.Values.Where(field => field.LabelData.Text.Contains("Name"))
                    .ToList().ForEach(v => Console.WriteLine($"{v.LabelData.Text} is {v.ValueData.Text}"));
                }
            }
        }
        public async Task ManageCustomModelsAsync()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            #region Snippet:FormRecognizerSampleManageCustomModelsAsync

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Check number of models in the FormRecognizer account, and the maximum number of models that can be stored.
            AccountProperties accountProperties = await client.GetAccountPropertiesAsync();

            Console.WriteLine($"Account has {accountProperties.CustomModelCount} models.");
            Console.WriteLine($"It can have at most {accountProperties.CustomModelLimit} models.");

            // List the models currently stored in the account.
            AsyncPageable <CustomFormModelInfo> models = client.GetCustomModelsAsync();

            await foreach (CustomFormModelInfo modelInfo in models)
            {
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"    Model Id: {modelInfo.ModelId}");
                Console.WriteLine($"    Model name: {modelInfo.ModelName}");
                Console.WriteLine($"    Is composed model: {modelInfo.Properties.IsComposedModel}");
                Console.WriteLine($"    Model Status: {modelInfo.Status}");
                Console.WriteLine($"    Training model started on: {modelInfo.TrainingStartedOn}");
                Console.WriteLine($"    Training model completed on: : {modelInfo.TrainingCompletedOn}");
            }

            // Create a new model to store in the account
            CustomFormModel model = await client.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false, new TrainingOptions()
            {
                ModelName = "My new model"
            }).WaitForCompletionAsync();

            // Get the model that was just created
            CustomFormModel modelCopy = await client.GetCustomModelAsync(model.ModelId);

            Console.WriteLine($"Custom Model with Id {modelCopy.ModelId}  and name {modelCopy.ModelName} recognizes the following form types:");

            foreach (CustomFormSubmodel submodel in modelCopy.Submodels)
            {
                Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
                foreach (CustomFormModelField field in submodel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Label != null)
                    {
                        Console.Write($", FieldLabel: {field.Label}");
                    }
                    Console.WriteLine("");
                }
            }

            // Delete the model from the account.
            await client.DeleteModelAsync(model.ModelId);

            #endregion
        }
예제 #5
0
        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"];

                // 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 : false)
                                        .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);
            }
        }
    // </snippet_receipt_print>

    // <snippet_train>
    private static async Task <String> TrainModel(
        FormTrainingClient trainingClient, string trainingDataUrl)
    {
        CustomFormModel model = await trainingClient
                                .StartTrainingAsync(new Uri(trainingDataUrl), useTrainingLabels : false)
                                .WaitForCompletionAsync();

        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}");
        // </snippet_train>
        // <snippet_train_response>
        foreach (CustomFormSubmodel submodel in model.Submodels)
        {
            Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
            foreach (CustomFormModelField field in submodel.Fields.Values)
            {
                Console.Write($"    FieldName: {field.Name}");
                if (field.Label != null)
                {
                    Console.Write($", FieldLabel: {field.Label}");
                }
                Console.WriteLine("");
            }
        }
        // </snippet_train_response>
        // <snippet_train_return>
        return(model.ModelId);
    }
예제 #7
0
        public async Task RecognizeCustomFormsFromUri()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            // Firstly, create a trained model we can use to recognize the custom form. Please note that
            // models can also be trained using a graphical user interface such as the Form Recognizer
            // Labeling Tool found here:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/label-tool

            FormTrainingClient trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model          = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false, "My Model").WaitForCompletionAsync();

            // Proceed with the custom form recognition.

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:FormRecognizerSampleRecognizeCustomFormsFromUri
#if SNIPPET
            string modelId = "<modelId>";
            Uri    formUri = < formUri >;
#else
            Uri    formUri = FormRecognizerTestEnvironment.CreateUri("Form_1.jpg");
            string modelId = model.ModelId;
#endif

            RecognizeCustomFormsOperation operation = await client.StartRecognizeCustomFormsFromUriAsync(modelId, formUri);

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection forms = operationResponse.Value;

            foreach (RecognizedForm form in forms)
            {
                Console.WriteLine($"Form of type: {form.FormType}");
                if (form.FormTypeConfidence.HasValue)
                {
                    Console.WriteLine($"Form type confidence: {form.FormTypeConfidence.Value}");
                }
                Console.WriteLine($"Form was analyzed with model with ID: {form.ModelId}");
                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}'");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await trainingClient.DeleteModelAsync(model.ModelId);
        }
예제 #8
0
        public async Task TrainModelWithFormsAndLabels()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleTrainModelWithFormsAndLabels
            // For this sample, you can use the training forms found in the `trainingFiles` folder.
            // Upload the forms to your storage container and then generate a container SAS URL. Note
            // that a container URI without SAS is accepted only when the container is public or has a
            // managed identity configured.
            //
            // For instructions to set up forms for training in an Azure Blob Storage Container, please see:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set#upload-your-training-data

            // For instructions to create a label file for your training forms, please see:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/label-tool?tabs=v2-1

#if SNIPPET
            Uri trainingFileUri = new Uri("<trainingFileUri>");
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrlV2);
#endif
            string             modelName = "My Model with labels";
            FormTrainingClient client    = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            TrainingOperation operation = await client.StartTrainingAsync(trainingFileUri, useTrainingLabels : true, modelName);

            Response <CustomFormModel> operationResponse = await operation.WaitForCompletionAsync();

            CustomFormModel model = operationResponse.Value;

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"  Model Id: {model.ModelId}");
            Console.WriteLine($"  Model name: {model.ModelName}");
            Console.WriteLine($"  Model Status: {model.Status}");
            Console.WriteLine($"  Is composed model: {model.Properties.IsComposedModel}");
            Console.WriteLine($"  Training model started on: {model.TrainingStartedOn}");
            Console.WriteLine($"  Training model completed on: {model.TrainingCompletedOn}");

            foreach (CustomFormSubmodel submodel in model.Submodels)
            {
                Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
                foreach (CustomFormModelField field in submodel.Fields.Values)
                {
                    Console.Write($"  FieldName: {field.Name}");
                    if (field.Accuracy != null)
                    {
                        Console.Write($", Accuracy: {field.Accuracy}");
                    }
                    Console.WriteLine("");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await client.DeleteModelAsync(model.ModelId);
        }
예제 #9
0
        public async Task OutputModelsTrainedWithLabels()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;
            string formFilePath    = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg");

            FormRecognizerClient client         = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            FormTrainingClient   trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Model trained with labels
            CustomFormModel modelTrainedWithLabels = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : true, new TrainingOptions()
            {
                ModelDisplayName = "My Model with labels"
            }).WaitForCompletionAsync();

            using (FileStream stream = new FileStream(formFilePath, FileMode.Open))
            {
                RecognizedFormCollection forms = await client.StartRecognizeCustomFormsAsync(modelTrainedWithLabels.ModelId, stream).WaitForCompletionAsync();

                // With a form recognized by a model trained with labels, the 'field.Name' key will be the label
                // that you gave it at training time.
                // Note that Label data is not returned for model trained with labels, as the trained model
                // contains this information and therefore the service returns the value of the recognized label.
                Console.WriteLine("---------Recognizing forms using models trained with labels---------");
                foreach (RecognizedForm form in forms)
                {
                    Console.WriteLine($"Form of type: {form.FormType}");
                    Console.WriteLine($"Form has form type confidence: {form.FormTypeConfidence.Value}");
                    Console.WriteLine($"Form was analyzed with model with ID: {form.ModelId}");
                    foreach (FormField field in form.Fields.Values)
                    {
                        Console.WriteLine($"Field {field.Name}: ");
                        Console.WriteLine($"    Value: '{field.ValueData.Text}");
                        Console.WriteLine($"    Confidence: '{field.Confidence}");
                    }
                }

                // Find labeled field.
                foreach (RecognizedForm form in forms)
                {
                    // Find the specific labeled field.
                    Console.WriteLine("Find the value for a specific labeled field:");
                    if (form.Fields.TryGetValue("VendorName", out FormField field))
                    {
                        Console.WriteLine($"VendorName is {field.ValueData.Text}");
                    }

                    // Find labeled fields with specific words
                    Console.WriteLine("Find the value for labeled field with specific words:");
                    form.Fields.Where(kv => kv.Key.StartsWith("Ven"))
                    .ToList().ForEach(v => Console.WriteLine($"{v.Key} is {v.Value.ValueData.Text}"));
                    form.Fields.Where(kv => kv.Key.Contains("Name"))
                    .ToList().ForEach(v => Console.WriteLine($"{v.Key} is {v.Value.ValueData.Text}"));
                }
            }
        }
        public override async Task SetupAsync()
        {
            var trainingClient = new FormTrainingClient(new Uri(Endpoint), new AzureKeyCredential(ApiKey));
            var op             = await trainingClient.StartTrainingAsync(new Uri(BlobContainerSasUrl), useTrainingLabels : false);

            CustomFormModel model = await op.WaitForCompletionAsync();

            _modelId = model.ModelId;
        }
        public async Task CopyModel()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            Uri    trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
            string resourceId      = TestEnvironment.TargetResourceId;
            string resourceRegion  = TestEnvironment.TargetResourceRegion;

            #region Snippet:FormRecognizerSampleCreateCopySourceClient
            //@@ string endpoint = "<source_endpoint>";
            //@@ string apiKey = "<source_apiKey>";
            var sourcecredential = new AzureKeyCredential(apiKey);
            var sourceClient     = new FormTrainingClient(new Uri(endpoint), sourcecredential);
            #endregion

            // For the purpose of this sample, we are going to create a trained model to copy. Please note that
            // if you already have a model, this is not necessary.
            //@@ Uri trainingFileUri = <trainingFileUri>;
            TrainingOperation operation = await sourceClient.StartTrainingAsync(trainingFileUri, useTrainingLabels : false);

            Response <CustomFormModel> operationResponse = await operation.WaitForCompletionAsync();

            CustomFormModel model = operationResponse.Value;

            string modelId = model.ModelId;

            #region Snippet:FormRecognizerSampleCreateCopyTargetClient
            //@@ string endpoint = "<target_endpoint>";
            //@@ string apiKey = "<target_apiKey>";
            var targetCredential = new AzureKeyCredential(apiKey);
            var targetClient     = new FormTrainingClient(new Uri(endpoint), targetCredential);
            #endregion

            #region Snippet:FormRecognizerSampleGetCopyAuthorization
            //@@ string resourceId = "<resourceId>";
            //@@ string resourceRegion = "<region>";
            CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync(resourceId, resourceRegion);

            #endregion

            #region Snippet:FormRecognizerSampleToJson
            string jsonTargetAuth = targetAuth.ToJson();
            #endregion

            #region Snippet:FormRecognizerSampleFromJson
            CopyAuthorization targetCopyAuth = CopyAuthorization.FromJson(jsonTargetAuth);
            #endregion

            #region Snippet:FormRecognizerSampleCopyModel
            //@@ string modelId = "<source_modelId>";
            CustomFormModelInfo newModel = await sourceClient.StartCopyModelAsync(modelId, targetCopyAuth).WaitForCompletionAsync();

            Console.WriteLine($"Original model ID => {modelId}");
            Console.WriteLine($"Copied model ID => {newModel.ModelId}");
            #endregion
        }
    // </snippet_analyze_response>

    // <snippet_manage>
    private static async Task ManageModels(
        FormTrainingClient trainingClient, string trainingFileUrl)
    {
        // </snippet_manage>
        // <snippet_manage_model_count>
        // Check number of models in the FormRecognizer account,
        // and the maximum number of models that can be stored.
        AccountProperties accountProperties = trainingClient.GetAccountProperties();

        Console.WriteLine($"Account has {accountProperties.CustomModelCount} models.");
        Console.WriteLine($"It can have at most {accountProperties.CustomModelLimit} models.");
        // </snippet_manage_model_count>

        // <snippet_manage_model_list>
        Pageable <CustomFormModelInfo> models = trainingClient.GetCustomModels();

        foreach (CustomFormModelInfo modelInfo in models)
        {
            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"    Model Id: {modelInfo.ModelId}");
            Console.WriteLine($"    Model Status: {modelInfo.Status}");
            Console.WriteLine($"    Training model started on: {modelInfo.TrainingStartedOn}");
            Console.WriteLine($"    Training model completed on: {modelInfo.TrainingCompletedOn}");
        }
        // </snippet_manage_model_list>

        // <snippet_manage_model_get>
        // Create a new model to store in the account
        CustomFormModel model = await trainingClient.StartTrainingAsync(
            new Uri(trainingFileUrl)).WaitForCompletionAsync();

        // Get the model that was just created
        CustomFormModel modelCopy = trainingClient.GetCustomModel(model.ModelId);

        Console.WriteLine($"Custom Model {modelCopy.ModelId} recognizes the following form types:");

        foreach (CustomFormSubmodel submodel in modelCopy.Submodels)
        {
            Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
            foreach (CustomFormModelField field in submodel.Fields.Values)
            {
                Console.Write($"    FieldName: {field.Name}");
                if (field.Label != null)
                {
                    Console.Write($", FieldLabel: {field.Label}");
                }
                Console.WriteLine("");
            }
        }
        // </snippet_manage_model_get>

        // <snippet_manage_model_delete>
        // Delete the model from the account.
        trainingClient.DeleteModel(model.ModelId);
    }
        public async Task ManageCustomModels()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            #region Snippet:FormRecognizerSample6ManageCustomModels

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Check number of models in the FormRecognizer account, and the maximum number of models that can be stored.
            AccountProperties accountProperties = client.GetAccountProperties();
            Console.WriteLine($"Account has {accountProperties.CustomModelCount} models.");
            Console.WriteLine($"It can have at most {accountProperties.CustomModelLimit} models.");

            // List the first ten or fewer models currently stored in the account.
            Pageable <CustomFormModelInfo> models = client.GetCustomModels();

            foreach (CustomFormModelInfo modelInfo in models.Take(10))
            {
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"    Model Id: {modelInfo.ModelId}");
                Console.WriteLine($"    Model Status: {modelInfo.Status}");
                Console.WriteLine($"    Created On: {modelInfo.CreatedOn}");
                Console.WriteLine($"    Last Modified: {modelInfo.LastModified}");
            }

            // Create a new model to store in the account
            CustomFormModel model = await client.StartTrainingAsync(new Uri(trainingFileUrl)).WaitForCompletionAsync();

            // Get the model that was just created
            CustomFormModel modelCopy = client.GetCustomModel(model.ModelId);

            Console.WriteLine($"Custom Model {modelCopy.ModelId} recognizes the following form types:");

            foreach (CustomFormSubModel subModel in modelCopy.Models)
            {
                Console.WriteLine($"SubModel Form Type: {subModel.FormType}");
                foreach (CustomFormModelField field in subModel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Label != null)
                    {
                        Console.Write($", FieldLabel: {field.Label}");
                    }
                    Console.WriteLine("");
                }
            }

            // Delete the model from the account.
            client.DeleteModel(model.ModelId);

            #endregion
        }
        /// <summary>
        ///  For testing purposes, we are training our models using the client library functionalities.
        ///  Please note that models can also be trained using a graphical user interface
        ///  such as the Form Recognizer Labeling Tool found here:
        ///  <a href="https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/label-tool"/>.
        /// </summary>
        private async Task <string> GetModelIdAsync(bool useLabels = false)
        {
            FormTrainingClient trainingClient = InstrumentClient(new FormTrainingClient(_endpoint, _credential));
            TrainingOperation  trainedModel   = await trainingClient.StartTrainingAsync(_containerUri, useLabels);

            await trainedModel.WaitForCompletionAsync();

            Assert.IsTrue(trainedModel.HasValue);

            return(trainedModel.Value.ModelId);
        }
예제 #15
0
        /// <summary>
        /// Trains a model using the specified <see cref="FormTrainingClient"/> and the specified set of training files. A
        /// <see cref="DisposableTrainedModel"/> instance is returned, from which the model ID can be obtained. Upon disposal,
        /// the associated model will be deleted.
        /// </summary>
        /// <param name="trainingClient">The client to use for training and for deleting the model upon disposal.</param>
        /// <param name="trainingFilesUri">An externally accessible Azure storage blob container Uri.</param>
        /// <param name="useTrainingLabels">If <c>true</c>, use a label file created in the &lt;link-to-label-tool-doc&gt; to provide training-time labels for training a model. If <c>false</c>, the model will be trained from forms only.</param>
        /// <param name="modelName">Optional model name.</param>
        /// <returns>A <see cref="DisposableTrainedModel"/> instance from which the trained model ID can be obtained.</returns>
        public static async Task <DisposableTrainedModel> TrainModelAsync(FormTrainingClient trainingClient, Uri trainingFilesUri, bool useTrainingLabels, string modelName = default)
        {
            TrainingOperation operation = await trainingClient.StartTrainingAsync(trainingFilesUri, useTrainingLabels, modelName);

            await operation.WaitForCompletionAsync();

            Assert.IsTrue(operation.HasValue);
            Assert.AreEqual(CustomFormModelStatus.Ready, operation.Value.Status);

            return(new DisposableTrainedModel(trainingClient, operation.Value.ModelId));
        }
        private static async Task AnalyzeDynamicCustomForm(FormRecognizerClient recognizerClient, string trainingFileUrl, string formUrl)
        {
            RecognizeCustomFormsOptions options = new RecognizeCustomFormsOptions();

            //train model
            FormTrainingClient trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model          = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false,
                                                                                        $"VIS-Dynamic-Model-{DateTime.Now.ToShortDateString()}-{DateTime.Now.ToLongTimeString()}").WaitForCompletionAsync();

            //string modelId = inModelID;
            string modelId = model.ModelId;

            //recognize form
            RecognizeCustomFormsOperation operation = await recognizerClient.StartRecognizeCustomFormsFromUriAsync(modelId, new Uri(formUrl));

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection forms = operationResponse.Value;

            foreach (RecognizedForm form in forms)
            {
                returnString += $"Form of type: {form.FormType}{Environment.NewLine}";
                foreach (FormField field in form.Fields.Values)
                {
                    returnString += $"Field '{field.Name}: ";

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

                    returnString += $"    Value: '{field.ValueData.Text}";
                    returnString += $"    Confidence: '{field.Confidence}{Environment.NewLine}";
                }
                returnString += $"Table data:{Environment.NewLine}";
                foreach (FormPage page in form.Pages)
                {
                    for (int i = 0; i < page.Tables.Count; i++)
                    {
                        FormTable table = page.Tables[i];
                        //Console.WriteLine($"Table {i} has {table.RowCount} rows and {table.ColumnCount} columns.");
                        foreach (FormTableCell cell in table.Cells)
                        {
                            returnString += $"    Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains {(cell.IsHeader ? "header" : "text")}: '{cell.Text}'{Environment.NewLine}";
                        }
                    }
                }
            }
            // Delete the model on completion to clean environment.
            await trainingClient.DeleteModelAsync(model.ModelId);
        }
예제 #17
0
        public async Task RecognizeCustomFormsFromFile()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            // Firstly, create a trained model we can use to recognize the custom form. Please note that
            // models can also be trained using a graphical user interface such as the Form Recognizer
            // Labeling Tool found here:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/label-tool

            FormTrainingClient trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model          = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false, new TrainingOptions()
            {
                ModelName = "My Model"
            }).WaitForCompletionAsync();

            // Proceed with the custom form recognition.

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            string formFilePath = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg");
            string modelId      = model.ModelId;

            using (FileStream stream = new FileStream(formFilePath, FileMode.Open))
            {
                RecognizedFormCollection forms = await client.StartRecognizeCustomFormsAsync(modelId, stream).WaitForCompletionAsync();

                foreach (RecognizedForm form in forms)
                {
                    Console.WriteLine($"Form of type: {form.FormType}");
                    Console.WriteLine($"Form was analyzed with model with ID: {form.ModelId}");
                    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}");
                    }
                }
            }

            // Delete the model on completion to clean environment.
            await trainingClient.DeleteModelAsync(model.ModelId);
        }
        public async Task TrainModelWithForms()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleTrainModelWithForms
            // For this sample, you can use the training forms found in the `trainingFiles` folder.
            // Upload the forms to your storage container and then generate a container SAS URL.
            // For instructions on setting up forms for training in an Azure Storage Blob Container, see
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set#upload-your-training-data

#if SNIPPET
            Uri trainingFileUri = < trainingFileUri >;
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrlV2);
#endif
            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            TrainingOperation operation = await client.StartTrainingAsync(trainingFileUri, useTrainingLabels : false, "My Model");

            Response <CustomFormModel> operationResponse = await operation.WaitForCompletionAsync();

            CustomFormModel model = operationResponse.Value;

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"  Model Id: {model.ModelId}");
            Console.WriteLine($"  Model name: {model.ModelName}");
            Console.WriteLine($"  Model Status: {model.Status}");
            Console.WriteLine($"  Is composed model: {model.Properties.IsComposedModel}");
            Console.WriteLine($"  Training model started on: {model.TrainingStartedOn}");
            Console.WriteLine($"  Training model completed on: {model.TrainingCompletedOn}");

            foreach (CustomFormSubmodel submodel in model.Submodels)
            {
                Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
                foreach (CustomFormModelField field in submodel.Fields.Values)
                {
                    Console.Write($"  FieldName: {field.Name}");
                    if (field.Label != null)
                    {
                        Console.Write($", FieldLabel: {field.Label}");
                    }
                    Console.WriteLine("");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await client.DeleteModelAsync(model.ModelId);
        }
        private static async Task ManageModels(
            FormTrainingClient trainingClient, string trainingFileUrl)
        {
            // Check number of models in the FormRecognizer account,
            // and the maximum number of models that can be stored.
            AccountProperties accountProperties = trainingClient.GetAccountProperties();

            Console.WriteLine($"Account has {accountProperties.CustomModelCount} models.");
            Console.WriteLine($"It can have at most {accountProperties.CustomModelLimit}" +
                              $" models.");
            // List the first ten or fewer models currently stored in the account.
            Pageable <CustomFormModelInfo> models = trainingClient.GetCustomModels();

            foreach (CustomFormModelInfo modelInfo in models.Take(10))
            {
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"    Model Id: {modelInfo.ModelId}");
                Console.WriteLine($"    Model Status: {modelInfo.Status}");
                Console.WriteLine($"    Created On: {modelInfo.TrainingStartedOn}");
                Console.WriteLine($"    Last Modified: {modelInfo.TrainingCompletedOn}");
            }

            // Create a new model to store in the account
            CustomFormModel model = await trainingClient.StartTrainingAsync(
                new Uri(trainingFileUrl), useTrainingLabels : false).WaitForCompletionAsync();

            // Get the model that was just created
            CustomFormModel modelCopy = trainingClient.GetCustomModel(model.ModelId);

            Console.WriteLine($"Custom Model {modelCopy.ModelId} recognizes the following" +
                              " form types:");

            foreach (CustomFormSubmodel subModel in modelCopy.Submodels)
            {
                Console.WriteLine($"SubModel Form Type: {subModel.FormType}");
                foreach (CustomFormModelField field in subModel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Label != null)
                    {
                        Console.Write($", FieldLabel: {field.Label}");
                    }
                    Console.WriteLine("");
                }
            }

            // Delete the model from the account.
            trainingClient.DeleteModel(model.ModelId);
        }
        public async Task TrainModelWithFormsAndLabels()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            #region Snippet:FormRecognizerSampleTrainModelWithFormsAndLabels
            // For this sample, you can use the training forms found in the `trainingFiles` folder.
            // Upload the forms to your storage container and then generate a container SAS URL.
            // For instructions to set up forms for training in an Azure Storage Blob Container, please see:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set#upload-your-training-data

            // For instructions to create a label file for your training forms, please see:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/label-tool

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model  = await client.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : true, new TrainingOptions()
            {
                ModelName = "My Model with labels"
            }).WaitForCompletionAsync();

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"    Model Id: {model.ModelId}");
            Console.WriteLine($"    Model name: {model.ModelName}");
            Console.WriteLine($"    Model Status: {model.Status}");
            Console.WriteLine($"    Is composed model: {model.Properties.IsComposedModel}");
            Console.WriteLine($"    Training model started on: {model.TrainingStartedOn}");
            Console.WriteLine($"    Training model completed on: {model.TrainingCompletedOn}");

            foreach (CustomFormSubmodel submodel in model.Submodels)
            {
                Console.WriteLine($"Submodel Form Type: {submodel.FormType}");
                foreach (CustomFormModelField field in submodel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Accuracy != null)
                    {
                        Console.Write($", Accuracy: {field.Accuracy}");
                    }
                    Console.WriteLine("");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await client.DeleteModelAsync(model.ModelId);
        }
예제 #21
0
        /// <summary>
        /// For testing purposes, we are training our models using the client library functionalities.
        /// Please note that models can also be trained using a graphical user interface
        /// such as the Form Recognizer Labeling Tool found here:
        /// <a href="https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/label-tool"/>.
        /// </summary>
        /// <param name="useLabels">If <c>true</c>, use a label file created in the &lt;link-to-label-tool-doc&gt; to provide training-time labels for training a model. If <c>false</c>, the model will be trained from forms only.</param>
        /// <returns>The identifier of the trained model.</returns>
        private async Task <string> GetModelIdAsync(bool useLabels = false)
        {
            var trainingFiles         = new Uri(TestEnvironment.BlobContainerSasUrl);
            FormTrainingClient client = CreateInstrumentedFormTrainingClient();
            TrainingOperation  trainedModel;

            // TODO: sanitize body and enable body recording here.
            using (Recording.DisableRequestBodyRecording())
            {
                trainedModel = await client.StartTrainingAsync(trainingFiles, useLabels);
            }

            await trainedModel.WaitForCompletionAsync();

            Assert.IsTrue(trainedModel.HasValue);
            Assert.AreEqual(CustomFormModelStatus.Ready, trainedModel.Value.Status);

            return(trainedModel.Value.ModelId);
        }
예제 #22
0
        public async Task TrainModelWithFormsAndLabels()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            #region Snippet:FormRecognizerSample5TrainModelWithFormsAndLabels
            // For instructions to set up forms for training in an Azure Storage Blob Container, please see:
            // https://docs.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/curl-train-extract#train-a-form-recognizer-model

            // For instructions to create a label file for your training forms, please see:
            // https://docs.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/label-tool

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model  = await client.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : true).WaitForCompletionAsync();

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"    Model Id: {model.ModelId}");
            Console.WriteLine($"    Model Status: {model.Status}");
            Console.WriteLine($"    Requested on: {model.RequestedOn}");
            Console.WriteLine($"    Completed on: {model.CompletedOn}");

            foreach (CustomFormSubModel subModel in model.Models)
            {
                Console.WriteLine($"SubModel Form Type: {subModel.FormType}");
                foreach (CustomFormModelField field in subModel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Accuracy != null)
                    {
                        Console.Write($", Accuracy: {field.Accuracy}");
                    }
                    Console.WriteLine("");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            client.DeleteModel(model.ModelId);
        }
        // </snippet_maintask>

        // <snippet_train>
        // Train model using training form data (pdf, jpg, png files)
        private static async Task <string> TrainModelAsync(
            FormTrainingClient formTrainingClient, string trainingDataUrl)
        {
            if (!Uri.IsWellFormedUriString(trainingDataUrl, UriKind.Absolute))
            {
                Console.WriteLine("\nInvalid trainingDataUrl:\n{0} \n", trainingDataUrl);
                return(null);
            }

            try
            {
                CustomFormModel result = await formTrainingClient.StartTrainingAsync(new Uri(trainingDataUrl), useTrainingLabels : false).WaitForCompletionAsync();

                DisplayModelStatus(result);

                return(result.ModelId);
            }
            catch (RequestFailedException e)
            {
                Console.WriteLine("Train Model : " + e.Message);
                return(null);
            }
        }
        public async Task TrainModelWithForms()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            #region Snippet:FormRecognizerSample4TrainModelWithForms
            // For instructions on setting up forms for training in an Azure Storage Blob Container, see
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/quickstarts/curl-train-extract#train-a-form-recognizer-model

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model  = await client.StartTrainingAsync(new Uri(trainingFileUrl)).WaitForCompletionAsync();

            Console.WriteLine($"Custom Model Info:");
            Console.WriteLine($"    Model Id: {model.ModelId}");
            Console.WriteLine($"    Model Status: {model.Status}");
            Console.WriteLine($"    Created On: {model.CreatedOn}");
            Console.WriteLine($"    Last Modified: {model.LastModified}");

            foreach (CustomFormSubModel subModel in model.Models)
            {
                Console.WriteLine($"SubModel Form Type: {subModel.FormType}");
                foreach (CustomFormModelField field in subModel.Fields.Values)
                {
                    Console.Write($"    FieldName: {field.Name}");
                    if (field.Label != null)
                    {
                        Console.Write($", FieldLabel: {field.Label}");
                    }
                    Console.WriteLine("");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            client.DeleteModel(model.ModelId);
        }
예제 #25
0
        public async Task OutputModelsTrainedWithDynamicRowsTables()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.TableDynamicRowsContainerSasUrlV2;
            string formFilePath    = FormRecognizerTestEnvironment.CreatePath("label_table_dynamic_rows1.pdf");

            FormRecognizerClient client         = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            FormTrainingClient   trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // Model trained with labeled table with dynamic rows.
            CustomFormModel modelTrainedWithLabels = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : true).WaitForCompletionAsync();

            using (FileStream stream = new FileStream(formFilePath, FileMode.Open))
            {
                RecognizedFormCollection forms = await client.StartRecognizeCustomFormsAsync(modelTrainedWithLabels.ModelId, stream).WaitForCompletionAsync();

                Console.WriteLine("---------Recognized labeled table with dynamic rows---------");
                foreach (RecognizedForm form in forms)
                {
                    foreach (FormField field in form.Fields.Values)
                    {
                        /// Substitute "table" for the label given to the table tag during training
                        /// (if different than sample training docs).
                        if (field.Name == "table")
                        {
                            if (field.Value.ValueType == FieldValueType.List)
                            {
                                var table = field.Value.AsList();
                                //columns
                                for (int i = 0; i < table.Count; i++)
                                {
                                    Console.WriteLine($"Row {i+1}:");
                                    var row = table[i].Value.AsDictionary();
                                    foreach (var colValues in row)
                                    {
                                        Console.Write($"  Col {colValues.Key}. Value: ");
                                        if (colValues.Value != null)
                                        {
                                            var rowContent = colValues.Value;
                                            if (rowContent.Value.ValueType == FieldValueType.String)
                                            {
                                                Console.WriteLine($"'{rowContent.Value.AsString()}'");
                                            }
                                        }
                                        else
                                        {
                                            Console.WriteLine("Empty cell.");
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            Console.WriteLine($"Field {field.Name}: ");
                            Console.WriteLine($"    Value: '{field.ValueData.Text}");
                            Console.WriteLine($"    Confidence: '{field.Confidence}");
                        }
                    }
                }
            }
        }
예제 #26
0
        public async Task RecognizeCustomFormsFromFile()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            // Firstly, create a trained model we can use to recognize the custom form. Please note that
            // models can also be trained using a graphical user interface such as the Form Recognizer
            // Labeling Tool found here:
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/label-tool?tabs=v2-1

            FormTrainingClient trainingClient = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            CustomFormModel    model          = await trainingClient.StartTrainingAsync(new Uri(trainingFileUrl), useTrainingLabels : false, "My Model").WaitForCompletionAsync();

            // Proceed with the custom form recognition.

            FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            #region Snippet:FormRecognizerRecognizeCustomFormsFromFile
#if SNIPPET
            string modelId  = "<modelId>";
            string filePath = "<filePath>";
#else
            string filePath = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg");
            string modelId  = model.ModelId;
#endif

            using var stream = new FileStream(filePath, FileMode.Open);
            var options = new RecognizeCustomFormsOptions()
            {
                IncludeFieldElements = true
            };

            RecognizeCustomFormsOperation operation = await client.StartRecognizeCustomFormsAsync(modelId, stream, options);

            Response <RecognizedFormCollection> operationResponse = await operation.WaitForCompletionAsync();

            RecognizedFormCollection forms = operationResponse.Value;

            foreach (RecognizedForm form in forms)
            {
                Console.WriteLine($"Form of type: {form.FormType}");
                Console.WriteLine($"Form was analyzed with model with ID: {form.ModelId}");
                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}'");
                }

                // Iterate over tables, lines, and selection marks on each page
                foreach (var page in form.Pages)
                {
                    for (int i = 0; i < page.Tables.Count; i++)
                    {
                        Console.WriteLine($"Table {i+1} on page {page.Tables[i].PageNumber}");
                        foreach (var cell in page.Tables[i].Cells)
                        {
                            Console.WriteLine($"  Cell[{cell.RowIndex}][{cell.ColumnIndex}] has text '{cell.Text}' with confidence {cell.Confidence}");
                        }
                    }
                    Console.WriteLine($"Lines found on page {page.PageNumber}");
                    foreach (var line in page.Lines)
                    {
                        Console.WriteLine($"  Line {line.Text}");
                    }

                    if (page.SelectionMarks.Count != 0)
                    {
                        Console.WriteLine($"Selection marks found on page {page.PageNumber}");
                        foreach (var selectionMark in page.SelectionMarks)
                        {
                            Console.WriteLine($"  Selection mark is '{selectionMark.State}' with confidence {selectionMark.Confidence}");
                        }
                    }
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await trainingClient.DeleteModelAsync(model.ModelId);
        }
        public async Task CreateComposedModel()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            string trainingFileUrl = TestEnvironment.BlobContainerSasUrl;

            FormTrainingClient client = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            string purchaseOrderOfficeSuppliesUrl   = trainingFileUrl;
            string purchaseOrderOfficeEquipmentUrl  = trainingFileUrl;
            string purchaseOrderFurnitureUrl        = trainingFileUrl;
            string purchaseOrderCleaningSuppliesUrl = trainingFileUrl;

            #region Snippet:FormRecognizerSampleTrainVariousModels
            // For this sample, you can use the training forms found in the `trainingFiles` folder.
            // Upload the forms to your storage container and then generate a container SAS URL.
            // For instructions on setting up forms for training in an Azure Storage Blob Container, see
            // https://docs.microsoft.com/azure/cognitive-services/form-recognizer/build-training-data-set#upload-your-training-data

            //@@ string purchaseOrderOfficeSuppliesUrl = "<purchaseOrderOfficeSupplies>";
            //@@ string purchaseOrderOfficeEquipmentUrl = "<purchaseOrderOfficeEquipment>";
            //@@ string purchaseOrderFurnitureUrl = "<purchaseOrderFurniture>";
            //@@ string purchaseOrderCleaningSuppliesUrl = "<purchaseOrderCleaningSupplies>";

            CustomFormModel purchaseOrderOfficeSuppliesModel   = (await client.StartTrainingAsync(new Uri(purchaseOrderOfficeSuppliesUrl), useTrainingLabels: true, "Purchase order - Office supplies").WaitForCompletionAsync()).Value;
            CustomFormModel purchaseOrderOfficeEquipmentModel  = (await client.StartTrainingAsync(new Uri(purchaseOrderOfficeEquipmentUrl), useTrainingLabels: true, "Purchase order - Office Equipment").WaitForCompletionAsync()).Value;
            CustomFormModel purchaseOrderFurnitureModel        = (await client.StartTrainingAsync(new Uri(purchaseOrderFurnitureUrl), useTrainingLabels: true, "Purchase order - Furniture").WaitForCompletionAsync()).Value;
            CustomFormModel purchaseOrderCleaningSuppliesModel = (await client.StartTrainingAsync(new Uri(purchaseOrderCleaningSuppliesUrl), useTrainingLabels: true, "Purchase order - Cleaning Supplies").WaitForCompletionAsync()).Value;

            #endregion

            #region Snippet:FormRecognizerSampleCreateComposedModel

            List <string> modelIds = new List <string>()
            {
                purchaseOrderOfficeSuppliesModel.ModelId,
                purchaseOrderOfficeEquipmentModel.ModelId,
                purchaseOrderFurnitureModel.ModelId,
                purchaseOrderCleaningSuppliesModel.ModelId
            };

            CustomFormModel purchaseOrderModel = (await client.StartCreateComposedModelAsync(modelIds, "Composed Purchase order").WaitForCompletionAsync()).Value;

            Console.WriteLine($"Purchase Order Model Info:");
            Console.WriteLine($"    Is composed model: {purchaseOrderModel.Properties.IsComposedModel}");
            Console.WriteLine($"    Model Id: {purchaseOrderModel.ModelId}");
            Console.WriteLine($"    Model name: {purchaseOrderModel.ModelName}");
            Console.WriteLine($"    Model Status: {purchaseOrderModel.Status}");
            Console.WriteLine($"    Create model started on: {purchaseOrderModel.TrainingStartedOn}");
            Console.WriteLine($"    Create model completed on: {purchaseOrderModel.TrainingCompletedOn}");

            #endregion

            #region Snippet:FormRecognizerSampleSubmodelsInComposedModel

            Dictionary <string, List <TrainingDocumentInfo> > trainingDocsPerModel = purchaseOrderModel.TrainingDocuments.GroupBy(doc => doc.ModelId).ToDictionary(g => g.Key, g => g.ToList());

            Console.WriteLine($"The purchase order model is based on {purchaseOrderModel.Submodels.Count} model{(purchaseOrderModel.Submodels.Count > 1 ? "s" : "")}.");
            foreach (CustomFormSubmodel model in purchaseOrderModel.Submodels)
            {
                Console.WriteLine($"    Model Id: {model.ModelId}");
                Console.WriteLine("    The documents used to trained the model are: ");
                foreach (var doc in trainingDocsPerModel[model.ModelId])
                {
                    Console.WriteLine($"        {doc.Name}");
                }
            }

            #endregion

            string purchaseOrderFilePath = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg");

            #region Snippet:FormRecognizerSampleRecognizeCustomFormWithComposedModel

            //@@ string purchaseOrderFilePath = "<purchaseOrderFilePath>";
            FormRecognizerClient formRecognizerClient = client.GetFormRecognizerClient();

            RecognizedFormCollection forms;
            using (FileStream stream = new FileStream(purchaseOrderFilePath, FileMode.Open))
            {
                forms = await formRecognizerClient.StartRecognizeCustomFormsAsync(purchaseOrderModel.ModelId, stream).WaitForCompletionAsync();

                // Find labeled field.
                foreach (RecognizedForm form in forms)
                {
                    // Setting an arbitrary confidence level
                    if (form.FormTypeConfidence.Value > 0.9)
                    {
                        if (form.Fields.TryGetValue("Total", out FormField field))
                        {
                            Console.WriteLine($"Total value in the form `{form.FormType}` is `{field.ValueData.Text}`");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Unable to recognize form.");
                    }
                }
            }

            #endregion

            // Delete the models on completion to clean environment.
            await client.DeleteModelAsync(purchaseOrderOfficeSuppliesModel.ModelId).ConfigureAwait(false);

            await client.DeleteModelAsync(purchaseOrderOfficeEquipmentModel.ModelId).ConfigureAwait(false);

            await client.DeleteModelAsync(purchaseOrderFurnitureModel.ModelId).ConfigureAwait(false);

            await client.DeleteModelAsync(purchaseOrderCleaningSuppliesModel.ModelId).ConfigureAwait(false);

            await client.DeleteModelAsync(purchaseOrderModel.ModelId).ConfigureAwait(false);
        }