Example #1
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 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>
 /// Deletes the model this instance is associated with.
 /// </summary>
 public async ValueTask DisposeAsync() => await _adminClient.DeleteModelAsync(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);
        }
Example #6
0
        public async Task ManageModelsAsync()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

            #region Snippet:FormRecognizerSampleManageModelsAsync

            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 = await client.GetAccountPropertiesAsync();

            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.
            AsyncPageable <DocumentModelInfo> models = client.GetModelsAsync();

            int count = 0;
            await foreach (DocumentModelInfo modelInfo in models)
            {
                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}");
                if (++count == 10)
                {
                    break;
                }
            }

            // Create a new model to store in the account
#if SNIPPET
            Uri trainingFileUri = < trainingFileUri >;
#else
            Uri trainingFileUri = new Uri(TestEnvironment.BlobContainerSasUrl);
#endif
            BuildModelOperation operation = await client.StartBuildModelAsync(trainingFileUri, DocumentBuildMode.Template);

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

            DocumentModel model = operationResponse.Value;

            // Get the model that was just created
            DocumentModel newCreatedModel = await client.GetModelAsync(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 model from the account.
            await client.DeleteModelAsync(newCreatedModel.ModelId);

            #endregion
        }