Azure.AI.DocumentIntelligence (.NET)
事前構築モデルとカスタムモデルを使用して、ドキュメントからテキスト、表、構造化データを抽出します。
インストール
dotnet add package Azure.AI.DocumentIntelligence
dotnet add package Azure.Identity
現在のバージョン: v1.0.0 (GA)
環境変数
DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource-name>.cognitiveservices.azure.com/
DOCUMENT_INTELLIGENCE_API_KEY=<your-api-key>
BLOB_CONTAINER_SAS_URL=https://<storage>.blob.core.windows.net/<container>?<sas-token>
AZURE_TOKEN_CREDENTIALS=prod
認証
Microsoft Entra トークン資格情報
using Azure.Identity;
using Azure.AI.DocumentIntelligence;
string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
var client = new DocumentIntelligenceClient(new Uri(endpoint), credential);
注: Entra ID にはカスタムサブドメイン(例: https://<resource-name>.cognitiveservices.azure.com/)が必要であり、リージョンエンドポイントは使用できません。
API キー
string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
string apiKey = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_API_KEY");
var client = new DocumentIntelligenceClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
クライアントタイプ
| クライアント | 目的 |
|---|
DocumentIntelligenceClient | ドキュメントの分析、ドキュメントの分類 |
DocumentIntelligenceAdministrationClient | カスタムモデルと分類器の構築/管理 |
事前構築モデル
| モデル ID | 説明 |
|---|
prebuilt-read | テキスト、言語、手書き文字を抽出 |
prebuilt-layout | テキスト、表、選択マーク、構造を抽出 |
prebuilt-invoice | 請求書フィールド(仕入先、品目、合計)を抽出 |
prebuilt-receipt | 領収書フィールド(店舗名、品目、合計)を抽出 |
prebuilt-idDocument | ID 文書フィールド(名前、生年月日、住所)を抽出 |
prebuilt-businessCard | 名刺フィールドを抽出 |
prebuilt-tax.us.w2 | W-2 税フォームフィールドを抽出 |
prebuilt-healthInsuranceCard.us | 健康保険証フィールドを抽出 |
コアワークフロー
1. 請求書の分析
using Azure.AI.DocumentIntelligence;
Uri invoiceUri = new Uri("https://example.com/invoice.pdf");
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-invoice",
invoiceUri);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField)
&& vendorNameField.FieldType == DocumentFieldType.String)
{
string vendorName = vendorNameField.ValueString;
Console.WriteLine($"仕入先名: '{vendorName}'、信頼度: {vendorNameField.Confidence}");
}
if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
&& invoiceTotalField.FieldType == DocumentFieldType.Currency)
{
CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
Console.WriteLine($"請求書合計: '{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
}
if (document.Fields.TryGetValue("Items", out DocumentField itemsField)
&& itemsField.FieldType == DocumentFieldType.List)
{
foreach (DocumentField item in itemsField.ValueList)
{
var itemFields = item.ValueDictionary;
if (itemFields.TryGetValue("Description", out DocumentField descField))
Console.WriteLine($" 品目: {descField.ValueString}");
}
}
}
2. レイアウトの抽出(テキスト、表、構造)
Uri fileUri = new Uri("https://example.com/document.pdf");
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-layout",
fileUri);
AnalyzeResult result = operation.Value;
foreach (DocumentPage page in result.Pages)
{
Console.WriteLine($"ページ {page.PageNumber}: {page.Lines.Count} 行、{page.Words.Count} 単語");
foreach (DocumentLine line in page.Lines)
{
Console.WriteLine($" 行: '{line.Content}'");
}
}
foreach (DocumentTable table in result.Tables)
{
Console.WriteLine($"表: {table.RowCount} 行 x {table.ColumnCount} 列");
foreach (DocumentTableCell cell in table.Cells)
{
Console.WriteLine($" セル ({cell.RowIndex}, {cell.ColumnIndex}): {cell.Content}");
}
}
3. 領収書の分析
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-receipt",
receiptUri);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
if (document.Fields.TryGetValue("MerchantName", out DocumentField merchantField))
Console.WriteLine($"店舗名: {merchantField.ValueString}");
if (document.Fields.TryGetValue("Total", out DocumentField totalField))
Console.WriteLine($"合計: {totalField.ValueCurrency.Amount}");
if (document.Fields.TryGetValue("TransactionDate", out DocumentField dateField))
Console.WriteLine($"日付: {dateField.ValueDate}");
}
4. カスタムモデルの構築
var adminClient = new DocumentIntelligenceAdministrationClient(
new Uri(endpoint),
new AzureKeyCredential(apiKey));
string modelId = "my-custom-model";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");
var blobSource = new BlobContentSource(blobContainerUri);
var options = new BuildDocumentModelOptions(modelId, DocumentBuildMode.Template, blobSource);
Operation<DocumentModelDetails> operation = await adminClient.BuildDocumentModelAsync(
WaitUntil.Completed,
options);
DocumentModelDetails model = operation.Value;
Console.WriteLine($"モデル ID: {model.ModelId}");
Console.WriteLine($"作成日時: {model.CreatedOn}");
foreach (var docType in model.DocumentTypes)
{
Console.WriteLine($"ドキュメントタイプ: {docType.Key}");
foreach (var field in docType.Value.FieldSchema)
{
Console.WriteLine($" フィールド: {field.Key}、信頼度: {docType.Value.FieldConfidence[field.Key]}");
}
}
5. ドキュメント分類器の構築
string classifierId = "my-classifier";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");
var sourceA = new BlobContentSource(blobContainerUri) { Prefix = "TypeA/train" };
var sourceB = new BlobContentSource(blobContainerUri) { Prefix = "TypeB/train" };
var docTypes = new Dictionary<string, ClassifierDocumentTypeDetails>()
{
{ "TypeA", new ClassifierDocumentTypeDetails(sourceA) },
{ "TypeB", new ClassifierDocumentTypeDetails(sourceB) }
};
var options = new BuildClassifierOptions(classifierId, docTypes);
Operation<DocumentClassifierDetails> operation = await adminClient.BuildClassifierAsync(
WaitUntil.Completed,
options);
DocumentClassifierDetails classifier = operation.Value;
Console.WriteLine($"分類器 ID: {classifier.ClassifierId}");
6. ドキュメントの分類
string classifierId = "my-classifier";
Uri documentUri = new Uri("https://example.com/document.pdf");
var options = new ClassifyDocumentOptions(classifierId, documentUri);
Operation<AnalyzeResult> operation = await client.ClassifyDocumentAsync(
WaitUntil.Completed,
options);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
Console.WriteLine($"ドキュメントタイプ: {document.DocumentType}、信頼度: {document.Confidence}");
}
7. モデルの管理
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"カスタムモデル: {resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");
DocumentModelDetails model = await adminClient.GetModelAsync("my-model-id");
Console.WriteLine($"モデル: {model.ModelId}、作成日時: {model.CreatedOn}");
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
Console.WriteLine($"モデル: {modelItem.ModelId}");
}
await adminClient.DeleteModelAsync("my-model-id");
主要な型のリファレンス
| 型 | 説明 |
|---|
DocumentIntelligenceClient | 分析用のメインクライアント |
DocumentIntelligenceAdministrationClient | モデル管理 |
AnalyzeResult | ドキュメント分析の結果 |
AnalyzedDocument | 結果内の単一ドキュメント |
DocumentField | 値と信頼度を含む抽出フィールド |
DocumentFieldType | 文字列、日付、数値、通貨など |
DocumentPage | ページ情報(行、単語、選択マーク) |
DocumentTable | セルを含む抽出された表 |
DocumentModelDetails | カスタムモデルのメタデータ |
BlobContentSource | トレーニングデータソース |
構築モード
| モード | 使用例 |
|---|
DocumentBuildMode.Template | 固定レイアウトのドキュメント(フォーム) |
DocumentBuildMode.Neural | 可変レイアウトのドキュメント |
ベストプラクティス
- 本番環境では DefaultAzureCredential を使用する
- クライアントインスタンスを再利用する — クライアントはスレッドセーフです
- 長時間実行操作を処理する — 簡略化するには
WaitUntil.Completed を使用します
- フィールドの信頼度を確認する — 常に
Confidence プロパティを確認します
- 適切なモデルを使用する — 一般的なドキュメントには事前構築モデル、特殊なドキュメントにはカスタムモデル
- カスタムサブドメインを使用する — Entra ID 認証に必要です
エラー処理
using Azure;
try
{
var operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-invoice",
documentUri);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"エラー: {ex.Status} - {ex.Message}");
}
関連 SDK
| SDK | 目的 | インストール |
|---|
Azure.AI.DocumentIntelligence | ドキュメント分析(この SDK) | dotnet add package Azure.AI.DocumentIntelligence |
Azure.AI.FormRecognizer | レガシー SDK(非推奨) | 代わりに DocumentIntelligence を使用してください |
参考リンク