// authenticate form recognizer client Navigation static private FormRecognizerClient AuthenticateFormNavigationClient() { var navigationCredential = new AzureKeyCredential(apiKeyNavigation); var navigationRecognizerClient = new FormRecognizerClient(new Uri(endpointNavigation), navigationCredential); return(navigationRecognizerClient); }
// </snippet_trainlabels_response> // <snippet_analyze> // Analyze PDF form data private static async Task AnalyzePdfForm( FormRecognizerClient recognizerClient, Guid modelId, string formUrl) { Response<IReadOnlyList<RecognizedForm>> forms = await recognizerClient .StartRecognizeCustomFormsFromUri(modelId.ToString(), new Uri(formUrl)) .WaitForCompletionAsync(); // </snippet_analyze> // <snippet_analyze_response> foreach (RecognizedForm form in forms.Value) { Console.WriteLine($"Form of type: {form.FormType}"); foreach (FormField field in form.Fields.Values) { Console.WriteLine($"Field '{field.Name}: "); if (field.LabelText != null) { Console.WriteLine($" Label: '{field.LabelText.Text}"); } Console.WriteLine($" Value: '{field.ValueText.Text}"); Console.WriteLine($" Confidence: '{field.Confidence}"); } } }
// </snippet_calls> // <snippet_getcontent_call> private static async Task GetContent( FormRecognizerClient recognizerClient, string invoiceUri) { Response<FormPageCollection> formPages = await recognizerClient .StartRecognizeContentFromUri(new Uri(invoiceUri)) .WaitForCompletionAsync(); // </snippet_getcontent_call> // <snippet_getcontent_print> foreach (FormPage page in formPages.Value) { Console.WriteLine($"Form Page {page.PageNumber} has {page.Lines.Count}" + $" lines."); for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; Console.WriteLine($" Line {i} has {line.Words.Count}" + $" word{(line.Words.Count > 1 ? "s" : "")}," + $" and text: '{line.Text}'."); } 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) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex})" + $" contains text: '{cell.Text}'."); } } } }
// </snippet_train_return> // <snippet_trainlabels> private static async Task <Guid> TrainModelWithLabelsAsync( FormRecognizerClient trainingClient, string trainingDataUrl) { CustomFormModel model = await trainingClient .StartTrainingAsync(new Uri(trainingDataUrl), useTrainingLabels : true) .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_trainlabels> // <snippet_trainlabels_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(""); } } return(model.ModelId); }
// </snippet_auth_training> // <snippet_getcontent_call> private static async Task RecognizeContent(FormRecognizerClient recognizerClient) { var invoiceUri = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/simple-invoice.png"; FormPageCollection formPages = await recognizerClient .StartRecognizeContentFromUri(new Uri(invoiceUri)) .WaitForCompletionAsync(); // </snippet_getcontent_call> // <snippet_getcontent_print> foreach (FormPage page in formPages) { Console.WriteLine($"Form Page {page.PageNumber} has {page.Lines.Count} lines."); for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; Console.WriteLine($" Line {i} has {line.Words.Count} word{(line.Words.Count > 1 ? "s" : "")}, and text: '{line.Text}'."); } 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) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains text: '{cell.Text}'."); } } } }
private static async Task RecognizeContent(FormRecognizerClient recognizerClient, string formUrl) { FormPageCollection formPages = await recognizerClient .StartRecognizeContentFromUri(new Uri(formUrl)) .WaitForCompletionAsync(); foreach (FormPage page in formPages) { //lines for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; //returnString += $"{line.Text}{Environment.NewLine}"; returnString += $" Line {i} has {line.Words.Count} word{(line.Words.Count > 1 ? "s" : "")}, and text: '{line.Text}'.{Environment.NewLine}"; } //tables for (int i = 0; i < page.Tables.Count; i++) { FormTable table = page.Tables[i]; foreach (FormTableCell cell in table.Cells) { //returnString += $"{cell.Text} "; returnString += $" Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains text: '{cell.Text}'.{Environment.NewLine}"; } } } }
// </snippet_main> // <snippet_maintask> static async Task RunFormRecognizerClient() { // Create form client object with Form Recognizer subscription key IFormRecognizerClient formClient = new FormRecognizerClient( new ApiKeyServiceClientCredentials(subscriptionKey)) { Endpoint = formRecognizerEndpoint }; Console.WriteLine("Train Model with training data..."); Guid modelId = await TrainModelAsync(formClient, trainingDataUrl); Console.WriteLine("Get list of extracted keys..."); await GetListOfExtractedKeys(formClient, modelId); // Choose any of the following three Analyze tasks: Console.WriteLine("Analyze PDF form..."); await AnalyzePdfForm(formClient, modelId, pdfFormFile); //Console.WriteLine("Analyze JPEG form..."); //await AnalyzeJpgForm(formClient, modelId, jpgFormFile); //Console.WriteLine("Analyze PNG form..."); //await AnalyzePngForm(formClient, modelId, pngFormFile); Console.WriteLine("Get list of trained models ..."); await GetListOfModels(formClient); Console.WriteLine("Delete Model..."); await DeleteModel(formClient, modelId); }
private FormRecognizerClient Authenticate(string endpoint, string key) { var credential = new AzureKeyCredential(key); var client = new FormRecognizerClient(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 async Task InitializeAsync() { DataProvider = new DataProviderFactory().GetDataProvider(Env.GetString("AZURE_STORAGE_TYPE")); await DataProvider.InitializeAsync(credential); // App Config ConfigurationClient = new ConfigurationClient(new Uri(Env.GetString("AZURE_APP_CONFIG_ENDPOINT")), credential); // Blob BlobServiceClient = new BlobServiceClient(new Uri(Env.GetString("AZURE_STORAGE_BLOB_ENDPOINT")), credential); ContainerClient = BlobServiceClient.GetBlobContainerClient(Env.GetString("AZURE_STORAGE_BLOB_CONTAINER_NAME")); await ContainerClient.CreateIfNotExistsAsync(PublicAccessType.BlobContainer); // Queue QueueServiceClient = new QueueServiceClient(new Uri(Env.GetString("AZURE_STORAGE_QUEUE_ENDPOINT")), credential); QueueClient = QueueServiceClient.GetQueueClient(Env.GetString("AZURE_STORAGE_QUEUE_NAME")); await QueueClient.CreateIfNotExistsAsync(); // FormRecognizerClient FormRecognizerClient = new FormRecognizerClient( new Uri(Env.GetString("AZURE_FORM_RECOGNIZER_ENDPOINT")), credential); // TextAnalyticsClient TextAnalyticsClient = new TextAnalyticsClient( new Uri(Env.GetString("AZURE_TEXT_ANALYTICS_ENDPOINT")), credential); }
public FormRecognizerService(FormRecognizerServiceOptions configuration) { var endpoint = configuration.Endpoint ?? throw new ArgumentException("endpoint"); var apiKey = configuration.ApiKey ?? throw new ArgumentException("apiKey"); client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); }
public async Task RecognizeContentFromFile() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); string invoiceFilePath = FormRecognizerTestEnvironment.CreatePath("Invoice_1.pdf"); using (FileStream stream = new FileStream(invoiceFilePath, FileMode.Open)) { FormPageCollection formPages = await client.StartRecognizeContent(stream).WaitForCompletionAsync(); foreach (FormPage page in formPages) { Console.WriteLine($"Form Page {page.PageNumber} has {page.Lines.Count} lines."); for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; Console.WriteLine($" Line {i} has {line.Words.Count} word{(line.Words.Count > 1 ? "s" : "")}, and text: '{line.Text}'."); } 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) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains text: '{cell.Text}'."); } } } } }
public FormRecognizerService(string subscriptionKey, string endpoint) { client = new FormRecognizerClient(new ApiKeyServiceClientCredentials(subscriptionKey)) { Endpoint = endpoint }; }
// authenticate form recognizer client Definition static private FormRecognizerClient AuthenticateFormDefinitionClient() { var definitionCredential = new AzureKeyCredential(apiKeyDefinition); var definitionRecognizerClient = new FormRecognizerClient(new Uri(endpointDefinition), definitionCredential); return(definitionRecognizerClient); }
public async Task RecognizeCustomFormsFromUri() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); string formUri = FormRecognizerTestEnvironment.CreateUri("Form_1.jpg"); string modelId = "<your model id>"; #region Snippet:FormRecognizerSample3RecognizeCustomFormsFromUri Response <IReadOnlyList <RecognizedForm> > forms = await client.StartRecognizeCustomFormsFromUri(modelId, new Uri(formUri)).WaitForCompletionAsync(); foreach (RecognizedForm form in forms.Value) { Console.WriteLine($"Form of type: {form.FormType}"); foreach (FormField field in form.Fields.Values) { Console.WriteLine($"Field '{field.Name}: "); if (field.LabelText != null) { Console.WriteLine($" Label: '{field.LabelText.Text}"); } Console.WriteLine($" Value: '{field.ValueText.Text}"); Console.WriteLine($" Confidence: '{field.Confidence}"); } } #endregion }
private static async Task RecognizeContent(FormRecognizerClient recognizerClient) { var invoiceUri = "https://raw.githubusercontent.com/Azure/azure-sdk-for-python/master/sdk/formrecognizer/azure-ai-formrecognizer/tests/sample_forms/forms/Invoice_1.pdf"; FormPageCollection formPages = await recognizerClient .StartRecognizeContentFromUri(new Uri(invoiceUri)) .WaitForCompletionAsync(); foreach (FormPage page in formPages) { Console.WriteLine($"Form Page {page.PageNumber} has {page.Lines.Count} lines."); for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; Console.WriteLine($" Line {i} has {line.Words.Count} word{(line.Words.Count > 1 ? "s" : "")}, and text: '{line.Text}'."); } 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) { Console.WriteLine($" Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains text: '{cell.Text}'."); } } } }
public async Task FieldBoundingBoxSample() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); string invoiceFilePath = FormRecognizerTestEnvironment.CreatePath("Invoice_1.pdf"); using (FileStream stream = new FileStream(invoiceFilePath, FileMode.Open)) { FormPageCollection formPages = await client.StartRecognizeContentAsync(stream).WaitForCompletionAsync(); foreach (FormPage page in formPages) { Console.WriteLine($"Form Page {page.PageNumber} has {page.Lines.Count} lines."); for (int i = 0; i < page.Lines.Count; i++) { FormLine line = page.Lines[i]; Console.WriteLine($" Line {i} with text: '{line.Text}'."); Console.WriteLine(" Its bounding box is:"); Console.WriteLine($" Upper left => X: {line.BoundingBox[0].X}, Y= {line.BoundingBox[0].Y}"); Console.WriteLine($" Upper right => X: {line.BoundingBox[1].X}, Y= {line.BoundingBox[1].Y}"); Console.WriteLine($" Lower right => X: {line.BoundingBox[2].X}, Y= {line.BoundingBox[2].Y}"); Console.WriteLine($" Lower left => X: {line.BoundingBox[3].X}, Y= {line.BoundingBox[3].Y}"); } } } }
// </snippet_trainlabels_response> // <snippet_analyze> // Analyze PDF form data private static async Task AnalyzePdfForm( FormRecognizerClient recognizerClient, Guid modelId, string formUrl) { RecognizedFormCollection forms = await recognizeClient.StartRecognizeCustomFormsFromUri(modelId, new Uri(invoiceUri)).WaitForCompletionAsync(); // </snippet_analyze> // <snippet_analyze_response> 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}"); } Console.WriteLine("Table data:"); foreach(FormPage page in form.Pages.Values) { 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) { Console.WriteLine($ " Cell ({cell.RowIndex}, {cell.ColumnIndex}) contains {(cell.IsHeader ? " header " : " text ")}: '{cell.Text}'"); } } } } }
public void CreateFormTrainingClientFromFormRecognizerClient() { FormRecognizerClient client = CreateInstrumentedClient(); FormTrainingClient trainingClient = client.GetFormTrainingClient(); Assert.IsNotNull(trainingClient); }
// </snippet_main> // <snippet_auth> static private FormRecognizerClient AuthenticateClient() { 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 FormRecognizerClient(new Uri(endpoint), credential); return client; }
public async Task RecognizeCustomFormsFromFile() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); string formFilePath = FormRecognizerTestEnvironment.CreatePath("Form_1.jpg"); string modelId = "<your model id>"; using (FileStream stream = new FileStream(formFilePath, FileMode.Open)) { Response <IReadOnlyList <RecognizedForm> > forms = await client.StartRecognizeCustomForms(modelId, stream).WaitForCompletionAsync(); foreach (RecognizedForm form in forms.Value) { Console.WriteLine($"Form of type: {form.FormType}"); foreach (FormField field in form.Fields.Values) { Console.WriteLine($"Field '{field.Name}: "); if (field.LabelText != null) { Console.WriteLine($" Label: '{field.LabelText.Text}"); } Console.WriteLine($" Value: '{field.ValueText.Text}"); Console.WriteLine($" Confidence: '{field.Confidence}"); } } } }
// </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) ; }
// </snippet_main> // <snippet_auth> private static FormRecognizerClient AuthenticateClient() { var credential = new AzureKeyCredential(apiKey); var client = new FormRecognizerClient(new Uri(endpoint), credential); return(client); }
/// <summary> /// Initializes a new instance of the <see cref="RecognizeCustomFormsOperation"/> class which /// tracks the status of a long-running operation for recognizing fields and other content from forms by using custom /// trained models. /// </summary> /// <param name="operationId">The ID of this operation.</param> /// <param name="client">The client used to check for completion.</param> public RecognizeCustomFormsOperation(string operationId, FormRecognizerClient client) { Argument.AssertNotNullOrEmpty(operationId, nameof(operationId)); Argument.AssertNotNull(client, nameof(client)); _serviceClient = client.ServiceClient; _diagnostics = client.Diagnostics; // TODO: Use regex to parse ids. // https://github.com/Azure/azure-sdk-for-net/issues/11505 // TODO: Add validation here (should we store _resuldId and _modelId as GUIDs?) // https://github.com/Azure/azure-sdk-for-net/issues/10385 string[] substrs = operationId.Split('/'); if (substrs.Length < 3) { throw new ArgumentException($"Invalid '{nameof(operationId)}'. It should be formatted as: '{{modelId}}/analyzeresults/{{resultId}}'.", nameof(operationId)); } _resultId = substrs.Last(); _modelId = substrs.First(); Id = operationId; }
public AzureFormRecognizer() { dictionaries = new Dictionary <string, int>[] { companyDic, nameDic, jobTitleDic, phoneDic, mobileDic, phoneDic, emailDic, faxDic, addressDic, natureDic }; assignedValues = new ArrayList(); //check key and endpoint recognizerClient = new FormRecognizerClient(new Uri(Constants.AFRendpoint), new AzureKeyCredential(Constants.AFRapiKey)); }
public async Task analyzePdfForm( FormRecognizerClient recognizerClient, string modelId, string pdfToAnalyzeLocalPath, ModelType processingModelType) { using (FileStream pdfInputstream = new FileStream(pdfToAnalyzeLocalPath, FileMode.Open)) { RecognizedFormCollection recognizedForms = await recognizerClient .StartRecognizeCustomForms(modelId, pdfInputstream) .WaitForCompletionAsync(); switch (processingModelType) { case ModelType.NAVIGATION: pdfToAnalyzeLocalPath = pdfToAnalyzeLocalPath + "_Navig"; break; case ModelType.DEFINITION: pdfToAnalyzeLocalPath = pdfToAnalyzeLocalPath + "_Defin"; break; } writeRecognizedFormCollectionToDB(pdfToAnalyzeLocalPath, recognizedForms); } }
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); }
private static async Task TestUrl(string endpoint, string apiKey, string modelId, string url) { FormRecognizerClient client = new FormRecognizerClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); Uri formFileUri = new Uri(url); RecognizeCustomFormsOperation operation = await client.StartRecognizeCustomFormsFromUriAsync(modelId, formFileUri); 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}'"); } } }
/// <summary> /// Initializes a new instance of the <see cref="RecognizeReceiptsOperation"/> class. /// </summary> /// <param name="operationId">The ID of this operation.</param> /// <param name="client">The client used to check for completion.</param> public RecognizeReceiptsOperation(string operationId, FormRecognizerClient client) { // TODO: Add argument validation here. Id = operationId; _serviceClient = client.ServiceClient; }
public async Task <docu3clist> ClassifyDocument(string doc_type, string formUri) { docu3clist docs = new docu3clist(); string modelId = GetModelID(doc_type); try { WebClient wc = new WebClient(); byte[] imageBytes = wc.DownloadData(formUri); var stream = new MemoryStream(imageBytes); FormRecognizerClient recognizerClient = new FormRecognizerClient(new Uri(endpoint), credential); //var forms = await recognizerClient.StartRecognizeCustomFormsFromUri(modelId,new Uri(formUri)).WaitForCompletionAsync(); //Response<IReadOnlyList<RecognizedForm>> var forms = await recognizerClient.StartRecognizeCustomForms(modelId, stream).WaitForCompletionAsync(); foreach (RecognizedForm form in forms.Value) { docu3c doc = new docu3c(); doc.docID = formUri; doc.docURL = formUri; doc.docType = form.FormType; doc.docProps = new Dictionary <string, docu3cProp>(); foreach (FormField field in form.Fields.Values) { if (field != null) { docu3cProp prop = new docu3cProp(); prop.Name = field.Name; if (field.LabelText != null) { prop.Label = field.LabelText; } if (field.Name == "doc.type") { prop.Value = field.ValueText.Text.Replace(" ", "_"); } else { prop.Value = field.ValueText.Text; } prop.Confidence = field.Confidence; doc.docProps.Add(field.Name, prop); } } docs.Add(doc); } //docs.html = docu3cAPI.SetDocHTML(docs); return(docs); } catch (Exception ex) { docu3c doc = new docu3c(); doc.docParseErrorMsg = ex.Message; docs.Add(doc); return(docs); } }