public async Task StartRecognizeInvoicesSendsUserSpecifiedLocale(string locale)
        {
            var mockResponse = new MockResponse(202);

            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/prebuilt/invoice/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceJpg);
            var recognizeOptions = new RecognizeInvoicesOptions {
                Locale = locale
            };
            await client.StartRecognizeInvoicesAsync(stream, recognizeOptions);

            var requestUriQuery = mockTransport.Requests.Single().Uri.Query;

            var localeQuery = "locale=";
            var index       = requestUriQuery.IndexOf(localeQuery);
            var length      = requestUriQuery.Length - (index + localeQuery.Length);

            Assert.AreEqual(locale, requestUriQuery.Substring(index + localeQuery.Length, length));
        }
Exemple #2
0
        public async Task CreateComposedModelOperationCreatesDiagnosticScopeOnUpdate()
        {
            using var testListener = new ClientDiagnosticListener(DiagnosticNamespace);
            using var stream       = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""modelInfo"": {
                        ""status"": ""creating"",
                        ""modelId"": ""00000000-0000-0000-0000-000000000000""
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateFormTrainingClient(options);

            var operation = new CreateComposedModelOperation("00000000-0000-0000-0000-000000000000", client);

            if (IsAsync)
            {
                await operation.UpdateStatusAsync();
            }
            else
            {
                operation.UpdateStatus();
            }

            testListener.AssertScope($"{nameof(CreateCustomFormModelOperation)}.{nameof(CreateCustomFormModelOperation.UpdateStatus)}");
        }
        public async Task StartRecognizeContentFromUriEncodesBlankSpaces()
        {
            var mockResponse = new MockResponse(202);
            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/layout/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options = new FormRecognizerClientOptions() { Transport = mockTransport };
            var client = CreateInstrumentedClient(options);

            var encodedUriString = "https://fakeuri.com/blank%20space";
            var decodedUriString = "https://fakeuri.com/blank space";

            await client.StartRecognizeContentFromUriAsync(new Uri(encodedUriString));
            await client.StartRecognizeContentFromUriAsync(new Uri(decodedUriString));

            Assert.AreEqual(2, mockTransport.Requests.Count);

            foreach (var request in mockTransport.Requests)
            {
                var requestBody = GetString(request.Content);

                Assert.True(requestBody.Contains(encodedUriString));
                Assert.False(requestBody.Contains(decodedUriString));
            }
        }
        public async Task StartTrainingEncodesBlankSpaces()
        {
            var mockResponse = new MockResponse(201);

            mockResponse.AddHeader(new HttpHeader("Location", "host/custom/models/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            var encodedUriString = "https://fakeuri.com/blank%20space";
            var decodedUriString = "https://fakeuri.com/blank space";

            await client.StartTrainingAsync(new Uri(encodedUriString), useTrainingLabels : false);

            await client.StartTrainingAsync(new Uri(decodedUriString), useTrainingLabels : false);

            Assert.AreEqual(2, mockTransport.Requests.Count);

            foreach (var request in mockTransport.Requests)
            {
                var requestBody = GetString(request.Content);

                Assert.True(requestBody.Contains(encodedUriString));
                Assert.False(requestBody.Contains(decodedUriString));
            }
        }
Exemple #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomFormClient"/>.
        /// </summary>
#pragma warning disable AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service.
        public CustomFormClient(Uri endpoint, AzureKeyCredential credential, FormRecognizerClientOptions options)
#pragma warning restore AZC0007 // DO provide a minimal constructor that takes only the parameters required to connect to the service.
        {
            _diagnostics = new ClientDiagnostics(options);
            _pipeline    = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, Constants.AuthorizationHeader));
            _operations  = new ServiceClient(_diagnostics, _pipeline, endpoint.ToString());
        }
Exemple #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormTrainingClient"/>.
        /// </summary>
        public FormTrainingClient(Uri endpoint, AzureKeyCredential credential, FormRecognizerClientOptions options)
        {
            var          diagnostics = new ClientDiagnostics(options);
            HttpPipeline pipeline    = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, Constants.AuthorizationHeader));

            ServiceClient = new ServiceClient(diagnostics, pipeline, endpoint.ToString());
        }
Exemple #7
0
        public async Task RecognizeContentOperationCreatesDiagnosticScopeOnUpdate()
        {
            using var testListener = new ClientDiagnosticListener(DiagnosticNamespace);
            using var stream       = new MemoryStream(Encoding.UTF8.GetBytes("{}"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = stream;

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateFormRecognizerClient(options);

            var operation = new RecognizeContentOperation("00000000-0000-0000-0000-000000000000", client);

            if (IsAsync)
            {
                await operation.UpdateStatusAsync();
            }
            else
            {
                operation.UpdateStatus();
            }

            testListener.AssertScope($"{nameof(RecognizeContentOperation)}.{nameof(RecognizeContentOperation.UpdateStatus)}");
        }
Exemple #8
0
        /// <summary>
        /// Creates a fake <see cref="FormTrainingClient" /> with the specified set of options.
        /// </summary>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <returns>The fake <see cref="FormTrainingClient" />.</returns>
        private FormTrainingClient CreateFormTrainingClient(FormRecognizerClientOptions options = default)
        {
            var fakeEndpoint   = new Uri("http://localhost");
            var fakeCredential = new AzureKeyCredential("fakeKey");

            options ??= new FormRecognizerClientOptions();

            return(new FormTrainingClient(fakeEndpoint, fakeCredential, options));
        }
        /// <summary>
        /// Creates a fake <see cref="FormRecognizerClient" /> and instruments it to make use of the Azure Core
        /// Test Framework functionalities.
        /// </summary>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <returns>The instrumented <see cref="FormRecognizerClient" />.</returns>
        private FormRecognizerClient CreateInstrumentedClient(FormRecognizerClientOptions options = default)
        {
            var fakeEndpoint = new Uri("http://localhost");
            var fakeCredential = new AzureKeyCredential("fakeKey");
            options ??= new FormRecognizerClientOptions();

            var client = new FormRecognizerClient(fakeEndpoint, fakeCredential, options);
            return InstrumentClient(client);
        }
Exemple #10
0
        public void FormRecognizerClientOptionsClone()
        {
            var options = new FormRecognizerClientOptions();
            FormRecognizerClientOptions clone = options.Clone();

            Assert.IsNotNull(clone);
            Assert.AreNotSame(options, clone);
            Assert.AreEqual(options.Version, clone.Version);
        }
        /// <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);
        }
Exemple #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormTrainingClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// The <paramref name="endpoint"/> URI <c>string</c> can be found in the Azure Portal.
        /// </remarks>
        /// <seealso href="https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-a-form-recognizer-client"/>
        public FormTrainingClient(Uri endpoint, TokenCredential credential, FormRecognizerClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            Diagnostics = new ClientDiagnostics(options);
            var pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, Constants.DefaultCognitiveScope));

            ServiceClient = new ServiceRestClient(Diagnostics, pipeline, endpoint.AbsoluteUri);
        }
Exemple #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormTrainingClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// Both the <paramref name="endpoint"/> URI <c>string</c> and the <paramref name="credential"/> <c>string</c> key
        /// can be found in the Azure Portal.
        /// </remarks>
        /// <seealso href="https://github.com/Azure/azure-sdk-for-net/blob/master/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-a-form-recognizer-client"/>
        public FormTrainingClient(Uri endpoint, AzureKeyCredential credential, FormRecognizerClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            Diagnostics = new ClientDiagnostics(options);
            HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, Constants.AuthorizationHeader));

            ServiceClient = new ServiceRestClient(Diagnostics, pipeline, endpoint.AbsoluteUri);
        }
Exemple #14
0
        /// <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()
            {
                Retry = { Delay = TimeSpan.Zero, Mode = RetryMode.Fixed }
            };
            var client = new FormTrainingClient(fakeEndpoint, fakeCredential, options);

            return(client);
        }
Exemple #15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FormTrainingClient"/> class.
        /// </summary>
        /// <param name="endpoint">The endpoint to use for connecting to the Form Recognizer Azure Cognitive Service.</param>
        /// <param name="credential">A credential used to authenticate to an Azure Service.</param>
        /// <param name="options">A set of options to apply when configuring the client.</param>
        /// <remarks>
        /// The <paramref name="endpoint"/> URI string can be found in the Azure Portal.
        /// For more information see <see href="https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/formrecognizer/Azure.AI.FormRecognizer/README.md#authenticate-a-form-recognizer-client"> here</see>.
        /// </remarks>
        public FormTrainingClient(Uri endpoint, TokenCredential credential, FormRecognizerClientOptions options)
        {
            Argument.AssertNotNull(endpoint, nameof(endpoint));
            Argument.AssertNotNull(credential, nameof(credential));
            Argument.AssertNotNull(options, nameof(options));

            string defaultScope = $"{(string.IsNullOrEmpty(options.Audience?.ToString()) ? FormRecognizerAudience.AzurePublicCloud : options.Audience)}/.default";

            Diagnostics    = new ClientDiagnostics(options);
            ServiceVersion = options.Version;
            var pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, defaultScope));

            ServiceClient = new FormRecognizerRestClient(Diagnostics, pipeline, endpoint.AbsoluteUri, FormRecognizerClientOptions.GetVersionString(ServiceVersion));
        }
        public async Task StartRecognizeContentSendsAutoDetectedContentType()
        {
            var mockResponse = new MockResponse(202);
            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/layout/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options = new FormRecognizerClientOptions() { Transport = mockTransport };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceLeTiff);
            await client.StartRecognizeContentAsync(stream);

            var request = mockTransport.Requests.Single();

            Assert.True(request.Headers.TryGetValue("Content-Type", out var contentType));
            Assert.AreEqual("image/tiff", contentType);
        }
        public async Task StartRecognizeCustomFormsSendsUserSpecifiedContentType()
        {
            var mockResponse = new MockResponse(202);
            mockResponse.AddHeader(new HttpHeader(Constants.OperationLocationHeader, "host/custom/models/00000000000000000000000000000000/analyzeResults/00000000000000000000000000000000"));

            var mockTransport = new MockTransport(new[] { mockResponse, mockResponse });
            var options = new FormRecognizerClientOptions() { Transport = mockTransport };
            var client = CreateInstrumentedClient(options);

            using var stream = FormRecognizerTestEnvironment.CreateStream(TestFile.InvoiceLeTiff);
            var recognizeOptions = new RecognizeCustomFormsOptions { ContentType = FormContentType.Jpeg };
            await client.StartRecognizeCustomFormsAsync("00000000000000000000000000000000", stream, recognizeOptions);

            var request = mockTransport.Requests.Single();

            Assert.True(request.Headers.TryGetValue("Content-Type", out var contentType));
            Assert.AreEqual("image/jpeg", contentType);
        }
Exemple #18
0
        static async Task Main(string[] args)
        {
            var endpoint = Environment.GetEnvironmentVariable(EnvEndpoint) ?? throw new ArgumentNullException(EnvEndpoint);
            var key      = Environment.GetEnvironmentVariable(EnvApiKey) ?? throw new ArgumentNullException(EnvApiKey);

            var frEndpoint = new Uri(endpoint);
            var frKey      = new FormRecognizerApiKeyCredential(key);
            var frOptions  = new FormRecognizerClientOptions(ServiceVersion.V2_0_Preview);

            var custom   = new CustomFormClient(frEndpoint, frKey, frOptions);
            var receipts = new ReceiptClient(frEndpoint, frKey, frOptions);
            var layout   = new FormLayoutClient(frEndpoint, frKey, frOptions);

            // await TrainCustomModelWithLabels(custom);
            // await AnalyzeWithCustomModelWithLabels(custom);
            // await AnalyzeLayout(layout);
            // await AnalyzeReceipt(receipts);
            // await GetModelSummary(custom);
            // await DeleteModel(custom);

            await Task.CompletedTask;
        }
        public async Task GetCustomModelDoesNotNeedTrainResult()
        {
            // When a model is still being created, the "trainResult" property is
            // not returned. We're mimicking this behavior here to make sure that
            // we can parse the response even without the "trainResult" property.

            // Ideally this test should be live, but the service behavior is
            // non-deterministic. Any delay in sending the request could give the
            // model enough time to change its status to Ready.

            using var Stream = new MemoryStream(Encoding.UTF8.GetBytes(@"
                {
                    ""modelInfo"": {
                        ""modelId"": ""00000000-0000-0000-0000-000000000000"",
                        ""status"": ""creating"",
                        ""createdDateTime"": ""1975-04-04T00:00:00Z"",
                        ""lastUpdatedTime"": ""1975-04-04T00:00:00Z""
                    }
                }"));

            var mockResponse = new MockResponse(200);

            mockResponse.ContentStream = Stream;

            var mockTransport = new MockTransport(new[] { mockResponse });
            var options       = new FormRecognizerClientOptions()
            {
                Transport = mockTransport
            };
            var client = CreateInstrumentedClient(options);

            var response = await client.GetCustomModelAsync("00000000-0000-0000-0000-000000000000");

            var model = response.Value;

            Assert.IsEmpty(model.TrainingDocuments);
            Assert.IsEmpty(model.Errors);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="CustomFormClient"/>.
 /// </summary>
 public CustomFormClient(Uri endpoint, FormRecognizerApiKeyCredential credential, FormRecognizerClientOptions options)
 {
     _diagnostics = new ClientDiagnostics(options);
     _pipeline    = HttpPipelineBuilder.Build(options, new ApiKeyAuthenticationPolicy(credential));
     _operations  = new ServiceClient(_diagnostics, _pipeline, endpoint.ToString());
 }