public async Task RecognizeContentFromUri()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            Uri formUri = FormRecognizerTestEnvironment.CreateUri("Invoice_1.pdf");

            #region Snippet:FormRecognizerSampleRecognizeContentFromUri
            //@@ Uri formUri = <formUri>;

            Response <FormPageCollection> response = await client.StartRecognizeContentFromUriAsync(formUri).WaitForCompletionAsync();

            FormPageCollection formPages = response.Value;

            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} {(line.Words.Count == 1 ? "word" : "words")}, and 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}");
                }

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

                for (int i = 0; i < page.SelectionMarks.Count; i++)
                {
                    FormSelectionMark selectionMark = page.SelectionMarks[i];
                    Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
                    Console.WriteLine("    Its bounding box is:");
                    Console.WriteLine($"      Upper left => X: {selectionMark.BoundingBox[0].X}, Y= {selectionMark.BoundingBox[0].Y}");
                    Console.WriteLine($"      Upper right => X: {selectionMark.BoundingBox[1].X}, Y= {selectionMark.BoundingBox[1].Y}");
                    Console.WriteLine($"      Lower right => X: {selectionMark.BoundingBox[2].X}, Y= {selectionMark.BoundingBox[2].Y}");
                    Console.WriteLine($"      Lower left => X: {selectionMark.BoundingBox[3].X}, Y= {selectionMark.BoundingBox[3].Y}");
                }
            }

            #endregion
        }
        public async Task RecognizeContentFromUri()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            Uri invoiceUri = FormRecognizerTestEnvironment.CreateUri("Invoice_1.pdf");

            #region Snippet:FormRecognizerSampleRecognizeContentFromUri

            FormPageCollection formPages = await client.StartRecognizeContentFromUriAsync(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}'.");
                    }
                }
            }

            #endregion
        }
Esempio n. 3
0
        public async Task RecognizeContentFromUri()
        {
            string endpoint = TestEnvironment.Endpoint;
            string apiKey   = TestEnvironment.ApiKey;

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

            #region Snippet:FormRecognizerSampleRecognizeContentFromUri
#if SNIPPET
            Uri formUri = new Uri("<formUri>");
#else
            Uri formUri = FormRecognizerTestEnvironment.CreateUri("Invoice_1.pdf");
#endif

            Response <FormPageCollection> response = await client.StartRecognizeContentFromUriAsync(formUri).WaitForCompletionAsync();

            FormPageCollection formPages = response.Value;

            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} {(line.Words.Count == 1 ? "word" : "words")}, and text: '{line.Text}'.");

                    if (line.Appearance != null)
                    {
                        // Check the style and style confidence to see if text is handwritten.
                        // Note that value '0.8' is used as an example.
                        if (line.Appearance.Style.Name == TextStyleName.Handwriting && line.Appearance.Style.Confidence > 0.8)
                        {
                            Console.WriteLine("The text is handwritten");
                        }
                    }

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

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

                for (int i = 0; i < page.SelectionMarks.Count; i++)
                {
                    FormSelectionMark selectionMark = page.SelectionMarks[i];
                    Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
                    Console.WriteLine("    Its bounding box is:");
                    Console.WriteLine($"      Upper left => X: {selectionMark.BoundingBox[0].X}, Y= {selectionMark.BoundingBox[0].Y}");
                    Console.WriteLine($"      Upper right => X: {selectionMark.BoundingBox[1].X}, Y= {selectionMark.BoundingBox[1].Y}");
                    Console.WriteLine($"      Lower right => X: {selectionMark.BoundingBox[2].X}, Y= {selectionMark.BoundingBox[2].Y}");
                    Console.WriteLine($"      Lower left => X: {selectionMark.BoundingBox[3].X}, Y= {selectionMark.BoundingBox[3].Y}");
                }
            }

            #endregion
        }
Esempio n. 4
0
        static async Task Main(string[] args)
        {
            Env.Load("../../../../.env");

            //using var listener = AzureEventSourceListener.CreateConsoleLogger();

            var cred = Identity.GetCredentialChain();

            // QueueClient
            var queueServiceClient = new QueueServiceClient(
                new Uri(Env.GetString("AZURE_STORAGE_QUEUE_ENDPOINT")), cred);

            var queueClient = queueServiceClient.GetQueueClient(Env.GetString("AZURE_STORAGE_QUEUE_NAME"));
            await queueClient.CreateIfNotExistsAsync();

            // FormRecognizerClient
            var formRecognizerClient = new FormRecognizerClient(
                new Uri(Env.GetString("AZURE_FORM_RECOGNIZER_ENDPOINT")),
                cred);

            // TextAnalyticsClient
            var textAnalyticsClient = new TextAnalyticsClient(
                new Uri(Env.GetString("AZURE_TEXT_ANALYTICS_ENDPOINT")),
                cred);

            // CosmosClient
            var cosmosClient = new CosmosClient(
                Env.GetString("AZURE_COSMOS_ENDPOINT"),
                Env.GetString("AZURE_COSMOS_KEY"),
                new CosmosClientOptions
            {
                Diagnostics =
                {
                    IsLoggingEnabled = false
                },
                ConnectionMode    = ConnectionMode.Direct,
                ConsistencyLevel  = ConsistencyLevel.Session,
                SerializerOptions = new CosmosSerializationOptions {
                    PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase, IgnoreNullValues = true
                },
            });

            // Create Database and Container
            var databaseResponse = await cosmosClient.CreateDatabaseIfNotExistsAsync(Env.GetString("AZURE_COSMOS_DB"));

            var containerResponse = await databaseResponse.Database.CreateContainerIfNotExistsAsync(new ContainerProperties(Env.GetString("AZURE_COSMOS_CONTAINER"), "/uid"));

            while (true)
            {
                Console.WriteLine("Receiving Messages...");

                // Get Messages
                var messages = await queueClient.ReceiveMessagesAsync(maxMessages : Env.GetInt("AZURE_STORAGE_QUEUE_MSG_COUNT", 10));

                foreach (var message in messages.Value)
                {
                    Console.WriteLine(message.MessageText);

                    // Deserialize Message
                    var image = JsonSerializer.Deserialize <Image>(message.MessageText,
                                                                   new JsonSerializerOptions {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    });

                    // Extract Text from Image
                    var recognizeContentOperation = await formRecognizerClient.StartRecognizeContentFromUriAsync(new Uri(image.BlobUri));

                    var recognizeContentCompletion = await recognizeContentOperation.WaitForCompletionAsync();

                    var content = recognizeContentCompletion.Value;
                    var text    = content.SelectMany(page => page.Lines).Aggregate(new StringBuilder(), (a, b) =>
                    {
                        a.Append($"{b.Text} ");
                        return(a);
                    });

                    image.Text = text.ToString();

                    if (!string.IsNullOrEmpty(image.Text))
                    {
                        Console.WriteLine($"Image Text: {image.Text}");

                        // Analyize Text Sentiment
                        var documentSentiment = await textAnalyticsClient.AnalyzeSentimentAsync(image.Text);

                        image.Sentiment = documentSentiment.Value.Sentiment.ToString();

                        Console.WriteLine($"Image Sentiment: {image.Sentiment}");
                    }
                    else
                    {
                        Console.WriteLine("No Text Extracted from Image.");
                    }

                    // Create Cosmos Document
                    var document = await containerResponse.Container.UpsertItemAsync(image);

                    Console.WriteLine($"Cosmos Document Saved: {document.Value.Id}");

                    // Delete Queue Message
                    var deleteResponse = await queueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);

                    Console.WriteLine($"Queue Message Deleted: {message.MessageId}");
                }
                await Task.Delay(TimeSpan.FromSeconds(Env.GetInt("AZURE_STORAGE_QUEUE_RECEIVE_SLEEP", 1)));
            }
        }