mcpField
A
azure-ai-document-intelligence-dotnet

azure-ai-document-intelligence-dotnet

github.com/sickn33ドキュメント48.7k68 回インストール今日更新
リポジトリ

azure-ai-document-intelligence-dotnet について

azure-ai-document-intelligence-dotnetは、Azure AI Document Intelligenceで文書からテキスト、表、構造化フィールドを抽出する.NET向けスキルです。事前構築モデルやカスタムモデル、分類器、モデル管理を扱います。

主な機能

  1. 01テキスト、表、文書構造の分析
  2. 02事前構築モデルによるフィールド抽出
  3. 03カスタム文書モデルの構築
  4. 04文書分類器の作成と実行
  5. 05モデルメタデータの確認と管理

活用シーン

  1. 01請求書やレシートの項目抽出
  2. 02文書内の表とレイアウトの読み取り
  3. 03文書の種類別分類
  4. 04専用文書向けモデルの構築

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-ai-document-intelligence-dotnet

インストール後、Claude Code で/azure-ai-document-intelligence-dotnetを入力して読み込まれたか確認します。

詳細

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>

認証

Microsoft Entra ID(推奨)
using Azure.Identity;
using Azure.AI.DocumentIntelligence;

string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
var credential = new DefaultAzureCredential();
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-idDocumentID ドキュメントのフィールド(氏名、生年月日、住所)を抽出
prebuilt-businessCard名刺のフィールドを抽出
prebuilt-tax.us.w2W-2 税務フォームのフィールドを抽出
prebuilt-healthInsuranceCard.us健康保険証のフィールドを抽出

主なワークフロー

分析やトレーニングの前に、リソースのリージョン/テナントと、ドキュメントの内容を Azure に送信する権限があることを確認してください。ID、請求書、医療関連ドキュメントには非常に機微な情報が含まれる場合があります。承認済みのサンプルデータを使用し、抽出された個人情報や SAS URL をログに記録せず、必要なコンテナーに限って有効期間の短いストレージアクセスを設定してください。SDK/API のバージョンを固定し、対応する公式サンプルで、対応モデル、フィールドの種類、オーバーロードを確認してください。コード断片はコンパイル可能なアプリケーションではありません。信頼度スコアは正確性が検証済みであることを意味しません。判断を下す前に、フィールドを元のページや業務ルールと照合してください。トレーニングや分析にはコストが発生する場合があります。削除対象は、明示的に許可されたモデルに限ってください。

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($"Vendor Name: '{vendorName}', confidence: {vendorNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
        && invoiceTotalField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
        Console.WriteLine($"Invoice Total: '{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
    }
    
    // Extract line items
    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($"  Item: {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;

// Extract text by page
foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Page {page.PageNumber}: {page.Lines.Count} lines, {page.Words.Count} words");
    
    foreach (DocumentLine line in page.Lines)
    {
        Console.WriteLine($"  Line: '{line.Content}'");
    }
}

// Extract tables
foreach (DocumentTable table in result.Tables)
{
    Console.WriteLine($"Table: {table.RowCount} rows x {table.ColumnCount} columns");
    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"  Cell ({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($"Merchant: {merchantField.ValueString}");
        
    if (document.Fields.TryGetValue("Total", out DocumentField totalField))
        Console.WriteLine($"Total: {totalField.ValueCurrency.Amount}");
        
    if (document.Fields.TryGetValue("TransactionDate", out DocumentField dateField))
        Console.WriteLine($"Date: {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($"Model ID: {model.ModelId}");
Console.WriteLine($"Created: {model.CreatedOn}");

foreach (var docType in model.DocumentTypes)
{
    Console.WriteLine($"Document type: {docType.Key}");
    foreach (var field in docType.Value.FieldSchema)
    {
        Console.WriteLine($"  Field: {field.Key}, Confidence: {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($"Classifier 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 type: {document.DocumentType}, confidence: {document.Confidence}");
}
7. モデルを管理する
// Get resource details
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"Custom models: {resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");

// Get specific model
DocumentModelDetails model = await adminClient.GetModelAsync("my-model-id");
Console.WriteLine($"Model: {model.ModelId}, Created: {model.CreatedOn}");

// List models
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
    Console.WriteLine($"Model: {modelItem.ModelId}");
}

// Delete model
await adminClient.DeleteModelAsync("my-model-id");

主な型のリファレンス

型説明
DocumentIntelligenceClient分析用のメインクライアント
DocumentIntelligenceAdministrationClientモデル管理
AnalyzeResultドキュメント分析の結果
AnalyzedDocument結果に含まれる単一のドキュメント
DocumentField値と信頼度を含む抽出フィールド
DocumentFieldType文字列、日付、数値、通貨など
DocumentPageページ情報(行、単語、選択マーク)
DocumentTable抽出されたセルを含む表
DocumentModelDetailsカスタムモデルのメタデータ
BlobContentSourceトレーニングデータのソース

構築モード

モード用途
DocumentBuildMode.Templateレイアウトが固定されたドキュメント(フォーム)
DocumentBuildMode.Neuralレイアウトが可変のドキュメント

ベストプラクティス

  1. 本番環境では DefaultAzureCredential を使用する
  2. クライアントインスタンスを再利用する — クライアントはスレッドセーフです
  3. 長時間実行される操作を処理する — 簡潔にするには WaitUntil.Completed を使用します
  4. フィールドの信頼度を確認する — Confidence プロパティを必ず検証します
  5. 適切なモデルを使用する — 一般的なドキュメントには事前構築済みモデル、特殊なドキュメントにはカスタムモデルを使用します
  6. カスタムサブドメインを使用する — Entra ID 認証に必要です

エラー処理

using Azure;

try
{
    var operation = await client.AnalyzeDocumentAsync(
        WaitUntil.Completed, 
        "prebuilt-invoice", 
        documentUri);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Error: {ex.Status} - {ex.Message}");
}

関連 SDK

SDK用途インストール
Azure.AI.DocumentIntelligenceドキュメント分析(この SDK)dotnet add package Azure.AI.DocumentIntelligence
Azure.AI.FormRecognizerレガシー SDK(非推奨)代わりに DocumentIntelligence を使用してください

参照リンク

リソースURL
NuGet パッケージhttps://www.nuget.org/packages/Azure.AI.DocumentIntelligence
API リファレンスhttps://learn.microsoft.com/dotnet/api/azure.ai.documentintelligence
GitHub サンプルhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/documentintelligence/Azure.AI.DocumentIntelligence/samples
Document Intelligence Studiohttps://documentintelligence.ai.azure.com/
事前構築済みモデルhttps://aka.ms/azsdk/formrecognizer/models

使用する場面

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明範囲に明確に合致する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、停止して確認を求めてください。

コメント