public async Task CopyModelAsync()
        {
            #region Snippet:FormRecognizerSampleCreateCopySourceClient
#if SNIPPET
            string sourceEndpoint = "<source_endpoint>";
            string sourceApiKey   = "<source_apiKey>";
#else
            string sourceEndpoint = TestEnvironment.Endpoint;
            string sourceApiKey   = TestEnvironment.ApiKey;
#endif
            var sourcecredential = new AzureKeyCredential(sourceApiKey);
            var sourceClient     = new DocumentModelAdministrationClient(new Uri(sourceEndpoint), new AzureKeyCredential(sourceApiKey));
            #endregion

            // For the purpose of this sample, we are going to create a model to copy. Please note that
            // if you already have a model, this is not necessary.
#if SNIPPET
            Uri trainingFileUri = new Uri("<trainingFileUri>");
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation operation = await sourceClient.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

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

            DocumentModel model = operationResponse.Value;

            #region Snippet:FormRecognizerSampleCreateCopyTargetClient
#if SNIPPET
            string targetEndpoint = "<target_endpoint>";
            string targetApiKey   = "<target_apiKey>";
#else
            string targetEndpoint = TestEnvironment.Endpoint;
            string targetApiKey   = TestEnvironment.ApiKey;
#endif
            var targetCredential = new AzureKeyCredential(targetApiKey);
            var targetClient     = new DocumentModelAdministrationClient(new Uri(targetEndpoint), new AzureKeyCredential(targetApiKey));
            #endregion

            #region Snippet:FormRecognizerSampleGetCopyAuthorization
            CopyAuthorization targetAuth = await targetClient.GetCopyAuthorizationAsync();

            #endregion

            #region Snippet:FormRecognizerSampleCreateCopyModel
#if SNIPPET
            string modelId = "<source_modelId>";
#else
            string modelId = model.ModelId;
#endif
            CopyModelOperation newModelOperation = await sourceClient.StartCopyModelToAsync(modelId, targetAuth);

            await newModelOperation.WaitForCompletionAsync();

            DocumentModel newModel = newModelOperation.Value;

            Console.WriteLine($"Original model ID => {modelId}");
            Console.WriteLine($"Copied model ID => {newModel.ModelId}");
            #endregion
        }
        public async Task ManageModels()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleManageModels

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

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

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

            foreach (DocumentModelInfo modelInfo in models.Take(10))
            {
                Console.WriteLine($"Custom Model Info:");
                Console.WriteLine($"  Model Id: {modelInfo.ModelId}");
                if (string.IsNullOrEmpty(modelInfo.Description))
                {
                    Console.WriteLine($"  Model description: {modelInfo.Description}");
                }
                Console.WriteLine($"  Created on: {modelInfo.CreatedOn}");
            }

            // Create a new model to store in the account

#if SNIPPET
            Uri trainingFileUri = < trainingFileUri >;
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation      operation         = client.StartBuildModel(trainingFileUri, DocumentBuildMode.Template);
            Response <DocumentModel> operationResponse = await operation.WaitForCompletionAsync();

            DocumentModel model = operationResponse.Value;

            // Get the model that was just created
            DocumentModel newCreatedModel = client.GetModel(model.ModelId);

            Console.WriteLine($"Custom Model with Id {newCreatedModel.ModelId} has the following information:");

            Console.WriteLine($"  Model Id: {newCreatedModel.ModelId}");
            if (string.IsNullOrEmpty(newCreatedModel.Description))
            {
                Console.WriteLine($"  Model description: {newCreatedModel.Description}");
            }
            Console.WriteLine($"  Created on: {newCreatedModel.CreatedOn}");

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

            #endregion
        }
        /// <summary>
        /// Builds a model using the specified <see cref="DocumentModelAdministrationClient"/> and the specified set of training files. A
        /// <see cref="DisposableBuildModel"/> instance is returned. Upon disposal,
        /// the associated model will be deleted.
        /// </summary>
        /// <param name="adminClient">The client to use for building and for deleting the model upon disposal.</param>
        /// <param name="trainingFilesUri">An externally accessible Azure storage blob container Uri.</param>
        /// <param name="buildMode">The technique to use to build the model.</param>
        /// <param name="modelId">Model Id.</param>
        /// <returns>A <see cref="DisposableBuildModel"/> instance from which the trained model ID can be obtained.</returns>
        public static async Task<DisposableBuildModel> BuildModelAsync(DocumentModelAdministrationClient adminClient, Uri trainingFilesUri, DocumentBuildMode buildMode, string modelId)
        {
            BuildModelOperation operation = await adminClient.StartBuildModelAsync(trainingFilesUri, buildMode, modelId);
            await operation.WaitForCompletionAsync();

            Assert.IsTrue(operation.HasValue);

            return new DisposableBuildModel(adminClient, operation.Value.ModelId);
        }
        /// <summary>
        /// Creates a fake <see cref="DocumentModelAdministrationClient" /> and instruments it to make use of the Azure Core
        /// Test Framework functionalities.
        /// </summary>
        /// <returns>The instrumented <see cref="DocumentModelAdministrationClient" />.</returns>
        private DocumentModelAdministrationClient CreateInstrumentedClient(DocumentAnalysisClientOptions options = default)
        {
            var fakeEndpoint   = new Uri("http://notreal.azure.com/");
            var fakeCredential = new AzureKeyCredential("fakeKey");

            options ??= new DocumentAnalysisClientOptions();
            var client = new DocumentModelAdministrationClient(fakeEndpoint, fakeCredential, options);

            return(client);
        }
Exemple #5
0
        public async Task BuildCustomModelAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleBuildModel
            // For this sample, you can use the training documents found in the `trainingFiles` folder.
            // Upload the documents 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 documents for training in an Azure Blob Storage Container, please see:
            // https://aka.ms/azsdk/formrecognizer/buildcustommodel

#if SNIPPET
            Uri trainingFileUri = new Uri("<trainingFileUri>");
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            var client = new DocumentModelAdministrationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));

            // We are selecting the Template build mode in this sample. For more information about the available
            // build modes and their differences, please see:
            // https://aka.ms/azsdk/formrecognizer/buildmode

            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

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

            DocumentModel model = operationResponse.Value;

            Console.WriteLine($"  Model Id: {model.ModelId}");
            if (string.IsNullOrEmpty(model.Description))
            {
                Console.WriteLine($"  Model description: {model.Description}");
            }
            Console.WriteLine($"  Created on: {model.CreatedOn}");
            Console.WriteLine("  Doc types the model can recognize:");
            foreach (KeyValuePair <string, DocTypeInfo> docType in model.DocTypes)
            {
                Console.WriteLine($"    Doc type: {docType.Key} which has the following fields:");
                foreach (KeyValuePair <string, DocumentFieldSchema> schema in docType.Value.FieldSchema)
                {
                    Console.WriteLine($"    Field: {schema.Key} with confidence {docType.Value.FieldConfidence[schema.Key]}");
                }
            }
            #endregion

            // Delete the model on completion to clean environment.
            await client.DeleteModelAsync(model.ModelId);
        }
        public void CreateDocumentModelAdministrationClient()
        {
            #region Snippet:CreateDocumentModelAdministrationClient
#if SNIPPET
            string endpoint = "<endpoint>";
            string apiKey   = "<apiKey>";
#else
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;
#endif
            var credential = new AzureKeyCredential(apiKey);
            var client     = new DocumentModelAdministrationClient(new Uri(endpoint), credential);
            #endregion
        }
        /// <summary>
        /// Creates a <see cref="DocumentModelAdministrationClient" /> with the endpoint and API key provided via environment
        /// variables and instruments it to make use of the Azure Core Test Framework functionalities.
        /// </summary>
        /// <param name="nonInstrumentedClient">The non-instrumented version of the client to be used to resume LROs.</param>
        /// <param name="useTokenCredential">Whether or not to use a <see cref="TokenCredential"/> to authenticate. An <see cref="AzureKeyCredential"/> is used by default.</param>
        /// <param name="apiKey">The API key to use for authentication. Defaults to <see cref="DocumentAnalysisTestEnvironment.ApiKey"/>.</param>
        /// <returns>The instrumented <see cref="DocumentModelAdministrationClient" />.</returns>
        protected DocumentModelAdministrationClient CreateDocumentModelAdministrationClient(out DocumentModelAdministrationClient nonInstrumentedClient, bool useTokenCredential = false, string apiKey = default)
        {
            var endpoint = new Uri(TestEnvironment.Endpoint);
            var options  = InstrumentClientOptions(new DocumentAnalysisClientOptions(_serviceVersion));

            if (useTokenCredential)
            {
                nonInstrumentedClient = new DocumentModelAdministrationClient(endpoint, TestEnvironment.Credential, options);
            }
            else
            {
                var credential = new AzureKeyCredential(apiKey ?? TestEnvironment.ApiKey);
                nonInstrumentedClient = new DocumentModelAdministrationClient(endpoint, credential, options);
            }

            return(InstrumentClient(nonInstrumentedClient));
        }
        public async Task BuildCustomModelAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleBuildModel
            // For this sample, you can use the training documents 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://aka.ms/azsdk/formrecognizer/buildtrainingset

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

            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri);

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

            DocumentModel model = operationResponse.Value;

            Console.WriteLine($"  Model Id: {model.ModelId}");
            if (string.IsNullOrEmpty(model.Description))
            {
                Console.WriteLine($"  Model description: {model.Description}");
            }
            Console.WriteLine($"  Created on: {model.CreatedOn}");
            Console.WriteLine("  Doc types the model can recognize:");
            foreach (KeyValuePair <string, DocTypeInfo> docType in model.DocTypes)
            {
                Console.WriteLine($"    Doc type: {docType.Key} which has the following fields:");
                foreach (KeyValuePair <string, DocumentFieldSchema> schema in docType.Value.FieldSchema)
                {
                    Console.WriteLine($"    Field: {schema.Key} with confidence {docType.Value.FieldConfidence[schema.Key]}");
                }
            }
            #endregion

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

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

            #region Snippet:FormRecognizerSampleBuildVariousModels
            // 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://aka.ms/azsdk/formrecognizer/buildtrainingset

#if SNIPPET
            Uri officeSuppliesUri = new Uri("<purchaseOrderOfficeSuppliesUri>");
#else
            Uri officeSuppliesUri = new Uri(trainingFileUrl);
#endif
            var officeSupplieOptions = new BuildModelOptions()
            {
                ModelDescription = "Purchase order - Office supplies"
            };

            BuildModelOperation suppliesOperation = await client.StartBuildModelAsync(officeSuppliesUri, DocumentBuildMode.Template, buildModelOptions : officeSupplieOptions);

            Response <DocumentModel> suppliesOperationResponse = await suppliesOperation.WaitForCompletionAsync();

            DocumentModel officeSuppliesModel = suppliesOperationResponse.Value;

#if SNIPPET
            Uri officeEquipmentUri = new Uri("<purchaseOrderOfficeEquipmentUri>");
#else
            Uri officeEquipmentUri = new Uri(trainingFileUrl);
#endif
            var equipmentOptions = new BuildModelOptions()
            {
                ModelDescription = "Purchase order - Office Equipment"
            };

            BuildModelOperation equipmentOperation = await client.StartBuildModelAsync(officeSuppliesUri, DocumentBuildMode.Template, buildModelOptions : equipmentOptions);

            Response <DocumentModel> equipmentOperationResponse = await equipmentOperation.WaitForCompletionAsync();

            DocumentModel officeEquipmentModel = equipmentOperationResponse.Value;

#if SNIPPET
            Uri furnitureUri = new Uri("<purchaseOrderFurnitureUri>");
#else
            Uri furnitureUri = new Uri(trainingFileUrl);
#endif
            var furnitureOptions = new BuildModelOptions()
            {
                ModelDescription = "Purchase order - Furniture"
            };

            BuildModelOperation furnitureOperation = await client.StartBuildModelAsync(officeSuppliesUri, DocumentBuildMode.Template, buildModelOptions : equipmentOptions);

            Response <DocumentModel> furnitureOperationResponse = await furnitureOperation.WaitForCompletionAsync();

            DocumentModel furnitureModel = furnitureOperationResponse.Value;

#if SNIPPET
            Uri cleaningSuppliesUri = new Uri("<purchaseOrderCleaningSuppliesUri>");
#else
            Uri cleaningSuppliesUri = new Uri(trainingFileUrl);
#endif
            var cleaningOptions = new BuildModelOptions()
            {
                ModelDescription = "Purchase order - Cleaning Supplies"
            };

            BuildModelOperation cleaningOperation = await client.StartBuildModelAsync(officeSuppliesUri, DocumentBuildMode.Template, buildModelOptions : equipmentOptions);

            Response <DocumentModel> cleaningOperationResponse = await cleaningOperation.WaitForCompletionAsync();

            DocumentModel cleaningSuppliesModel = cleaningOperationResponse.Value;

            #endregion

            #region Snippet:FormRecognizerSampleCreateComposedModel

            List <string> modelIds = new List <string>()
            {
                officeSuppliesModel.ModelId,
                officeEquipmentModel.ModelId,
                furnitureModel.ModelId,
                cleaningSuppliesModel.ModelId
            };

            BuildModelOperation operation = await client.StartCreateComposedModelAsync(modelIds, modelDescription : "Composed Purchase order");

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

            DocumentModel purchaseOrderModel = operationResponse.Value;

            Console.WriteLine($"  Model Id: {purchaseOrderModel.ModelId}");
            if (string.IsNullOrEmpty(purchaseOrderModel.Description))
            {
                Console.WriteLine($"  Model description: {purchaseOrderModel.Description}");
            }
            Console.WriteLine($"  Created on: {purchaseOrderModel.CreatedOn}");

            #endregion

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

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

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

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

            await client.DeleteModelAsync(purchaseOrderModel.ModelId).ConfigureAwait(false);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DisposableBuildModel"/> class.
 /// </summary>
 /// <param name="adminClient">The client to use for deleting the model upon disposal.</param>
 /// <param name="modelId">The identifier of the model to delete upon disposal.</param>
 private DisposableBuildModel(DocumentModelAdministrationClient adminClient, string modelId)
 {
     _adminClient = adminClient;
     ModelId      = modelId;
 }
        public async Task AnalyzeWithCustomModelFromFileAsync()
        {
            string endpoint        = TestEnvironment.Endpoint;
            string apiKey          = TestEnvironment.ApiKey;
            Uri    trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);

            // Firstly, create a custom built model we can use to recognize the custom document. Please note
            // that models can also be built using a graphical user interface such as the Form Recognizer
            // Labeling Tool found here:
            // https://aka.ms/azsdk/formrecognizer/labelingtool

            var adminClient = new DocumentModelAdministrationClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
            BuildModelOperation buildOperation = await adminClient.StartBuildModelAsync(trainingFileUri);

            await buildOperation.WaitForCompletionAsync();

            DocumentModel customModel = buildOperation.Value;

            // Proceed with the custom document recognition.

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

            #region Snippet:FormRecognizerAnalyzeWithCustomModelFromFileAsync
#if SNIPPET
            string modelId  = "<modelId>";
            string filePath = "<filePath>";
#else
            string filePath = DocumentAnalysisTestEnvironment.CreatePath("Form_1.jpg");
            string modelId  = customModel.ModelId;
#endif

            using var stream = new FileStream(filePath, FileMode.Open);

            AnalyzeDocumentOperation operation = await client.StartAnalyzeDocumentAsync(modelId, stream);

            await operation.WaitForCompletionAsync();

            AnalyzeResult result = operation.Value;

            Console.WriteLine($"Document was analyzed with model with ID: {result.ModelId}");

            foreach (AnalyzedDocument document in result.Documents)
            {
                Console.WriteLine($"Document of type: {document.DocType}");

                foreach (KeyValuePair <string, DocumentField> fieldKvp in document.Fields)
                {
                    string        fieldName = fieldKvp.Key;
                    DocumentField field     = fieldKvp.Value;

                    Console.WriteLine($"Field '{fieldName}': ");

                    Console.WriteLine($"  Content: '{field.Content}'");
                    Console.WriteLine($"  Confidence: '{field.Confidence}'");
                }
            }
            #endregion

            // Iterate over lines and selection marks on each page
            foreach (DocumentPage page in result.Pages)
            {
                Console.WriteLine($"Lines found on page {page.PageNumber}");
                foreach (var line in page.Lines)
                {
                    Console.WriteLine($"  {line.Content}");
                }

                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}");
                }
            }

            // Iterate over the document tables
            for (int i = 0; i < result.Tables.Count; i++)
            {
                Console.WriteLine($"Table {i + 1}");
                foreach (var cell in result.Tables[i].Cells)
                {
                    Console.WriteLine($"  Cell[{cell.RowIndex}][{cell.ColumnIndex}] has content '{cell.Content}' with kind '{cell.Kind}'");
                }
            }

            // Delete the model on completion to clean environment.
            await adminClient.DeleteModelAsync(customModel.ModelId);
        }
Exemple #12
0
        public async Task GetAndListOperationsAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleGetAndListOperations

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

            // Make sure there is at least one operation, so we are going to build a custom model.
#if SNIPPET
            Uri trainingFileUri = new Uri("<trainingFileUri>");
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

            await operation.WaitForCompletionAsync();

            // List the first ten or fewer operations that have been executed in the last 24h.
            AsyncPageable <ModelOperationInfo> modelOperations = client.GetOperationsAsync();

            string operationId = string.Empty;
            int    count       = 0;
            await foreach (ModelOperationInfo modelOperationInfo in modelOperations)
            {
                Console.WriteLine($"Model operation info:");
                Console.WriteLine($"  Id: {modelOperationInfo.OperationId}");
                Console.WriteLine($"  Kind: {modelOperationInfo.Kind}");
                Console.WriteLine($"  Status: {modelOperationInfo.Status}");
                Console.WriteLine($"  Percent completed: {modelOperationInfo.PercentCompleted}");
                Console.WriteLine($"  Created on: {modelOperationInfo.CreatedOn}");
                Console.WriteLine($"  LastUpdated on: {modelOperationInfo.LastUpdatedOn}");
                Console.WriteLine($"  Resource location of successful operation: {modelOperationInfo.ResourceLocation}");

                if (count == 0)
                {
                    operationId = modelOperationInfo.OperationId;
                }

                if (++count == 10)
                {
                    break;
                }
            }

            // Get an operation by ID
            ModelOperation specificOperation = await client.GetOperationAsync(operationId);

            if (specificOperation.Status == DocumentOperationStatus.Succeeded)
            {
                Console.WriteLine($"My {specificOperation.Kind} operation is completed.");
                DocumentModel result = specificOperation.Result;
                Console.WriteLine($"Model ID: {result.ModelId}");
            }
            else if (specificOperation.Status == DocumentOperationStatus.Failed)
            {
                Console.WriteLine($"My {specificOperation.Kind} operation failed.");
                ResponseError error = specificOperation.Error;
                Console.WriteLine($"Code: {error.Code}: Message: {error.Message}");
            }
            else
            {
                Console.WriteLine($"My {specificOperation.Kind} operation status is {specificOperation.Status}");
            }
            #endregion
        }