In this post, let's have a look at the new Azure Content Understanding Client Library for .NET.
Until now, when working with Azure Content Understanding, we had to use the Azure Content Understanding REST API directly. That meant building requests ourselves, handling responses manually, and taking care of the long-running operation flow on our own.
Now there is a proper NET client library, and that makes the experience much nicer. It follows the familiar Azure SDK for .NET patterns such as Response<T> and Operation<T>, so if you have worked with other Azure SDKs before, this will feel very natural.
As of today, this is the latest package and APIs will likely evolve over time. But even at this stage, the SDK already gives a much cleaner developer experience compared to calling the REST endpoints directly.
For the rest of this post, let's go through a simple example.
First step is installing the Azure.AI.ContentUnderstanding NuGet package.
dotnet add package Azure.AI.ContentUnderstanding
using Azure; using Azure.AI.ContentUnderstanding; using Azure.Identity; using System.Net.Mime; string endpoint = "<Endpoint>"; string analyzerId = "<AnalyzerId>"; string filePath = @"<sample-file>.pdf"; BinaryData fileData = BinaryData.FromBytes(await File.ReadAllBytesAsync(filePath)); string contentType = Path.GetExtension(filePath).ToLowerInvariant() switch { ".pdf" => MediaTypeNames.Application.Pdf, _ => throw new NotSupportedException($"File type {Path.GetExtension(filePath)} is not supported.") }; ContentUnderstandingClient contentUnderstandingClient = new(new Uri(endpoint), new DefaultAzureCredential()); Operation<AnalysisResult> operation = await contentUnderstandingClient.AnalyzeBinaryAsync( WaitUntil.Started, analyzerId, fileData, contentType: contentType); Console.WriteLine($"Operation Id: {operation.Id}, Started."); while (!operation.HasCompleted) { Console.WriteLine($"Operation Id: {operation.Id}, Running."); await Task.Delay(TimeSpan.FromSeconds(3)); await operation.UpdateStatusAsync(); } Console.WriteLine($"Operation Id: {operation.Id}, Completed.");
AnalysisResult = operation.Value;
foreach (AnalysisContent? item in analysisResult.Contents)
{ foreach (KeyValuePair<string, ContentField> field in item.Fields) { Console.WriteLine($"Field: {field.Key}: Value: {field.Value.Value}"); Console.WriteLine(); } } Console.WriteLine("Done");
Hope this helps.
Read more:
Azure Content Understanding client library for .NET
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment