public void CreateFormTrainingClientFromFormRecognizerClient()
        {
            var client = CreateClient();
            FormTrainingClient trainingClient = client.GetFormTrainingClient();

            Assert.IsNotNull(trainingClient);
        }
        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);
        }
Exemplo n.º 3
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);
            }
        }
        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
        }
Exemplo n.º 5
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.

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

            // Proceed with the custom form recognition.

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

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

            #region Snippet:FormRecognizerRecognizeCustomFormsFromFile
            using (FileStream stream = new FileStream(formFilePath, FileMode.Open))
            {
                //@@ string modelId = "<modelId>";

                RecognizedFormCollection forms = await client.StartRecognizeCustomForms(modelId, stream).WaitForCompletionAsync();

                /*
                 *
                 */
            }
            #endregion

            // Delete the model on completion to clean environment.
            trainingClient.DeleteModel(model.ModelId);
        }
        public void CreateFormTrainingClientFromFormRecognizerClient()
        {
            FormRecognizerClient client         = CreateInstrumentedClient();
            FormTrainingClient   trainingClient = client.GetFormTrainingClient();

            Assert.IsNotNull(trainingClient);
        }
    // </snippet_main>

// <snippet_auth>
    static async Task RunFormRecognizerClient()
    { 
        string endpoint = Environment.GetEnvironmentVariable(
            "FORM_RECOGNIZER_ENDPOINT");
        string apiKey = Environment.GetEnvironmentVariable(
            "FORM_RECOGNIZER_KEY");
        var credential = new AzureKeyCredential(apiKey);
        
        var trainingClient = new FormTrainingClient(new Uri(endpoint), credential);
        var recognizerClient = new FormRecognizerClient(new Uri(endpoint), credential);
        // </snippet_auth>
        // <snippet_calls>
        string trainingDataUrl = "<SAS-URL-of-your-form-folder-in-blob-storage>";
        string formUrl = "<SAS-URL-of-a-form-in-blob-storage>";
        string receiptUrl = "https://docs.microsoft.com/azure/cognitive-services/form-recognizer/media"
        + "/contoso-allinone.jpg";

        // Call Form Recognizer scenarios:
        Console.WriteLine("Get form content...");
        await GetContent(recognizerClient, formUrl);

        Console.WriteLine("Analyze receipt...");
        await AnalyzeReceipt(recognizerClient, receiptUrl);

        Console.WriteLine("Train Model with training data...");
        Guid modelId = await TrainModel(trainingClient, trainingDataUrl);

        Console.WriteLine("Analyze PDF form...");
        await AnalyzePdfForm(recognizerClient, modelId, formUrl);

        Console.WriteLine("Manage models...");
        await ManageModels(trainingClient, trainingDataUrl) ;
    }
Exemplo n.º 8
0
        private static async Task CreateModel(string endpoint, string apiKey, string trainingSetUrl, string modelName)
        {
            // Create a new model to store in the account
            Uri trainingSetUri = new Uri(trainingSetUrl);

            FormTrainingClient         client            = new FormTrainingClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            TrainingOperation          operation         = client.StartTraining(trainingSetUri, useTrainingLabels: true, modelName);
            Response <CustomFormModel> operationResponse = await operation.WaitForCompletionAsync();

            CustomFormModel model = operationResponse.Value;

            // Get the model that was just created
            CustomFormModel modelCopy = client.GetCustomModel(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.
            //client.DeleteModel(model.ModelId);
        }
    // </snippet_auth>

    // <snippet_auth_training>
    static private FormTrainingClient AuthenticateTrainingClient()
    {
        var credential = new AzureKeyCredential(apiKey);
        var client     = new FormTrainingClient(new Uri(endpoint), credential);

        return(client);
    }
        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 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));
        }
Exemplo n.º 12
0
        //Authenticate form training client Definition
        static private FormTrainingClient AuthenticateTrainingClientForDefinitionModel()
        {
            var credential     = new AzureKeyCredential(apiKeyDefinition);
            var trainingClient = new FormTrainingClient(new Uri(endpointDefinition), credential);

            return(trainingClient);
        }
    // </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);
    }
        // </snippet_main>

        // <snippet_maintask>
        static async Task RunFormRecognizerClient()
        {
            // Create form client object with Form Recognizer subscription key
            var formTrainingClient = new FormTrainingClient(new Uri(formRecognizerEndpoint), new AzureKeyCredential(subscriptionKey));

            Console.WriteLine("Train Model with training data...");
            string modelId = await TrainModelAsync(formTrainingClient, trainingDataUrl);

            // Choose any of the following three Analyze tasks:

            Console.WriteLine("Analyze PDF form...");
            await AnalyzePdfForm(formTrainingClient, modelId, pdfFormFile);

            Console.WriteLine("Analyze JPEG form...");
            await AnalyzeJpgForm(formTrainingClient, modelId, jpgFormFile);

            Console.WriteLine("Analyze PNG form...");
            await AnalyzePngForm(formTrainingClient, modelId, pngFormFile);

            Console.WriteLine("Get list of trained models ...");
            GetListOfModels(formTrainingClient);

            Console.WriteLine("Delete Model...");
            await DeleteModel(formTrainingClient, modelId);
        }
Exemplo n.º 15
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);
        }
        /// <summary>
        /// Creates a fake <see cref="FormTrainingClient" /> and instruments it to make use of the Azure Core
        /// Test Framework functionalities.
        /// </summary>
        /// <returns>The instrumented <see cref="FormTrainingClient" />.</returns>
        private FormTrainingClient CreateInstrumentedClient()
        {
            var fakeEndpoint   = new Uri("http://notreal.azure.com/");
            var fakeCredential = new AzureKeyCredential("fakeKey");
            var client         = new FormTrainingClient(fakeEndpoint, fakeCredential);

            return(InstrumentClient(client));
        }
        public void DeleteModelArgumentValidation()
        {
            FormTrainingClient client = CreateInstrumentedClient();

            Assert.ThrowsAsync <ArgumentNullException>(() => client.DeleteModelAsync(null));
            Assert.ThrowsAsync <ArgumentException>(() => client.DeleteModelAsync(string.Empty));
            Assert.ThrowsAsync <ArgumentException>(() => client.DeleteModelAsync("1975-04-04"));
        }
        public void CreateFormRecognizerClientFromFormTrainingClient()
        {
            FormTrainingClient   trainingClient       = new FormTrainingClient(new Uri("http://localhost"), new AzureKeyCredential("key"));
            FormRecognizerClient formRecognizerClient = trainingClient.GetFormRecognizerClient();

            Assert.IsNotNull(formRecognizerClient);
            Assert.IsNotNull(formRecognizerClient.Diagnostics);
            Assert.IsNotNull(formRecognizerClient.ServiceClient);
        }
Exemplo n.º 19
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 void CreateFormRecognizerClientFromFormTrainingClient()
        {
            FormTrainingClient   trainingClient       = CreateInstrumentedClient();
            FormRecognizerClient formRecognizerClient = trainingClient.GetFormRecognizerClient();

            Assert.IsNotNull(formRecognizerClient);
            Assert.IsNotNull(formRecognizerClient.Diagnostics);
            Assert.IsNotNull(formRecognizerClient.ServiceClient);
        }
Exemplo n.º 21
0
        static private FormTrainingClient AuthenticateTrainingClient()
        {
            string endpoint   = "<replace-with-your-form-recognizer-endpoint-here>";
            string apiKey     = "<replace-with-your-form-recognizer-key-here>";
            var    credential = new AzureKeyCredential(apiKey);
            var    client     = new FormTrainingClient(new Uri(endpoint), credential);

            return(client);
        }
Exemplo n.º 22
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);
        }
        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;
        }
Exemplo n.º 24
0
        private FormTrainingClient AuthenticateTrainingClient()
        {
            var apiKey     = $"{_configuration["FormRecognizer:Key"]}" ?? "";
            var endpoint   = $"{_configuration["FormRecognizer:Endpoint"]}" ?? "";
            var credential = new AzureKeyCredential(apiKey);
            var client     = new FormTrainingClient(new Uri(endpoint), credential);

            return(client);
        }
        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
        }
Exemplo n.º 26
0
        public void CopyModelOperationRequiredParameters()
        {
            FormTrainingClient client      = CreateFormTrainingClient();
            string             operationId = "00000000-0000-0000-0000-000000000000/copyresults/00000000-0000-0000-0000-000000000000";
            string             targetId    = "00000000-0000-0000-0000-000000000000";

            Assert.Throws <ArgumentNullException>(() => new CopyModelOperation(null, targetId, client));
            Assert.Throws <ArgumentException>(() => new CopyModelOperation(string.Empty, targetId, client));
            Assert.Throws <ArgumentNullException>(() => new CopyModelOperation(operationId, targetId, null));
        }
        /// <summary>
        /// Creates a <see cref="FormTrainingClient" /> with the endpoint and API key provided via environment
        /// variables and instruments it to make use of the Azure Core Test Framework functionalities.
        /// </summary>
        /// <returns>The instrumented <see cref="FormTrainingClient" />.</returns>
        private FormTrainingClient CreateInstrumentedClient()
        {
            var endpoint   = new Uri(TestEnvironment.Endpoint);
            var credential = new AzureKeyCredential(TestEnvironment.ApiKey);

            var options = Recording.InstrumentClientOptions(new FormRecognizerClientOptions());
            var client  = new FormTrainingClient(endpoint, credential, options);

            return(InstrumentClient(client));
        }
        /// <summary>
        /// Creates a fake <see cref="FormTrainingClient" /> and instruments it to make use of the Azure Core
        /// Test Framework functionalities.
        /// </summary>
        /// <returns>The instrumented <see cref="FormTrainingClient" />.</returns>
        private FormTrainingClient CreateClient(FormRecognizerClientOptions options = default)
        {
            var fakeEndpoint   = new Uri("http://notreal.azure.com/");
            var fakeCredential = new AzureKeyCredential("fakeKey");

            options ??= new FormRecognizerClientOptions();
            var client = new FormTrainingClient(fakeEndpoint, fakeCredential, options);

            return(client);
        }
    // </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
        }