Skip to content

Commit 531087d

Browse files
authored
Merge pull request #34 from TakaValley/TaKaValley/Add-Net-SDK-sample
add SDK sample for .Net
2 parents b801b73 + fdf2eff commit 531087d

22 files changed

+1349
-0
lines changed
180 KB
Loading
157 KB
Loading
76.6 KB
Binary file not shown.
88.3 KB
Binary file not shown.
2.72 MB
Loading
179 KB
Loading
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// coding: utf - 8
2+
// --------------------------------------------------------------------------
3+
// Copyright(c) Microsoft Corporation. All rights reserved.
4+
// Licensed under the MIT License. See License.txt in the project root for
5+
// license information.
6+
// --------------------------------------------------------------------------
7+
using Azure.AI.DocumentIntelligence;
8+
9+
namespace Quickstarts
10+
{
11+
public static class SdkExtension
12+
{
13+
/// <summary>
14+
/// Parse the BoundingRegion to coordinate boundary
15+
/// </summary>
16+
/// <param name="boundingRegion">BoundingRegion</param>
17+
/// <returns> the important coordinate boundary </returns>
18+
public static (float, float, float, float) CoordinateBoundary(this BoundingRegion boundingRegion)
19+
{
20+
// To learn more about bounding regions, see https://aka.ms/bounding-region
21+
var x_left = boundingRegion.Polygon[0];
22+
var y_top = boundingRegion.Polygon[1];
23+
var x_right = boundingRegion.Polygon[4];
24+
var y_bottom = boundingRegion.Polygon[5];
25+
26+
return (x_left, y_top, x_right, y_bottom);
27+
}
28+
}
29+
}
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
// coding: utf - 8
2+
// --------------------------------------------------------------------------
3+
// Copyright(c) Microsoft Corporation. All rights reserved.
4+
// Licensed under the MIT License. See License.txt in the project root for
5+
// license information.
6+
// --------------------------------------------------------------------------
7+
8+
using Azure.AI.DocumentIntelligence;
9+
10+
namespace Quickstarts
11+
{
12+
public class Utils
13+
{
14+
/// <summary>
15+
/// Extract value from AnalyzeResult.Document[n].Fields . This function could extract descendant child DocumentField by recursion.
16+
/// </summary>
17+
/// <param name="key">The key to display</param>
18+
/// <param name="docField">The DocumentField value to extract</param>
19+
/// <param name="isSubItem">Indicates whether the current DocumentField is a descendant element</param>
20+
public static void ExtractValueFromDocumentField(string key, DocumentField docField, bool isSubItem = false)
21+
{
22+
var valueStr = "";
23+
24+
if (docField.Type == DocumentFieldType.String)
25+
{
26+
valueStr = docField.ValueString;
27+
}
28+
else if (docField.Type == DocumentFieldType.Currency)
29+
{
30+
CurrencyValue currencyVal = docField.ValueCurrency;
31+
valueStr = $"{currencyVal.CurrencySymbol}{currencyVal.Amount}";
32+
}
33+
else if (docField.Type == DocumentFieldType.Address)
34+
{
35+
valueStr = $"{docField.ValueAddress.HouseNumber}, {docField.ValueAddress.Road}, {docField.ValueAddress.City}, " +
36+
$"{docField.ValueAddress.State}, {docField.ValueAddress.PostalCode}";
37+
}
38+
else if (docField.Type == DocumentFieldType.Date)
39+
{
40+
valueStr = docField.ValueDate.ToString();
41+
}
42+
else if (docField.Type == DocumentFieldType.Dictionary)
43+
{
44+
// if current DocumentField type is an Object, extract each property in Object.
45+
IReadOnlyDictionary<string, DocumentField> itemFields = docField.ValueDictionary;
46+
foreach (var item in itemFields)
47+
{
48+
ExtractValueFromDocumentField(item.Key, item.Value, isSubItem);
49+
}
50+
51+
return;
52+
}
53+
else if (docField.Type == DocumentFieldType.List)
54+
{
55+
Console.WriteLine(key);
56+
if (docField.ValueList.Count > 0)
57+
{
58+
// if current DocumentField type is an array, extract each member in array.
59+
for (var i = 0; i < docField.ValueList.Count; i++)
60+
{
61+
Console.WriteLine($" Index {i} :");
62+
ExtractValueFromDocumentField(key, docField.ValueList[i], true);
63+
}
64+
}
65+
66+
return;
67+
}
68+
else
69+
{
70+
valueStr = docField.Content;
71+
}
72+
73+
var keyStr = isSubItem ? $" {key}" : key;
74+
Console.WriteLine($"{keyStr} : '{valueStr}', with confidence {docField.Confidence}");
75+
}
76+
77+
/// <summary>
78+
/// Get the file extension name from url.
79+
/// </summary>
80+
/// <param name="url"> url of online file </param>
81+
/// <returns></returns>
82+
public static string GetExtensionFromUrl(string url)
83+
{
84+
var pathArr = url.Split("?");
85+
var extStr = System.IO.Path.GetExtension(pathArr[0]);
86+
return extStr;
87+
}
88+
89+
90+
#region colorful output for good console visual effect
91+
public static void ConsoleWarningWrite(string text)
92+
{
93+
Console.ForegroundColor = ConsoleColor.Red;
94+
Console.BackgroundColor = ConsoleColor.DarkYellow;
95+
Console.Write(text);
96+
Console.ResetColor();
97+
}
98+
99+
public static void ConsoleWarningWriteLine(string text)
100+
{
101+
Console.ForegroundColor = ConsoleColor.Red;
102+
Console.BackgroundColor = ConsoleColor.DarkYellow;
103+
Console.WriteLine(text);
104+
Console.ResetColor();
105+
}
106+
107+
108+
public static void ConsoleHighlightWrite(string text)
109+
{
110+
Console.ForegroundColor = ConsoleColor.Yellow;
111+
Console.Write(text);
112+
Console.ResetColor();
113+
}
114+
115+
public static void ConsoleHighlightWriteLine(string text)
116+
{
117+
Console.ForegroundColor = ConsoleColor.Yellow;
118+
Console.WriteLine(text);
119+
Console.ResetColor();
120+
}
121+
122+
public static void ConsoleImportantWrite(string text)
123+
{
124+
Console.ForegroundColor = ConsoleColor.Green;
125+
Console.Write(text);
126+
Console.ResetColor();
127+
}
128+
129+
public static void ConsoleImportantWriteLine(string text)
130+
{
131+
Console.ForegroundColor = ConsoleColor.Green;
132+
Console.WriteLine(text);
133+
Console.ResetColor();
134+
}
135+
#endregion
136+
}
137+
}
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
// coding: utf - 8
2+
// --------------------------------------------------------------------------
3+
// Copyright(c) Microsoft Corporation. All rights reserved.
4+
// Licensed under the MIT License. See License.txt in the project root for
5+
// license information.
6+
// --------------------------------------------------------------------------
7+
8+
using ConsoleTables;
9+
using System.Configuration;
10+
using System.Diagnostics;
11+
12+
namespace Quickstarts
13+
{
14+
internal class Program
15+
{
16+
const string GNU_PARAM_SYMBOL = " --";
17+
static readonly ConsoleTable helpTable = new(["FunctionName", "Description"]);
18+
static readonly List<(string, string)> sampleFunctionList = [
19+
("ExtractLayoutAsync", "Sample - Extract the layout of a document"),
20+
("AnalyzeWithPrebuiltModel", "Sample - Analyze a document with a prebuilt model"),
21+
("ExtractHighResolution", "Sample - Add-on : High resolution extraction"),
22+
("ExtractFormula", "Sample - Add-on : Formula extraction"),
23+
("ExtractFontProperty", "Sample - Add-on : Font property extraction"),
24+
("ExtractBarcodeProperty", "Sample - Add-on : Barcode property extraction"),
25+
("ExtractKeyValuePairs", "Sample - Add-on : Key-value pairs extraction"),
26+
("DetectLanguage", "Sample - Add-on : Language detection")];
27+
28+
/// <summary>
29+
/// Here is the entrance for the Azure Document Intelligence client SDK Samples.
30+
/// </summary>
31+
/// <returns></returns>
32+
static async Task Main()
33+
{
34+
Console.WriteLine("Hello, welcome to the Azure Document Intelligence client SDK Sample Codes for .Net!");
35+
36+
// Read the Azure Document Intelligence endpoint and apikey from app.config.
37+
// For how to obtain the endpoint and apikey, please see Prerequisites in README.md .
38+
var docIntelligenceEndPoint = ConfigurationManager.AppSettings["AZURE_DOCUMENT_INTELLIGENCE_ENDPOINT"];
39+
var docIntelligenceApiKey = ConfigurationManager.AppSettings["AZURE_DOCUMENT_INTELLIGENCE_KEY"];
40+
if (string.IsNullOrWhiteSpace(docIntelligenceEndPoint) || string.IsNullOrWhiteSpace(docIntelligenceApiKey))
41+
{
42+
var exceptionStr = "Missing the Azure Document Intelligence EndPoint and ApiKey.";
43+
Console.WriteLine(exceptionStr);
44+
Console.WriteLine("Press the 'Enter' for getting help.");
45+
Console.ReadLine();
46+
Process.Start(new ProcessStartInfo("https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/quickstarts/get-started-sdks-rest-api?view=doc-intel-4.0.0&pivots=programming-language-csharp#prerequisites") { UseShellExecute = true });
47+
throw new ArgumentException(exceptionStr);
48+
}
49+
50+
Type sampleType = typeof(Samples);
51+
var sampleInstance = new Samples(docIntelligenceEndPoint!, docIntelligenceApiKey!);
52+
53+
sampleFunctionList.ForEach(f =>
54+
{
55+
(string funcName, string description) = f;
56+
helpTable.AddRow(funcName, description);
57+
});
58+
PrintHelpInfo();
59+
60+
bool running = true;
61+
while (running)
62+
{
63+
Console.WriteLine("Please input the command which you want to execute:");
64+
string? commandStr = Console.ReadLine();
65+
if (!string.IsNullOrWhiteSpace(commandStr))
66+
{
67+
switch (commandStr.ToLower())
68+
{
69+
case "help": PrintHelpInfo(); break;
70+
case "cls": Console.Clear(); break;
71+
case "quit":
72+
case "exit": running = false; break;
73+
default:
74+
var commandArr = commandStr.Split(GNU_PARAM_SYMBOL);
75+
if (commandArr.Length >= 1)
76+
{
77+
var funcName = commandArr[0];
78+
var methodInfo = sampleType.GetMethod(funcName);
79+
if (methodInfo != null)
80+
{
81+
Console.WriteLine();
82+
Utils.ConsoleImportantWriteLine($"Running function: {commandStr}");
83+
84+
object? taskResult = null;
85+
if (commandArr.Length > 1)
86+
{
87+
var paramKVP = commandArr[1].Split(" ");
88+
var paramName = paramKVP[0].ToLower();
89+
var paramValue = paramKVP[1].Trim('"').Trim('\'');
90+
if (paramName == "path")
91+
{
92+
taskResult = methodInfo.Invoke(sampleInstance, [paramValue, ""]);
93+
}
94+
else if (paramName == "url")
95+
{
96+
taskResult = methodInfo.Invoke(sampleInstance, ["", paramValue]);
97+
}
98+
else
99+
{
100+
Console.WriteLine("No corresponding parameter, please check it!");
101+
PrintHelpInfo();
102+
}
103+
}
104+
else
105+
{
106+
taskResult = methodInfo.Invoke(sampleInstance, ["", ""]);
107+
}
108+
109+
if (taskResult != null)
110+
{
111+
await (Task)taskResult;
112+
}
113+
}
114+
else
115+
{
116+
Console.WriteLine("The syntax format is incorrect, please check it!");
117+
PrintHelpInfo();
118+
}
119+
}
120+
else
121+
{
122+
Console.WriteLine("No such function");
123+
PrintHelpInfo();
124+
}
125+
break;
126+
}
127+
}
128+
}
129+
130+
Console.WriteLine("Program Exited.");
131+
}
132+
133+
/// <summary>
134+
/// Print the sample command list and help information.
135+
/// </summary>
136+
static void PrintHelpInfo()
137+
{
138+
Console.WriteLine("Here're the demo functions:");
139+
Console.ForegroundColor = ConsoleColor.Green;
140+
Console.WriteLine("--------------------------------------------------------------------------------");
141+
helpTable.Write(Format.Minimal);
142+
Console.WriteLine("--------------------------------------------------------------------------------");
143+
Console.ResetColor();
144+
Console.WriteLine("If you want to run the demo function with the sample test data, just input the function name directly.");
145+
Console.WriteLine("e.g.");
146+
Utils.ConsoleImportantWriteLine("ExtractLayoutAsync");
147+
Console.WriteLine();
148+
Console.WriteLine("If you want to execute the function with your customized data, input the function name with the parameter by GNU style, as below:");
149+
Utils.ConsoleImportantWriteLine("--path the file path to analyze in you local file system.");
150+
Utils.ConsoleImportantWriteLine("--url the file url which you expect to analyze online.");
151+
Console.WriteLine("e.g.");
152+
Utils.ConsoleImportantWriteLine("ExtractLayoutAsync --path <The file path to analyze in you local file system>");
153+
Console.WriteLine("or");
154+
Utils.ConsoleImportantWriteLine("ExtractLayoutAsync --url <The file url which you expect to analyze online>");
155+
Console.WriteLine("--------------------------------------------------------------------------------");
156+
Console.WriteLine();
157+
Console.WriteLine("Here're the console commands:");
158+
Console.WriteLine("================================================================================");
159+
Utils.ConsoleImportantWriteLine("help ------------ Print the command list");
160+
Utils.ConsoleImportantWriteLine("cls ------------ Clear the console output");
161+
Utils.ConsoleImportantWriteLine("exit | quit ------------ Exit program");
162+
Console.WriteLine("================================================================================");
163+
}
164+
}
165+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFramework>net8.0</TargetFramework>
6+
<ImplicitUsings>enable</ImplicitUsings>
7+
<Nullable>enable</Nullable>
8+
</PropertyGroup>
9+
10+
<ItemGroup>
11+
<PackageReference Include="Azure.AI.DocumentIntelligence" Version="1.0.0-beta.2" />
12+
<PackageReference Include="ConsoleTables" Version="2.6.1" />
13+
<PackageReference Include="System.Configuration.ConfigurationManager" Version="8.0.0" />
14+
</ItemGroup>
15+
16+
<ItemGroup>
17+
<Folder Include="Assets\" />
18+
</ItemGroup>
19+
20+
<Target Name="PostBuild" AfterTargets="PostBuildEvent">
21+
<Exec Command="xcopy /Y &quot;$(ProjectDir)Assets\*.*&quot; &quot;$(TargetDir)Assets\&quot;" />
22+
</Target>
23+
24+
</Project>

0 commit comments

Comments
 (0)