ドキュメント インテリジェンスを始める

重要

  • Azure Cognitive Services Form Recognizerは、Foundry ToolsのAzure Document Intelligenceになりました。
  • 一部のプラットフォームでは、名前の変更の更新がまだ待っています。
  • ドキュメント内のForm Recognizerまたはドキュメント インテリジェンスに関するすべての言及は、同じAzure サービスを指します。

このコンテンツは適用対象:チェックマークv4.0 (GA)以前のバージョン:blue-checkmarkv3.1 (GA)blue-checkmarkv3.0 (GA)

  • Azure ドキュメント インテリジェンスの最新の安定バージョン v4.0 2024-11-30 (GA) の使用を開始します。

このコンテンツは適用対象:チェックマークv3.1 (GA)以前のバージョン:blue-checkmarkv3.0blue-checkmarkv2.1

  • Azure Form Recognizer の最新の一般提供 (GA) バージョン (2023-07-31) を使用開始しましょう。

このコンテンツは適用対象:チェックマークv3.0 (GA)新しいバージョン:blue-checkmarkv3.1blue-checkmarkv2.1

  • Azure Form Recognizer のレガシ GA バージョン (2022-08-31)の使用を開始する。
  • Azure ドキュメント インテリジェンス/Form Recognizerは、機械学習を使用して、ドキュメントからキーと値のペア、テキスト、テーブル、およびキー データを抽出するクラウドベースの Foundry Tools サービスです。

  • プログラミング言語 SDK を使用するか、REST API を呼び出すことで、ドキュメント処理モデルをワークフローやアプリケーションに簡単に統合できます。

  • このクイックスタートのテクノロジを学習している間は、無料サービスを使用することをお勧めします。 無料ページの数は 1 か月あたり 500 ページに制限されていることに注意してください。

API の機能と開発オプションの詳細については、 概要 ページを参照してください。

Client ライブラリREST API リファレンスPackageSamplesサポートされている REST API バージョン

Client ライブラリREST API リファレンスPackageSamplesサポートされている REST API バージョン

このクイック スタートでは、次の機能を使用して、フォームとドキュメントからデータと値を分析および抽出します。

前提 条件

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または Azure マルチサービス リソースを作成して、キーとエンドポイントを取得します。

  • Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

ヒント

1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または Azure マルチサービス リソースを作成して、キーとエンドポイントを取得します。

  • Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

ヒント

1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 Form Recognizerアクセスの場合のみ、Form Recognizer リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションを Form Recognizer API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

  1. Visual Studioを開始します。

  2. スタート ページで、[新しいプロジェクトの作成] を選択します。

    Visual Studio開始ウィンドウのスクリーンショット.

  3. [ 新しいプロジェクトの作成] ページで、検索ボックスに コンソール を入力します。 コンソール アプリケーション テンプレートを選択し、[次へ] を選択します。

    Visual Studioの新しいプロジェクトの作成ページのスクリーンショット。

  1. 新しいプロジェクト ダイアログ ウィンドウで、[プロジェクト名] ボックスに「doc_intel_quickstart」と入力します。 次に、[次へ] を選択します。
  1. 新しいプロジェクトの構成 ダイアログ ウィンドウで、「プロジェクト名」ボックスに「form_recognizer_quickstart」と入力します。 次に、[次へ] を選択します。
  1. [追加情報 ダイアログ ウィンドウで、.NET 8.0 (長期サポート) を選択し、Create を選択します。

    Visual Studioの追加情報ダイアログ ウィンドウのスクリーンショット.

NuGet を使用してクライアント ライブラリをインストールする

  1. doc_intel_quickstart プロジェクトを右クリックし、[NuGet パッケージの管理...] を選択します。

    Visual Studio の NuGet プレリリース パッケージ選択ウィンドウのスクリーンショット

  2. Browse タブを選択し、「Azure.AI.DocumentIntelligence」と入力します。

  3. [ Include prerelease ] チェック ボックスをオンにします。

    Visual Studio で選択されたプレリリース NuGet パッケージのスクリーンショット

  4. ドロップダウン メニューからバージョンを選択し、プロジェクトにパッケージをインストールします。

  1. form_recognizer_quickstart プロジェクトを右クリックし、[NuGet パッケージの管理...]

    Visual Studio の NuGet パッケージ検索ウィンドウのスクリーンショット

  2. ブラウズ タブを選択し、「Azure.AI.FormRecognizer」と入力します。 ドロップダウン メニューからバージョン 4.1.0 を選択する

    Visual Studio の NuGet Form Recognizer パッケージの選択スクリーンショット。

  1. form_recognizer_quickstart プロジェクトを右クリックし、[NuGet パッケージの管理...] を選択します。

    Visual Studio の NuGet パッケージ ウィンドウのスクリーンショット

  2. [ブラウズ] タブを選択し、Azure.AI.FormRecognizer と入力します。 ドロップダウン メニューからバージョン 4.0.0 を選択する

    Visual Studio で特定の NuGet レガシ パッケージを選択したスクリーンショット。

アプリケーションをビルドする

ドキュメント インテリジェンス サービスと対話するには、 DocumentIntelligenceClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentIntelligenceClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

Form Recognizer サービスと対話するには、DocumentAnalysisClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentAnalysisClient と Form Recognizer AzureKeyCredential を使用して endpoint インスタンスを作成します。

メモ

  • .NET 6 以降では、console テンプレートを使用する新しいプロジェクトによって、以前のバージョンとは異なる新しいプログラム スタイルが生成されます。
  • 新しい出力では、記述する必要があるコードを簡略化する最近の C# 機能が使用されます。
  • 新しいバージョンを使用する場合は、 Main メソッドの本体を記述するだけで済みます。 最上位レベルのステートメント、グローバル using ディレクティブ、または暗黙的な using ディレクティブを含める必要はありません。
  • 詳細については、「新しい C# テンプレートで最上位レベルのステートメントを生成する」参照してください
  1. Program.cs ファイルを開きます。

  2. Console.Writeline("Hello World!") を含む既存のコードを削除し、次のコード サンプルのいずれかを選択して、アプリケーションのProgram.cs ファイルにコピーして貼り付けます。

重要

クラウドで実行されるアプリケーションに資格情報を格納しないように、 Azure リソースの管理された ID を使用して認証をMicrosoft Entra IDすることをお勧めします。

API キーは慎重に使用してください。 API キーをコードに直接含めず、パブリックに投稿しないでください。 API キーを使用する場合は、Azure Key Vaultに安全に格納し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用してAzure Key Vaultへのアクセスを制限します。 アプリで API キーを安全に使用する方法の詳細については、「Azure Key Vault を使用した API キー」を参照してください。

AI サービスのセキュリティの詳細については、「Authenticate requests to Azure AI サービス」を参照してください。

レイアウト モデル

ドキュメントからテキスト、選択マーク、テキスト スタイル、テーブル構造、境界領域座標を抽出します。

  • この例では、 URI からのドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • スクリプトの先頭にある Uri fileUri 変数にファイル URI 値を追加しました。
  • URI で特定のファイルからレイアウトを抽出するには、 AnalyzeDocumentAsync メソッドを使用し、モデル ID として prebuilt-layout を渡します。 戻り値は、送信されたドキュメントのデータを含む AnalyzeResult オブジェクトです。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


using Azure;
using Azure.AI.DocumentIntelligence;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `DocumentIntelligenceClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentIntelligenceClient client = new DocumentIntelligenceClient(new Uri(endpoint), credential);

//sample document
Uri fileUri = new Uri ("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf");

AnalyzeDocumentContent content = new AnalyzeDocumentContent()
{
    UrlSource= fileUri
};

Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-layout", content);

AnalyzeResult result = operation.Value;

foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s)," +
        $" and {page.SelectionMarks.Count} selection mark(s).");

    for (int i = 0; i < page.Lines.Count; i++)
    {
        DocumentLine line = page.Lines[i];

        Console.WriteLine($"  Line {i}:");
        Console.WriteLine($"    Content: '{line.Content}'");

        Console.Write("    Bounding polygon, with points ordered clockwise:");
        for (int j = 0; j < line.Polygon.Count; j += 2)
        {
            Console.Write($" ({line.Polygon[j]}, {line.Polygon[j + 1]})");
        }

        Console.WriteLine();
    }

    for (int i = 0; i < page.SelectionMarks.Count; i++)
    {
        DocumentSelectionMark selectionMark = page.SelectionMarks[i];

        Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
        Console.WriteLine($"    State: {selectionMark.State}");

        Console.Write("    Bounding polygon, with points ordered clockwise:");
        for (int j = 0; j < selectionMark.Polygon.Count; j++)
        {
            Console.Write($" ({selectionMark.Polygon[j]}, {selectionMark.Polygon[j + 1]})");
        }

        Console.WriteLine();
    }
}

for (int i = 0; i < result.Paragraphs.Count; i++)
{
    DocumentParagraph paragraph = result.Paragraphs[i];

    Console.WriteLine($"Paragraph {i}:");
    Console.WriteLine($"  Content: {paragraph.Content}");

    if (paragraph.Role != null)
    {
        Console.WriteLine($"  Role: {paragraph.Role}");
    }
}

foreach (DocumentStyle style in result.Styles)
{
    // Check the style and style confidence to see if text is handwritten.
    // Note that value '0.8' is used as an example.

    bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true;

    if (isHandwritten && style.Confidence > 0.8)
    {
        Console.WriteLine($"Handwritten content found:");

        foreach (DocumentSpan span in style.Spans)
        {
            var handwrittenContent = result.Content.Substring(span.Offset, span.Length);
            Console.WriteLine($"  {handwrittenContent}");
        }
    }
}

for (int i = 0; i < result.Tables.Count; i++)
{
    DocumentTable table = result.Tables[i];

    Console.WriteLine($"Table {i} has {table.RowCount} rows and {table.ColumnCount} columns.");

    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"  Cell ({cell.RowIndex}, {cell.ColumnIndex}) is a '{cell.Kind}' with content: {cell.Content}");
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行するボタンのスクリーンショット。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。

using Azure;
using Azure.AI.FormRecognizer.DocumentAnalysis;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `DocumentAnalysisClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), credential);

//sample document
Uri fileUri = new Uri ("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf");

AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, "prebuilt-layout", fileUri);

AnalyzeResult result = operation.Value;

foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),");
    Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s).");

    for (int i = 0; i < page.Lines.Count; i++)
    {
        DocumentLine line = page.Lines[i];
        Console.WriteLine($"  Line {i} has content: '{line.Content}'.");

        Console.WriteLine($"    Its bounding box is:");
        Console.WriteLine($"      Upper left => X: {line.Polygon[0].X}, Y= {line.Polygon[0].Y}");
        Console.WriteLine($"      Upper right => X: {line.Polygon[1].X}, Y= {line.Polygon[1].Y}");
        Console.WriteLine($"      Lower right => X: {line.Polygon[2].X}, Y= {line.Polygon[2].Y}");
        Console.WriteLine($"      Lower left => X: {line.Polygon[3].X}, Y= {line.Polygon[3].Y}");
    }

    for (int i = 0; i < page.SelectionMarks.Count; i++)
    {
        DocumentSelectionMark selectionMark = page.SelectionMarks[i];

        Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
        Console.WriteLine($"    Its bounding box is:");
        Console.WriteLine($"      Upper left => X: {selectionMark.Polygon[0].X}, Y= {selectionMark.Polygon[0].Y}");
        Console.WriteLine($"      Upper right => X: {selectionMark.Polygon[1].X}, Y= {selectionMark.Polygon[1].Y}");
        Console.WriteLine($"      Lower right => X: {selectionMark.Polygon[2].X}, Y= {selectionMark.Polygon[2].Y}");
        Console.WriteLine($"      Lower left => X: {selectionMark.Polygon[3].X}, Y= {selectionMark.Polygon[3].Y}");
    }
}

foreach (DocumentStyle style in result.Styles)
{
    // Check the style and style confidence to see if text is handwritten.
    // Note that value '0.8' is used as an example.

    bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true;

    if (isHandwritten && style.Confidence > 0.8)
    {
        Console.WriteLine($"Handwritten content found:");

        foreach (DocumentSpan span in style.Spans)
        {
            Console.WriteLine($"  Content: {result.Content.Substring(span.Index, span.Length)}");
        }
    }
}

Console.WriteLine("The following tables were extracted:");

for (int i = 0; i < result.Tables.Count; i++)
{
    DocumentTable table = result.Tables[i];
    Console.WriteLine($"  Table {i} has {table.RowCount} rows and {table.ColumnCount} columns.");

    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"    Cell ({cell.RowIndex}, {cell.ColumnIndex}) has kind '{cell.Kind}' and content: '{cell.Content}'.");
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行するボタンの位置のスクリーンショット。

レイアウト モデルの出力

予想される出力のスニペットを次に示します。

  Document Page 1 has 69 line(s), 425 word(s), and 15 selection mark(s).
  Line 0 has content: 'UNITED STATES'.
    Its bounding box is:
      Upper left => X: 3.4915, Y= 0.6828
      Upper right => X: 5.0116, Y= 0.6828
      Lower right => X: 5.0116, Y= 0.8265
      Lower left => X: 3.4915, Y= 0.8265
  Line 1 has content: 'SECURITIES AND EXCHANGE COMMISSION'.
    Its bounding box is:
      Upper left => X: 2.1937, Y= 0.9061
      Upper right => X: 6.297, Y= 0.9061
      Lower right => X: 6.297, Y= 1.0498
      Lower left => X: 2.1937, Y= 1.0498

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、レイアウト モデルの出力を表示します。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。

using Azure;
using Azure.AI.FormRecognizer.DocumentAnalysis;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `DocumentAnalysisClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), credential);

//sample document
Uri fileUri = new Uri ("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf");

AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, "prebuilt-layout", fileUri);

AnalyzeResult result = operation.Value;

foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),");
    Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s).");

    for (int i = 0; i < page.Lines.Count; i++)
    {
        DocumentLine line = page.Lines[i];
        Console.WriteLine($"  Line {i} has content: '{line.Content}'.");

        Console.WriteLine($"    Its bounding polygon (points ordered clockwise):");

        for (int j = 0; j < line.Polygon.Count; j++)
        {
            Console.WriteLine($"      Point {j} => X: {line.Polygon[j].X}, Y: {line.Polygon[j].Y}");
        }
    }

    for (int i = 0; i < page.SelectionMarks.Count; i++)
    {
        DocumentSelectionMark selectionMark = page.SelectionMarks[i];

        Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
        Console.WriteLine($"    Its bounding polygon (points ordered clockwise):");

        for (int j = 0; j < selectionMark.Polygon.Count; j++)
        {
            Console.WriteLine($"      Point {j} => X: {selectionMark.Polygon[j].X}, Y: {selectionMark.Polygon[j].Y}");
        }
    }
}

Console.WriteLine("Paragraphs:");

foreach (DocumentParagraph paragraph in result.Paragraphs)
{
    Console.WriteLine($"  Paragraph content: {paragraph.Content}");

    if (paragraph.Role != null)
    {
        Console.WriteLine($"    Role: {paragraph.Role}");
    }
}

foreach (DocumentStyle style in result.Styles)
{
    // Check the style and style confidence to see if text is handwritten.
    // Note that value '0.8' is used as an example.

    bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true;

    if (isHandwritten && style.Confidence > 0.8)
    {
        Console.WriteLine($"Handwritten content found:");

        foreach (DocumentSpan span in style.Spans)
        {
            Console.WriteLine($"  Content: {result.Content.Substring(span.Index, span.Length)}");
        }
    }
}

Console.WriteLine("The following tables were extracted:");

for (int i = 0; i < result.Tables.Count; i++)
{
    DocumentTable table = result.Tables[i];
    Console.WriteLine($"  Table {i} has {table.RowCount} rows and {table.ColumnCount} columns.");

    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"    Cell ({cell.RowIndex}, {cell.ColumnIndex}) has kind '{cell.Kind}' and content: '{cell.Content}'.");
    }
}
Extract the layout of a document from a file stream
To extract the layout from a given file at a file stream, use the AnalyzeDocument method and pass prebuilt-layout as the model ID. The returned value is an AnalyzeResult object containing data about the submitted document.

string filePath = "<filePath>";
using var stream = new FileStream(filePath, FileMode.Open);

AnalyzeDocumentOperation operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-layout", stream);
AnalyzeResult result = operation.Value;

foreach (DocumentPage page in result.Pages)
{
    Console.WriteLine($"Document Page {page.PageNumber} has {page.Lines.Count} line(s), {page.Words.Count} word(s),");
    Console.WriteLine($"and {page.SelectionMarks.Count} selection mark(s).");

    for (int i = 0; i < page.Lines.Count; i++)
    {
        DocumentLine line = page.Lines[i];
        Console.WriteLine($"  Line {i} has content: '{line.Content}'.");

        Console.WriteLine($"    Its bounding polygon (points ordered clockwise):");

        for (int j = 0; j < line.Polygon.Count; j++)
        {
            Console.WriteLine($"      Point {j} => X: {line.Polygon[j].X}, Y: {line.Polygon[j].Y}");
        }
    }

    for (int i = 0; i < page.SelectionMarks.Count; i++)
    {
        DocumentSelectionMark selectionMark = page.SelectionMarks[i];

        Console.WriteLine($"  Selection Mark {i} is {selectionMark.State}.");
        Console.WriteLine($"    Its bounding polygon (points ordered clockwise):");

        for (int j = 0; j < selectionMark.Polygon.Count; j++)
        {
            Console.WriteLine($"      Point {j} => X: {selectionMark.Polygon[j].X}, Y: {selectionMark.Polygon[j].Y}");
        }
    }
}

Console.WriteLine("Paragraphs:");

foreach (DocumentParagraph paragraph in result.Paragraphs)
{
    Console.WriteLine($"  Paragraph content: {paragraph.Content}");

    if (paragraph.Role != null)
    {
        Console.WriteLine($"    Role: {paragraph.Role}");
    }
}

foreach (DocumentStyle style in result.Styles)
{
    // Check the style and style confidence to see if text is handwritten.
    // Note that value '0.8' is used as an example.

    bool isHandwritten = style.IsHandwritten.HasValue && style.IsHandwritten == true;

    if (isHandwritten && style.Confidence > 0.8)
    {
        Console.WriteLine($"Handwritten content found:");

        foreach (DocumentSpan span in style.Spans)
        {
            Console.WriteLine($"  Content: {result.Content.Substring(span.Index, span.Length)}");
        }
    }
}

Console.WriteLine("The following tables were extracted:");

for (int i = 0; i < result.Tables.Count; i++)
{
    DocumentTable table = result.Tables[i];
    Console.WriteLine($"  Table {i} has {table.RowCount} rows and {table.ColumnCount} columns.");

    foreach (DocumentTableCell cell in table.Cells)
    {
        Console.WriteLine($"    Cell ({cell.RowIndex}, {cell.ColumnIndex}) has kind '{cell.Kind}' and content: '{cell.Content}'.");
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行している画面のスクリーンショット。

事前構築済みモデル

事前構築済みのモデルを使用して、特定のドキュメントの種類の共通フィールドを分析して抽出します。 この例では、 事前構築済みの 請求書モデルを使用して請求書を分析します。

ヒント

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 モデル データの抽出を参照してください。

  • 事前構築済みの請求書モデルを使用して請求書を分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • Program.cs ファイルの先頭にある Uri invoiceUri 変数にファイル URI 値を追加しました。
  • URI で特定のファイルを分析するには、 AnalyzeDocumentAsync メソッドを使用し、モデル ID として prebuilt-invoice を渡します。 戻り値は、送信されたドキュメントのデータを含む AnalyzeResult オブジェクトです。
  • わかりやすくするために、サービスから返されるすべてのキーと値のペアはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


using Azure;
using Azure.AI.DocumentIntelligence;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `DocumentIntelligenceClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentIntelligenceClient client = new DocumentIntelligenceClient(new Uri(endpoint), credential);

//sample invoice document
Uri invoiceUri = new Uri("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf");

AnalyzeDocumentContent content = new AnalyzeDocumentContent()
{
    UrlSource = invoiceUri
};

Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-invoice", content);

AnalyzeResult result = operation.Value;

for (int i = 0; i < result.Documents.Count; i++)
{
    Console.WriteLine($"Document {i}:");

    AnalyzedDocument document = result.Documents[i];

    if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField)
        && vendorNameField.FieldType == DocumentFieldType.String)
    {
        string vendorName = vendorNameField.ValueString;
        Console.WriteLine($"Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("CustomerName", out DocumentField customerNameField)
        && customerNameField.FieldType == DocumentFieldType.String)
    {
        string customerName = customerNameField.ValueString;
        Console.WriteLine($"Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
    }

    if (document.Fields.TryGetValue("Items", out DocumentField itemsField)
        && itemsField.FieldType == DocumentFieldType.List)
    {
        foreach (DocumentField itemField in itemsField.ValueList)
        {
            Console.WriteLine("Item:");

            if (itemField.FieldType == DocumentFieldType.Dictionary)
            {
                IReadOnlyDictionary<string, DocumentField> itemFields = itemField.ValueDictionary;

                if (itemFields.TryGetValue("Description", out DocumentField itemDescriptionField)
                    && itemDescriptionField.FieldType == DocumentFieldType.String)
                {
                    string itemDescription = itemDescriptionField.ValueString;
                    Console.WriteLine($"  Description: '{itemDescription}', with confidence {itemDescriptionField.Confidence}");
                }

                if (itemFields.TryGetValue("Amount", out DocumentField itemAmountField)
                    && itemAmountField.FieldType == DocumentFieldType.Currency)
                {
                    CurrencyValue itemAmount = itemAmountField.ValueCurrency;
                    Console.WriteLine($"  Amount: '{itemAmount.CurrencySymbol}{itemAmount.Amount}', with confidence {itemAmountField.Confidence}");
                }
            }
        }
    }

    if (document.Fields.TryGetValue("SubTotal", out DocumentField subTotalField)
        && subTotalField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue subTotal = subTotalField.ValueCurrency;
        Console.WriteLine($"Sub Total: '{subTotal.CurrencySymbol}{subTotal.Amount}', with confidence {subTotalField.Confidence}");
    }

    if (document.Fields.TryGetValue("TotalTax", out DocumentField totalTaxField)
        && totalTaxField.FieldType == DocumentFieldType.Currency)
    {
        CurrencyValue totalTax = totalTaxField.ValueCurrency;
        Console.WriteLine($"Total Tax: '{totalTax.CurrencySymbol}{totalTax.Amount}', with confidence {totalTaxField.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}', with confidence {invoiceTotalField.Confidence}");
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行するボタンのスクリーンショット。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


using Azure;
using Azure.AI.FormRecognizer.DocumentAnalysis;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `FormRecognizerClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), credential);

//sample invoice document

Uri invoiceUri = new Uri ("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf");

Operation operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-invoice", invoiceUri);

AnalyzeResult result = operation.Value;

for (int i = 0; i < result.Documents.Count; i++)
{
    Console.WriteLine($"Document {i}:");

    AnalyzedDocument document = result.Documents[i];

    if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField))
    {
        if (vendorNameField.FieldType == DocumentFieldType.String)
        {
            string vendorName = vendorNameField.Value.AsString();
            Console.WriteLine($"Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("CustomerName", out DocumentField customerNameField))
    {
        if (customerNameField.FieldType == DocumentFieldType.String)
        {
            string customerName = customerNameField.Value.AsString();
            Console.WriteLine($"Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("Items", out DocumentField itemsField))
    {
        if (itemsField.FieldType == DocumentFieldType.List)
        {
            foreach (DocumentField itemField in itemsField.Value.AsList())
            {
                Console.WriteLine("Item:");

                if (itemField.FieldType == DocumentFieldType.Dictionary)
                {
                    IReadOnlyDictionary<string, DocumentField> itemFields = itemField.Value.AsDictionary();

                    if (itemFields.TryGetValue("Description", out DocumentField itemDescriptionField))
                    {
                        if (itemDescriptionField.FieldType == DocumentFieldType.String)
                        {
                            string itemDescription = itemDescriptionField.Value.AsString();

                            Console.WriteLine($"  Description: '{itemDescription}', with confidence {itemDescriptionField.Confidence}");
                        }
                    }

                    if (itemFields.TryGetValue("Amount", out DocumentField itemAmountField))
                    {
                        if (itemAmountField.FieldType == DocumentFieldType.Currency)
                        {
                            CurrencyValue itemAmount = itemAmountField.Value.AsCurrency();

                            Console.WriteLine($"  Amount: '{itemAmount.Symbol}{itemAmount.Amount}', with confidence {itemAmountField.Confidence}");
                        }
                    }
                }
            }
        }
    }

    if (document.Fields.TryGetValue("SubTotal", out DocumentField subTotalField))
    {
        if (subTotalField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue subTotal = subTotalField.Value.AsCurrency();
            Console.WriteLine($"Sub Total: '{subTotal.Symbol}{subTotal.Amount}', with confidence {subTotalField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("TotalTax", out DocumentField totalTaxField))
    {
        if (totalTaxField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue totalTax = totalTaxField.Value.AsCurrency();
            Console.WriteLine($"Total Tax: '{totalTax.Symbol}{totalTax.Amount}', with confidence {totalTaxField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField))
    {
        if (invoiceTotalField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue invoiceTotal = invoiceTotalField.Value.AsCurrency();
            Console.WriteLine($"Invoice Total: '{invoiceTotal.Symbol}{invoiceTotal.Amount}', with confidence {invoiceTotalField.Confidence}");
        }
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studioプログラム実行ボタンの位置を示すスクリーンショット。

事前構築済みモデルの出力

予想される出力のスニペットを次に示します。

  Document 0:
  Vendor Name: 'CONTOSO LTD.', with confidence 0.962
  Customer Name: 'MICROSOFT CORPORATION', with confidence 0.951
  Item:
    Description: 'Test for 23 fields', with confidence 0.899
    Amount: '100', with confidence 0.902
  Sub Total: '100', with confidence 0.979

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、事前構築済みの請求書モデルの出力を表示します。

Program.cs ファイルに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


using Azure;
using Azure.AI.FormRecognizer.DocumentAnalysis;

//set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal to create your `AzureKeyCredential` and `FormRecognizerClient` instance
string endpoint = "<your-endpoint>";
string key = "<your-key>";
AzureKeyCredential credential = new AzureKeyCredential(key);
DocumentAnalysisClient client = new DocumentAnalysisClient(new Uri(endpoint), credential);

//sample invoice document

Uri invoiceUri = new Uri ("https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf");

AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, "prebuilt-invoice", invoiceUri);

AnalyzeResult result = operation.Value;

for (int i = 0; i < result.Documents.Count; i++)
{
    Console.WriteLine($"Document {i}:");

    AnalyzedDocument document = result.Documents[i];

    if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField))
    {
        if (vendorNameField.FieldType == DocumentFieldType.String)
        {
            string vendorName = vendorNameField.Value.AsString();
            Console.WriteLine($"Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("CustomerName", out DocumentField customerNameField))
    {
        if (customerNameField.FieldType == DocumentFieldType.String)
        {
            string customerName = customerNameField.Value.AsString();
            Console.WriteLine($"Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("Items", out DocumentField itemsField))
    {
        if (itemsField.FieldType == DocumentFieldType.List)
        {
            foreach (DocumentField itemField in itemsField.Value.AsList())
            {
                Console.WriteLine("Item:");

                if (itemField.FieldType == DocumentFieldType.Dictionary)
                {
                    IReadOnlyDictionary<string, DocumentField> itemFields = itemField.Value.AsDictionary();

                    if (itemFields.TryGetValue("Description", out DocumentField itemDescriptionField))
                    {
                        if (itemDescriptionField.FieldType == DocumentFieldType.String)
                        {
                            string itemDescription = itemDescriptionField.Value.AsString();

                            Console.WriteLine($"  Description: '{itemDescription}', with confidence {itemDescriptionField.Confidence}");
                        }
                    }

                    if (itemFields.TryGetValue("Amount", out DocumentField itemAmountField))
                    {
                        if (itemAmountField.FieldType == DocumentFieldType.Currency)
                        {
                            CurrencyValue itemAmount = itemAmountField.Value.AsCurrency();

                            Console.WriteLine($"  Amount: '{itemAmount.Symbol}{itemAmount.Amount}', with confidence {itemAmountField.Confidence}");
                        }
                    }
                }
            }
        }
    }

    if (document.Fields.TryGetValue("SubTotal", out DocumentField subTotalField))
    {
        if (subTotalField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue subTotal = subTotalField.Value.AsCurrency();
            Console.WriteLine($"Sub Total: '{subTotal.Symbol}{subTotal.Amount}', with confidence {subTotalField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("TotalTax", out DocumentField totalTaxField))
    {
        if (totalTaxField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue totalTax = totalTaxField.Value.AsCurrency();
            Console.WriteLine($"Total Tax: '{totalTax.Symbol}{totalTax.Amount}', with confidence {totalTaxField.Confidence}");
        }
    }

    if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField))
    {
        if (invoiceTotalField.FieldType == DocumentFieldType.Currency)
        {
            CurrencyValue invoiceTotal = invoiceTotalField.Value.AsCurrency();
            Console.WriteLine($"Invoice Total: '{invoiceTotal.Symbol}{invoiceTotal.Amount}', with confidence {invoiceTotalField.Confidence}");
        }
    }
}

アプリケーションを実行する

コード サンプルをアプリケーションに追加したら、formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行している画面のスクリーンショット。

Client ライブラリREST API リファレンスPackage (Maven)< /c4>Samplesサポートされている REST API バージョン

Client ライブラリREST API リファレンスPackage (Maven)< /c4>Samplesサポートされている REST API バージョン

Client ライブラリREST API リファレンスPackage (Maven)< /c4>Samplesサポートされている REST API バージョン

このクイック スタートでは、次の機能を使用して、フォームとドキュメントからデータと値を分析および抽出します。

  • レイアウト - モデルをトレーニングする必要なく、ドキュメント内のラジオ ボタンやチェック ボックスなどのテーブル、線、単語、選択マークを分析して抽出します。

  • 事前構築済みの請求書 - 事前トレーニング済みモデルを使用して、特定のドキュメントの種類の共通フィールドを分析および抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • 最新バージョンの Visual Studio Code または任意の IDE。 Java を Visual Studio Code で見る。

    ヒント

    • Visual Studio Codeでは、Windowsおよび macOS 用の Coding Pack for Java を提供しています。コーディング パックは、VS Code、Java Development Kit (JDK)、およびMicrosoftによって推奨される拡張機能のコレクションのバンドルです。 コーディング パックを使用して、既存の開発環境を修正することもできます。
    • VS Code と Coding Pack for Javaを使用している場合は、Gradle for Java 拡張機能をインストールします。
  • Visual Studio Codeを使用していない場合は、開発環境に次のものがインストールされていることを確認してください。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または multi-service Document Intelligence リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 後で、キーとエンドポイントをコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

新しい Gradle プロジェクトを作成する

  1. コンソール ウィンドウ (cmd、PowerShell、Bash など) で、 doc-intel-app という名前のアプリの新しいディレクトリを作成し、そこに移動します。

    mkdir doc-intel-app && doc-intel-app
    
    mkdir doc-intel-app; cd doc-intel-app
    
  2. 作業ディレクトリから gradle init コマンドを実行します。 このコマンドは、実行時にアプリケーションの作成と構成に使用される build.gradle.kts など、Gradle に不可欠なビルド ファイルを作成します。

    gradle init --type basic
    
  3. DSL の選択を求められたら、[Kotlin] を選択します。

  4. [戻る] または [Enter] を選択して、既定のプロジェクト名 (doc-intel-app) をそのまま使用します。

  1. コンソール ウィンドウ (cmd、PowerShell、Bash など) で、 form-recognize-app という名前のアプリ用の新しいディレクトリを作成し、そこに移動します。

    mkdir form-recognize-app && cd form-recognize-app
    
    mkdir form-recognize-app; cd form-recognize-app
    
  2. 作業ディレクトリから gradle init コマンドを実行します。 このコマンドは、実行時にアプリケーションの作成と構成に使用される build.gradle.kts など、Gradle に不可欠なビルド ファイルを作成します。

    gradle init --type basic
    
  3. DSL の選択を求められたら、[Kotlin] を選択します。

  4. [戻る] または [Enter] を選択して、既定のプロジェクト名 (form-recognize-app) をそのまま使用します。

クライアント ライブラリをインストールする

このクイック スタートでは、Gradle 依存関係マネージャーを使用します。 Maven Central Repository では、クライアント ライブラリと他の依存関係マネージャーの情報を確認できます。

IDE でプロジェクトの build.gradle.kts ファイルを開きます。 必要なプラグインと設定と共に、クライアント ライブラリを implementation ステートメントとして含めるには、次のコードを貼り付けます。

   plugins {
       java
       application
   }
   application {
       mainClass.set("DocIntelligence")
   }
   repositories {
       mavenCentral()
   }
   dependencies {
       implementation group: 'com.azure', name: 'azure-ai-documentintelligence', version: '1.0.0'

   }

このクイック スタートでは、Gradle 依存関係マネージャーを使用します。 Maven Central Repository では、クライアント ライブラリと他の依存関係マネージャーの情報を確認できます。

IDE でプロジェクトの build.gradle.kts ファイルを開きます。 必要なプラグインと設定と共に、クライアント ライブラリを implementation ステートメントとして含めるには、次のコードを貼り付けます。

   plugins {
       java
       application
   }
   application {
       mainClass.set("FormRecognizer")
   }
   repositories {
       mavenCentral()
   }
   dependencies {
       implementation group: 'com.azure', name: 'azure-ai-formrecognizer', version: '4.1.0'

   }

このクイック スタートでは、Gradle 依存関係マネージャーを使用します。 Maven Central Repository では、クライアント ライブラリと他の依存関係マネージャーの情報を確認できます。

IDE でプロジェクトの build.gradle.kts ファイルを開きます。 必要なプラグインと設定と共に、クライアント ライブラリを implementation ステートメントとして含めるには、次のコードを貼り付けます。

   plugins {
       java
       application
   }
   application {
       mainClass.set("FormRecognizer")
   }
   repositories {
       mavenCentral()
   }
   dependencies {
       implementation group: 'com.azure', name: 'azure-ai-formrecognizer', version: '4.0.0'


   }

Java アプリケーションを作成する

ドキュメント インテリジェンス サービスと対話するには、 DocumentIntelligenceClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentIntelligenceClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

ドキュメント インテリジェンス サービスと対話するには、 DocumentAnalysisClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentAnalysisClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

  1. doc-intel-app ディレクトリから、次のコマンドを実行します。

    mkdir -p src/main/java
    

    次のディレクトリ構造を作成します。

    Javaディレクトリ構造のスクリーンショット

  1. java ディレクトリに移動し、DocIntelligence.javaという名前のファイルを作成します。

    ヒント

    • PowerShell を使用して新しいファイルを作成できます。
    • Shift キーを押しながらフォルダーを右クリックして、プロジェクト ディレクトリの PowerShell ウィンドウを開きます。
    • 次のコマンド New-Item DocIntelligence.java を入力します。
  2. DocIntelligence.java ファイルを開きます。 次のコード サンプルのいずれかをコピーして、アプリケーションに貼り付けます。

  1. java ディレクトリに移動し、FormRecognizer.javaという名前のファイルを作成します。

    ヒント

    • PowerShell を使用して新しいファイルを作成できます。
    • Shift キーを押しながらフォルダーを右クリックして、プロジェクト ディレクトリの PowerShell ウィンドウを開きます。
    • 次のコマンド New-Item FormRecognizer.java を入力します。
  2. FormRecognizer.java ファイルを開きます。 次のコード サンプルのいずれかをコピーして、アプリケーションに貼り付けます。

重要

クラウドで実行されるアプリケーションに資格情報を格納しないように、 Azure リソースの管理された ID を使用して認証をMicrosoft Entra IDすることをお勧めします。

API キーは慎重に使用してください。 API キーをコードに直接含めず、パブリックに投稿しないでください。 API キーを使用する場合は、Azure Key Vaultに安全に格納し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用してAzure Key Vaultへのアクセスを制限します。 アプリで API キーを安全に使用する方法の詳細については、「Azure Key Vault を使用した API キー」を参照してください。

AI サービスのセキュリティの詳細については、「Authenticate requests to Azure AI サービス」を参照してください。

レイアウト モデル

ドキュメントからテキスト、選択マーク、テキスト スタイル、テーブル構造、境界領域座標を抽出します。

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • URI で特定のファイルを分析するには、 beginAnalyzeDocument メソッドを使用し、モデル ID として prebuilt-layout を渡します。返される値は、送信されたドキュメントに関するデータを含む AnalyzeResult オブジェクトです。
  • main メソッドの documentUrl 変数にファイル URI 値を追加しました。

DocIntelligence.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.documentintelligence.DocumentIntelligenceClient;
import com.azure.ai.documentintelligence.DocumentIntelligenceClientBuilder;
import com.azure.ai.documentintelligence.models.AnalyzeDocumentOptions;
import com.azure.ai.documentintelligence.models.AnalyzeOperationDetails;
import com.azure.ai.documentintelligence.models.AnalyzeResult;
import com.azure.ai.documentintelligence.models.DocumentTable;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.util.List;

public class DocIntelligence {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(String[] args) {

    // create your `DocumentIntelligenceClient` instance and `AzureKeyCredential` variable
    DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String modelId = "prebuilt-layout";
    String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";

    AnalyzeDocumentOptions options = new AnalyzeDocumentOptions(documentUrl);

    SyncPoller<AnalyzeOperationDetails, AnalyzeResult> analyzeLayoutPoller = client.beginAnalyzeDocument(modelId, options);

    AnalyzeResult analyzeLayoutResult = analyzeLayoutPoller.getFinalResult();

    // pages
    analyzeLayoutResult.getPages().forEach(documentPage -> {
      System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
        documentPage.getWidth(),
        documentPage.getHeight(),
        documentPage.getUnit());

      // lines
      documentPage.getLines().forEach(documentLine ->
        System.out.printf("Line '%s' is within a bounding polygon %s.%n",
          documentLine.getContent(),
          documentLine.getPolygon()));

      // words
      documentPage.getWords().forEach(documentWord ->
        System.out.printf("Word '%s' has a confidence score of %.2f.%n",
          documentWord.getContent(),
          documentWord.getConfidence()));

      // selection marks
      documentPage.getSelectionMarks().forEach(documentSelectionMark ->
        System.out.printf("Selection mark is '%s' and is within a bounding polygon %s with confidence %.2f.%n",
          documentSelectionMark.getState().toString(),
          documentSelectionMark.getPolygon(),
          documentSelectionMark.getConfidence()));
    });

    // tables
    List < DocumentTable > tables = analyzeLayoutResult.getTables();
    for (int i = 0; i < tables.size(); i++) {
      DocumentTable documentTable = tables.get(i);
      System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
        documentTable.getColumnCount());
      documentTable.getCells().forEach(documentTableCell ->
        System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
          documentTableCell.getRowIndex(), documentTableCell.getColumnIndex()));
      System.out.println();
    }

    // styles
    analyzeLayoutResult.getStyles().forEach(documentStyle -> System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten()));
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ doc-intel-app に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

FormRecognizer.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.formrecognizer.documentanalysis.models.*;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;

import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import java.time.LocalDate;
import java.util.Map;
import java.util.stream.Collectors;

public class FormRecognizer {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(String[] args) {

    // create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
    DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
    String modelId = "prebuilt-layout";

    SyncPoller < OperationResult, AnalyzeResult > analyzeLayoutResultPoller =
      client.beginAnalyzeDocumentFromUrl(modelId, documentUrl);

    AnalyzeResult analyzeLayoutResult = analyzeLayoutResultPoller.getFinalResult();

    // pages
    analyzeLayoutResult.getPages().forEach(documentPage -> {
      System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
        documentPage.getWidth(),
        documentPage.getHeight(),
        documentPage.getUnit());

      // lines
      documentPage.getLines().forEach(documentLine ->
        System.out.printf("Line %s is within a bounding polygon %s.%n",
          documentLine.getContent(),
          documentLine.getPolygon().toString()));

      // words
      documentPage.getWords().forEach(documentWord ->
        System.out.printf("Word '%s' has a confidence score of %.2f%n",
          documentWord.getContent(),
          documentWord.getConfidence()));

      // selection marks
      documentPage.getSelectionMarks().forEach(documentSelectionMark ->
        System.out.printf("Selection mark is %s and is within a bounding polygon %s with confidence %.2f.%n",
          documentSelectionMark.getState().toString(),
          documentSelectionMark.getPolygon().toString(),
          documentSelectionMark.getConfidence()));
    });

    // tables
    List < DocumentTable > tables = analyzeLayoutResult.getTables();
    for (int i = 0; i < tables.size(); i++) {
      DocumentTable documentTable = tables.get(i);
      System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
        documentTable.getColumnCount());
      documentTable.getCells().forEach(documentTableCell -> {
        System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
          documentTableCell.getRowIndex(), documentTableCell.getColumnIndex());
      });
      System.out.println();
    }
  }
  // Utility function to get the bounding polygon coordinates
  private static String getBoundingCoordinates(List < Point > Polygon) {
    return Polygon.stream().map(point -> String.format("[%.2f, %.2f]", point.getX(),
      point.getY())).collect(Collectors.joining(", "));
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ (form-recognize-app) に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

レイアウト モデルの出力

予想される出力のスニペットを次に示します。

  Table 0 has 5 rows and 3 columns.
  Cell 'Title of each class', has row index 0 and column index 0.
  Cell 'Trading Symbol', has row index 0 and column index 1.
  Cell 'Name of exchange on which registered', has row index 0 and column index 2.
  Cell 'Common stock, $0.00000625 par value per share', has row index 1 and column index 0.
  Cell 'MSFT', has row index 1 and column index 1.
  Cell 'NASDAQ', has row index 1 and column index 2.
  Cell '2.125% Notes due 2021', has row index 2 and column index 0.
  Cell 'MSFT', has row index 2 and column index 1.
  Cell 'NASDAQ', has row index 2 and column index 2.
  Cell '3.125% Notes due 2028', has row index 3 and column index 0.
  Cell 'MSFT', has row index 3 and column index 1.
  Cell 'NASDAQ', has row index 3 and column index 2.
  Cell '2.625% Notes due 2033', has row index 4 and column index 0.
  Cell 'MSFT', has row index 4 and column index 1.
  Cell 'NASDAQ', has row index 4 and column index 2.

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、レイアウト モデルの出力を表示します。

FormRecognizer.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentTable;
import com.azure.ai.formrecognizer.documentanalysis.models.Point;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.util.List;
import java.util.stream.Collectors;

public class FormRecognizer {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(String[] args) {

    // create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
    DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String documentUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
    String modelId = "prebuilt-layout";

    SyncPoller < OperationResult, AnalyzeResult > analyzeLayoutPoller =
      client.beginAnalyzeDocumentFromUrl(modelId, documentUrl);

    AnalyzeResult analyzeLayoutResult = analyzeLayoutPoller.getFinalResult();

    // pages
    analyzeLayoutResult.getPages().forEach(documentPage -> {
      System.out.printf("Page has width: %.2f and height: %.2f, measured with unit: %s%n",
        documentPage.getWidth(),
        documentPage.getHeight(),
        documentPage.getUnit());

      // lines
      documentPage.getLines().forEach(documentLine ->
        System.out.printf("Line '%s' is within a bounding polygon %s.%n",
          documentLine.getContent(),
          getBoundingCoordinates(documentLine.getPolygon())));

      // words
      documentPage.getWords().forEach(documentWord ->
        System.out.printf("Word '%s' has a confidence score of %.2f.%n",
          documentWord.getContent(),
          documentWord.getConfidence()));

      // selection marks
      documentPage.getSelectionMarks().forEach(documentSelectionMark ->
        System.out.printf("Selection mark is '%s' and is within a bounding polygon %s with confidence %.2f.%n",
          documentSelectionMark.getSelectionMarkState().toString(),
          getBoundingCoordinates(documentSelectionMark.getPolygon()),
          documentSelectionMark.getConfidence()));
    });

    // tables
    List < DocumentTable > tables = analyzeLayoutResult.getTables();
    for (int i = 0; i < tables.size(); i++) {
      DocumentTable documentTable = tables.get(i);
      System.out.printf("Table %d has %d rows and %d columns.%n", i, documentTable.getRowCount(),
        documentTable.getColumnCount());
      documentTable.getCells().forEach(documentTableCell -> {
        System.out.printf("Cell '%s', has row index %d and column index %d.%n", documentTableCell.getContent(),
          documentTableCell.getRowIndex(), documentTableCell.getColumnIndex());
      });
      System.out.println();
    }

    // styles
    analyzeLayoutResult.getStyles().forEach(documentStyle -
      > System.out.printf("Document is handwritten %s.%n", documentStyle.isHandwritten()));
  }

  /**
   * Utility function to get the bounding polygon coordinates.
   */
  private static String getBoundingCoordinates(List < Point > Polygon) {
    return Polygon.stream().map(point -> String.format("[%.2f, %.2f]", point.getX(),
      point.getY())).collect(Collectors.joining(", "));
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ (form-recognize-app) に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

事前構築済みモデル

事前構築済みのモデルを使用して、特定のドキュメントの種類の共通フィールドを分析して抽出します。 この例では、 事前構築済みの 請求書モデルを使用して請求書を分析します。

ヒント

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 モデル データの抽出を参照してください。

  • 事前構築済みの請求書モデルを使用して請求書を分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • ファイルの URL 値が、ファイルの先頭にある invoiceUrl 変数に追加されました。
  • URI で特定のファイルを分析するには、 beginAnalyzeDocuments メソッドを使用し、モデル ID として PrebuiltModels.Invoice を渡します。戻り値は、送信されたドキュメントに関するデータを含む result オブジェクトです。
  • わかりやすくするために、サービスから返されるすべてのキーと値のペアはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

DocIntelligence.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.documentintelligence.DocumentIntelligenceClient;
import com.azure.ai.documentintelligence.DocumentIntelligenceClientBuilder;
import com.azure.ai.documentintelligence.models.AnalyzeDocumentOptions;
import com.azure.ai.documentintelligence.models.AnalyzeOperationDetails;
import com.azure.ai.documentintelligence.models.AnalyzeResult;
import com.azure.ai.documentintelligence.models.AnalyzedDocument;
import com.azure.ai.documentintelligence.models.DocumentField;
import com.azure.ai.documentintelligence.models.DocumentFieldType;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;

public class DocIntelligence {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(String[] args) {

    // create your `DocumentIntelligenceClient` instance and `AzureKeyCredential` variable
    DocumentIntelligenceClient client = new DocumentIntelligenceClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String modelId = "prebuilt-invoice";
    String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

    SyncPoller<AnalyzeOperationDetails, AnalyzeResult> analyzeInvoicesPoller =
      client.beginAnalyzeDocument(modelId, new AnalyzeDocumentOptions(invoiceUrl));

    AnalyzeResult analyzeInvoiceResult = analyzeInvoicesPoller.getFinalResult();

    for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
      AnalyzedDocument analyzedInvoice = analyzeInvoiceResult.getDocuments().get(i);
      Map<String, DocumentField> invoiceFields = analyzedInvoice.getFields();
      System.out.printf("----------- Analyzing invoice  %d -----------%n", i);
      DocumentField vendorNameField = invoiceFields.get("VendorName");
      if (vendorNameField != null) {
        if (DocumentFieldType.STRING == vendorNameField.getType()) {
          String merchantName = vendorNameField.getValueAsString();
          System.out.printf("Vendor Name: %s, confidence: %.2f%n",
            merchantName, vendorNameField.getConfidence());
        }
      }

      DocumentField vendorAddressField = invoiceFields.get("VendorAddress");
      if (vendorAddressField != null) {
        if (DocumentFieldType.STRING == vendorAddressField.getType()) {
          String merchantAddress = vendorAddressField.getValueAsString();
          System.out.printf("Vendor address: %s, confidence: %.2f%n",
            merchantAddress, vendorAddressField.getConfidence());
        }
      }

      DocumentField customerNameField = invoiceFields.get("CustomerName");
      if (customerNameField != null) {
        if (DocumentFieldType.STRING == customerNameField.getType()) {
          String merchantAddress = customerNameField.getValueAsString();
          System.out.printf("Customer Name: %s, confidence: %.2f%n",
            merchantAddress, customerNameField.getConfidence());
        }
      }

      DocumentField customerAddressRecipientField = invoiceFields.get("CustomerAddressRecipient");
      if (customerAddressRecipientField != null) {
        if (DocumentFieldType.STRING == customerAddressRecipientField.getType()) {
          String customerAddr = customerAddressRecipientField.getValueAsString();
          System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n",
            customerAddr, customerAddressRecipientField.getConfidence());
        }
      }

      DocumentField invoiceIdField = invoiceFields.get("InvoiceId");
      if (invoiceIdField != null) {
        if (DocumentFieldType.STRING == invoiceIdField.getType()) {
          String invoiceId = invoiceIdField.getValueAsString();
          System.out.printf("Invoice ID: %s, confidence: %.2f%n",
            invoiceId, invoiceIdField.getConfidence());
        }
      }

      DocumentField invoiceDateField = invoiceFields.get("InvoiceDate");
      if (invoiceDateField != null) {
        if (DocumentFieldType.DATE == invoiceDateField.getType()) {
          LocalDate invoiceDate = invoiceDateField.getValueAsDate();
          System.out.printf("Invoice Date: %s, confidence: %.2f%n",
            invoiceDate, invoiceDateField.getConfidence());
        }
      }

      DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
      if (invoiceTotalField != null) {
        if (DocumentFieldType.DOUBLE == invoiceTotalField.getType()) {
          Double invoiceTotal = invoiceTotalField.getValueAsDouble();
          System.out.printf("Invoice Total: %.2f, confidence: %.2f%n",
            invoiceTotal, invoiceTotalField.getConfidence());
        }
      }

      DocumentField invoiceItemsField = invoiceFields.get("Items");
      if (invoiceItemsField != null) {
        System.out.printf("Invoice Items: %n");
        if (DocumentFieldType.LIST == invoiceItemsField.getType()) {
          List<DocumentField> invoiceItems = invoiceItemsField.getValueAsList();
          invoiceItems.stream()
            .filter(invoiceItem -> DocumentFieldType.MAP == invoiceItem.getType())
            .map(documentField -> documentField.getValueAsMap())
            .forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {

              // See a full list of fields found on an invoice here:
              // https://aka.ms/documentintelligence/invoicefields

              if ("Description".equals(key)) {
                if (DocumentFieldType.STRING == documentField.getType()) {
                  String name = documentField.getValueAsString();
                  System.out.printf("Description: %s, confidence: %.2fs%n",
                    name, documentField.getConfidence());
                }
              }
              if ("Quantity".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double quantity = documentField.getValueAsDouble();
                  System.out.printf("Quantity: %f, confidence: %.2f%n",
                    quantity, documentField.getConfidence());
                }
              }
              if ("UnitPrice".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double unitPrice = documentField.getValueAsDouble();
                  System.out.printf("Unit Price: %f, confidence: %.2f%n",
                    unitPrice, documentField.getConfidence());
                }
              }
              if ("ProductCode".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double productCode = documentField.getValueAsDouble();
                  System.out.printf("Product Code: %f, confidence: %.2f%n",
                    productCode, documentField.getConfidence());
                }
              }
            }));
        }
      }
    }
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ doc-intel-app に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

FormRecognizer.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.formrecognizer.documentanalysis.models.*;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;

import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.io.IOException;
import java.util.List;
import java.util.Arrays;
import java.time.LocalDate;
import java.util.Map;
import java.util.stream.Collectors;

public class FormRecognizer {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(final String[] args) throws IOException {

    // create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
    DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String modelId = "prebuilt-invoice";
    String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

    SyncPoller < OperationResult, AnalyzeResult > analyzeInvoicePoller = client.beginAnalyzeDocumentFromUrl(modelId, invoiceUrl);

    AnalyzeResult analyzeInvoiceResult = analyzeInvoicePoller.getFinalResult();

    for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
      AnalyzedDocument analyzedInvoice = analyzeInvoiceResult.getDocuments().get(i);
      Map < String, DocumentField > invoiceFields = analyzedInvoice.getFields();
      System.out.printf("----------- Analyzing invoice  %d -----------%n", i);
      DocumentField vendorNameField = invoiceFields.get("VendorName");
      if (vendorNameField != null) {
        if (DocumentFieldType.STRING == vendorNameField.getType()) {
          String merchantName = vendorNameField.getValueAsString();
          System.out.printf("Vendor Name: %s, confidence: %.2f%n",
            merchantName, vendorNameField.getConfidence());
        }
      }

      DocumentField vendorAddressField = invoiceFields.get("VendorAddress");
      if (vendorAddressField != null) {
        if (DocumentFieldType.STRING == vendorAddressField.getType()) {
          String merchantAddress = vendorAddressField.getValueAsString();
          System.out.printf("Vendor address: %s, confidence: %.2f%n",
            merchantAddress, vendorAddressField.getConfidence());
        }
      }

      DocumentField customerNameField = invoiceFields.get("CustomerName");
      if (customerNameField != null) {
        if (DocumentFieldType.STRING == customerNameField.getType()) {
          String merchantAddress = customerNameField.getValueAsString();
          System.out.printf("Customer Name: %s, confidence: %.2f%n",
            merchantAddress, customerNameField.getConfidence());
        }
      }

      DocumentField customerAddressRecipientField = invoiceFields.get("CustomerAddressRecipient");
      if (customerAddressRecipientField != null) {
        if (DocumentFieldType.STRING == customerAddressRecipientField.getType()) {
          String customerAddr = customerAddressRecipientField.getValueAsString();
          System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n",
            customerAddr, customerAddressRecipientField.getConfidence());
        }
      }

      DocumentField invoiceIdField = invoiceFields.get("InvoiceId");
      if (invoiceIdField != null) {
        if (DocumentFieldType.STRING == invoiceIdField.getType()) {
          String invoiceId = invoiceIdField.getValueAsString();
          System.out.printf("Invoice ID: %s, confidence: %.2f%n",
            invoiceId, invoiceIdField.getConfidence());
        }
      }

      DocumentField invoiceDateField = invoiceFields.get("InvoiceDate");
      if (customerNameField != null) {
        if (DocumentFieldType.DATE == invoiceDateField.getType()) {
          LocalDate invoiceDate = invoiceDateField.getValueAsDate();
          System.out.printf("Invoice Date: %s, confidence: %.2f%n",
            invoiceDate, invoiceDateField.getConfidence());
        }
      }

      DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
      if (customerAddressRecipientField != null) {
        if (DocumentFieldType.DOUBLE == invoiceTotalField.getType()) {
          Double invoiceTotal = invoiceTotalField.getValueAsDouble();
          System.out.printf("Invoice Total: %.2f, confidence: %.2f%n",
            invoiceTotal, invoiceTotalField.getConfidence());
        }
      }

      DocumentField invoiceItemsField = invoiceFields.get("Items");
      if (invoiceItemsField != null) {
        System.out.printf("Invoice Items: %n");
        if (DocumentFieldType.LIST == invoiceItemsField.getType()) {
          List < DocumentField > invoiceItems = invoiceItemsField.getValueAsList();
          invoiceItems.stream()
            .filter(invoiceItem -> DocumentFieldType.MAP == invoiceItem.getType())
            .map(documentField -> documentField.getValueAsMap())
            .forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {

              // See a full list of fields found on an invoice here:
              // https://aka.ms/formrecognizer/invoicefields

              if ("Description".equals(key)) {
                if (DocumentFieldType.STRING == documentField.getType()) {
                  String name = documentField.getValueAsString();
                  System.out.printf("Description: %s, confidence: %.2fs%n",
                    name, documentField.getConfidence());
                }
              }
              if ("Quantity".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double quantity = documentField.getValueAsDouble();
                  System.out.printf("Quantity: %f, confidence: %.2f%n",
                    quantity, documentField.getConfidence());
                }
              }
              if ("UnitPrice".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double unitPrice = documentField.getValueAsDouble();
                  System.out.printf("Unit Price: %f, confidence: %.2f%n",
                    unitPrice, documentField.getConfidence());
                }
              }
              if ("ProductCode".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double productCode = documentField.getValueAsDouble();
                  System.out.printf("Product Code: %f, confidence: %.2f%n",
                    productCode, documentField.getConfidence());
                }
              }
            }));
        }
      }
    }
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ doc-intel-app に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

事前構築済みモデルの出力

予想される出力のスニペットを次に示します。

  ----------- Analyzing invoice  0 -----------
  Analyzed document has doc type invoice with confidence : 1.00
  Vendor Name: CONTOSO LTD., confidence: 0.92
  Vendor address: 123 456th St New York, NY, 10001, confidence: 0.91
  Customer Name: MICROSOFT CORPORATION, confidence: 0.84
  Customer Address Recipient: Microsoft Corp, confidence: 0.92
  Invoice ID: INV-100, confidence: 0.97
  Invoice Date: 2019-11-15, confidence: 0.97

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、事前構築済みの請求書モデルの出力を表示します。

FormRecognizer.java ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClient;
import com.azure.ai.formrecognizer.documentanalysis.DocumentAnalysisClientBuilder;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzeResult;
import com.azure.ai.formrecognizer.documentanalysis.models.AnalyzedDocument;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentField;
import com.azure.ai.formrecognizer.documentanalysis.models.DocumentFieldType;
import com.azure.ai.formrecognizer.documentanalysis.models.OperationResult;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

public class FormRecognizer {

  // set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
  private static final String endpoint = "<your-endpoint>";
  private static final String key = "<your-key>";

  public static void main(String[] args) {

    // create your `DocumentAnalysisClient` instance and `AzureKeyCredential` variable
    DocumentAnalysisClient client = new DocumentAnalysisClientBuilder()
      .credential(new AzureKeyCredential(key))
      .endpoint(endpoint)
      .buildClient();

    // sample document
    String modelId = "prebuilt-invoice";
    String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

    SyncPoller < OperationResult, AnalyzeResult > analyzeInvoicePoller = client.beginAnalyzeDocumentFromUrl(modelId, invoiceUrl);

    AnalyzeResult analyzeInvoiceResult = analyzeInvoicePoller.getFinalResult();

    for (int i = 0; i < analyzeInvoiceResult.getDocuments().size(); i++) {
      AnalyzedDocument analyzedInvoice = analyzeInvoiceResult.getDocuments().get(i);
      Map < String, DocumentField > invoiceFields = analyzedInvoice.getFields();
      System.out.printf("----------- Analyzing invoice  %d -----------%n", i);
      DocumentField vendorNameField = invoiceFields.get("VendorName");
      if (vendorNameField != null) {
        if (DocumentFieldType.STRING == vendorNameField.getType()) {
          String merchantName = vendorNameField.getValueAsString();
          System.out.printf("Vendor Name: %s, confidence: %.2f%n",
            merchantName, vendorNameField.getConfidence());
        }
      }

      DocumentField vendorAddressField = invoiceFields.get("VendorAddress");
      if (vendorAddressField != null) {
        if (DocumentFieldType.STRING == vendorAddressField.getType()) {
          String merchantAddress = vendorAddressField.getValueAsString();
          System.out.printf("Vendor address: %s, confidence: %.2f%n",
            merchantAddress, vendorAddressField.getConfidence());
        }
      }

      DocumentField customerNameField = invoiceFields.get("CustomerName");
      if (customerNameField != null) {
        if (DocumentFieldType.STRING == customerNameField.getType()) {
          String merchantAddress = customerNameField.getValueAsString();
          System.out.printf("Customer Name: %s, confidence: %.2f%n",
            merchantAddress, customerNameField.getConfidence());
        }
      }

      DocumentField customerAddressRecipientField = invoiceFields.get("CustomerAddressRecipient");
      if (customerAddressRecipientField != null) {
        if (DocumentFieldType.STRING == customerAddressRecipientField.getType()) {
          String customerAddr = customerAddressRecipientField.getValueAsString();
          System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n",
            customerAddr, customerAddressRecipientField.getConfidence());
        }
      }

      DocumentField invoiceIdField = invoiceFields.get("InvoiceId");
      if (invoiceIdField != null) {
        if (DocumentFieldType.STRING == invoiceIdField.getType()) {
          String invoiceId = invoiceIdField.getValueAsString();
          System.out.printf("Invoice ID: %s, confidence: %.2f%n",
            invoiceId, invoiceIdField.getConfidence());
        }
      }

      DocumentField invoiceDateField = invoiceFields.get("InvoiceDate");
      if (customerNameField != null) {
        if (DocumentFieldType.DATE == invoiceDateField.getType()) {
          LocalDate invoiceDate = invoiceDateField.getValueAsDate();
          System.out.printf("Invoice Date: %s, confidence: %.2f%n",
            invoiceDate, invoiceDateField.getConfidence());
        }
      }

      DocumentField invoiceTotalField = invoiceFields.get("InvoiceTotal");
      if (customerAddressRecipientField != null) {
        if (DocumentFieldType.DOUBLE == invoiceTotalField.getType()) {
          Double invoiceTotal = invoiceTotalField.getValueAsDouble();
          System.out.printf("Invoice Total: %.2f, confidence: %.2f%n",
            invoiceTotal, invoiceTotalField.getConfidence());
        }
      }

      DocumentField invoiceItemsField = invoiceFields.get("Items");
      if (invoiceItemsField != null) {
        System.out.printf("Invoice Items: %n");
        if (DocumentFieldType.LIST == invoiceItemsField.getType()) {
          List < DocumentField > invoiceItems = invoiceItemsField.getValueAsList();
          invoiceItems.stream()
            .filter(invoiceItem -> DocumentFieldType.MAP == invoiceItem.getType())
            .map(documentField -> documentField.getValueAsMap())
            .forEach(documentFieldMap -> documentFieldMap.forEach((key, documentField) -> {

              // See a full list of fields found on an invoice here:
              // https://aka.ms/formrecognizer/invoicefields

              if ("Description".equals(key)) {
                if (DocumentFieldType.STRING == documentField.getType()) {
                  String name = documentField.getValueAsString();
                  System.out.printf("Description: %s, confidence: %.2fs%n",
                    name, documentField.getConfidence());
                }
              }
              if ("Quantity".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double quantity = documentField.getValueAsDouble();
                  System.out.printf("Quantity: %f, confidence: %.2f%n",
                    quantity, documentField.getConfidence());
                }
              }
              if ("UnitPrice".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double unitPrice = documentField.getValueAsDouble();
                  System.out.printf("Unit Price: %f, confidence: %.2f%n",
                    unitPrice, documentField.getConfidence());
                }
              }
              if ("ProductCode".equals(key)) {
                if (DocumentFieldType.DOUBLE == documentField.getType()) {
                  Double productCode = documentField.getValueAsDouble();
                  System.out.printf("Product Code: %f, confidence: %.2f%n",
                    productCode, documentField.getConfidence());
                }
              }
            }));
        }
      }
    }
  }
}

アプリケーションをビルドして実行する

アプリケーションにコード サンプルを追加したら、メイン プロジェクト ディレクトリ doc-intel-app に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。

    gradle build
    
  2. run コマンドを使用してアプリケーションを実行します。

    gradle run
    

クライアントライブラリREST API リファレンスパッケージ (npm)サンプルサポートされている REST API バージョン

このクイック スタートでは、次の機能を使用して、フォームとドキュメントからデータと値を分析および抽出します。

  • レイアウト - モデルをトレーニングする必要なく、ドキュメント内のラジオ ボタンやチェック ボックスなどのテーブル、線、単語、選択マークを分析して抽出します。

  • 事前構築済みの請求書 - 事前トレーニング済みの請求書モデルを使用して、特定のドキュメントの種類の共通フィールドを分析および抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • 最新バージョンの Visual Studio Code または任意の IDE。 詳細については、Visual Studio Code の Node.js を参照してください。

  • Node.jsの最新のLTSバージョン。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または multi-service Document Intelligence リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

  1. 新しい Node.js Express アプリケーションの作成: コンソール ウィンドウ (cmd、PowerShell、Bash など) で、 doc-intel-app という名前のアプリの新しいディレクトリを作成して移動します。

    mkdir doc-intel-app && cd doc-intel-app
    
  2. npm init コマンドを実行してアプリケーションを初期化し、プロジェクトをスキャフォールディングします。

    npm init
    
  3. ターミナルに表示されるプロンプトを使用して、プロジェクトの属性を指定します。

    • 最も重要な属性は、名前、バージョン番号、およびエントリ ポイントです。
    • エントリ ポイント名の index.js を維持することをお勧めします。 説明、テスト コマンド、GitHub リポジトリ、キーワード、作成者、ライセンス情報は省略可能な属性であり、このプロジェクトではスキップできます。
    • [戻る] または [Enter] を選択して、かっこ内の候補を受け入れます。
    • プロンプトが完了すると、doc-intel-app ディレクトリに package.json ファイルが作成されます。
  1. ai-document-intelligence クライアント ライブラリをインストールし、npm パッケージをazure/identityします。

    npm i @azure-rest/ai-document-intelligence@1.1.0
    

    アプリの package.json ファイルが依存関係で更新されます。

  1. ai-form-recognizer クライアント ライブラリをインストールし、npm パッケージをazure/identityします。

    npm i @azure/ai-form-recognizer@5.0.0 @azure/identity
    
    • アプリの package.json ファイルが依存関係で更新されます。
  1. ai-form-recognizer クライアント ライブラリをインストールし、npm パッケージをazure/identityします。

    npm i @azure/ai-form-recognizer@4.0.0 @azure/identity
    
  1. アプリケーション ディレクトリに index.js という名前のファイルを作成します。

    ヒント

    • PowerShell を使用して新しいファイルを作成できます。
    • Shift キーを押しながらフォルダーを右クリックして、プロジェクト ディレクトリの PowerShell ウィンドウを開きます。
    • 次のコマンド をNew-Item index.js入力します。

アプリケーションをビルドする

ドキュメント インテリジェンス サービスと対話するには、 DocumentIntelligenceClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentIntelligenceClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

ドキュメント インテリジェンス サービスと対話するには、 DocumentAnalysisClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentAnalysisClient と Form Recognizer AzureKeyCredential を使用して endpoint インスタンスを作成します。

  1. Visual Studio Codeまたは任意の IDE で index.js ファイルを開きます。 次のコード サンプルのいずれかをコピーして、アプリケーションに貼り付けます。

重要

クラウドで実行されるアプリケーションに資格情報を格納しないように、 Azure リソースの管理された ID を使用して認証をMicrosoft Entra IDすることをお勧めします。

API キーは慎重に使用してください。 API キーをコードに直接含めず、パブリックに投稿しないでください。 API キーを使用する場合は、Azure Key Vaultに安全に格納し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用してAzure Key Vaultへのアクセスを制限します。 アプリで API キーを安全に使用する方法の詳細については、「Azure Key Vault を使用した API キー」を参照してください。

AI サービスのセキュリティの詳細については、「Authenticate requests to Azure AI サービス」を参照してください。

レイアウト モデル

ドキュメントからテキスト、選択マーク、テキスト スタイル、テーブル構造、境界領域座標を抽出します。

  • この例では、 URL からのドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • ファイルの URL 値が、ファイルの先頭付近にある formUrl 変数に追加されました。
  • URL から特定のファイルを分析するには、 beginAnalyzeDocuments メソッドを使用し、モデル ID として prebuilt-layout 渡します。
const DocumentIntelligence = require("@azure-rest/ai-document-intelligence").default,
{ getLongRunningPoller, isUnexpected } = require("@azure-rest/ai-document-intelligence");

// set `<your-key>` and `<your-endpoint>` variables with the values from the Azure portal.
const key = "<your-key>";
const endpoint = "<your-endpoint>";

// sample document
const formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

async function main() {
  const client = DocumentIntelligence(endpoint, { key });

  const initialResponse = await client
    .path("/documentModels/{modelId}:analyze", "prebuilt-layout")
    .post({
      contentType: "application/json",
      body: {
        urlSource: formUrl
      },
    });

  if (isUnexpected(initialResponse)) {
    throw initialResponse.body.error;
  }

  const poller = getLongRunningPoller(client, initialResponse);
  const analyzeResult = (await poller.pollUntilDone()).body.analyzeResult;

  const pages = analyzeResult?.pages;
  const tables = analyzeResult?.tables;

  if (pages && pages.length > 0) {
    console.log("Pages:");
    for (const page of pages) {
      console.log("- Page", page.pageNumber, `(unit: ${page.unit})`);
      console.log(`  ${page.width}x${page.height}`);
      console.log(`  ${page.lines?.length || 0} lines, ${page.words?.length || 0} words`);
    }
  } else {
    console.log("No pages were extracted from the document.");
  }

  if (tables && tables.length > 0) {
    console.log("Tables:");
    for (const table of tables) {
      console.log(
        `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)`
      );
    }
  } else {
    console.log("No tables were extracted from the document.");
  }
}

main().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムを実行します。

  1. ドキュメント インテリジェンス アプリケーション (doc-intel-app) があるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    node index.js
    

index.js ファイルに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


 const { AzureKeyCredential, DocumentAnalysisClient } = require("@azure/ai-form-recognizer");

    // set `<your-key>` and `<your-endpoint>` variables with the values from the Azure portal.
    const key = "<your-key>";
    const endpoint = "<your-endpoint>";

    // sample document
  const formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

  async function main() {
    const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(key));

    const poller = await client.beginAnalyzeDocumentFromUrl("prebuilt-layout", formUrl);

    const {
        pages,
        tables
    } = await poller.pollUntilDone();

    if (pages.length <= 0) {
        console.log("No pages were extracted from the document.");
    } else {
        console.log("Pages:");
        for (const page of pages) {
            console.log("- Page", page.pageNumber, `(unit: ${page.unit})`);
            console.log(`  ${page.width}x${page.height}, angle: ${page.angle}`);
            console.log(`  ${page.lines.length} lines, ${page.words.length} words`);
        }
    }

    if (tables.length <= 0) {
        console.log("No tables were extracted from the document.");
    } else {
        console.log("Tables:");
        for (const table of tables) {
            console.log(
                `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)`
            );
        }
    }
}

main().catch((error) => {
    console.error("An error occurred:", error);
    process.exit(1);
});

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムを実行します。

  1. ドキュメント インテリジェンス アプリケーション (doc-intel-app) があるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    node index.js
    

レイアウト モデルの出力

予想される出力のスニペットを次に示します。

Pages:
- Page 1 (unit: inch)
  8.5x11, angle: 0
  69 lines, 425 words
Tables:
- Extracted table: 3 columns, 5 rows (15 cells)

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、レイアウト モデルの出力を表示します。

事前構築済みモデル

この例では、 事前構築済みの 請求書モデルを使用して請求書を分析します。

ヒント

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 モデル データの抽出を参照してください。

  • 事前構築済みの請求書モデルを使用して請求書を分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • ファイルの URL 値が、ファイルの先頭にある invoiceUrl 変数に追加されました。
  • URI で特定のファイルを分析するには、 beginAnalyzeDocuments メソッドを使用し、モデル ID として PrebuiltModels.Invoice を渡します。戻り値は、送信されたドキュメントに関するデータを含む result オブジェクトです。
  • わかりやすくするために、サービスから返されるすべてのキーと値のペアはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。
const DocumentIntelligence = require("@azure-rest/ai-document-intelligence").default,
{ getLongRunningPoller, isUnexpected } = require("@azure-rest/ai-document-intelligence");

// set `<your-key>` and `<your-endpoint>` variables with the values from the Azure portal.
const key = "<your-key>";
const endpoint = "<your-endpoint>";

// sample document
const invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

async function main() {
  const client = DocumentIntelligence(endpoint, { key });

  const initialResponse = await client
    .path("/documentModels/{modelId}:analyze", "prebuilt-invoice")
    .post({
      contentType: "application/json",
      body: {
        urlSource: invoiceUrl,
      },
    });

  if (isUnexpected(initialResponse)) {
    throw initialResponse.body.error;
  }

  const poller = getLongRunningPoller(client, initialResponse);
  const analyzeResult = (await poller.pollUntilDone()).body.analyzeResult;

  const documents = analyzeResult?.documents;

  const invoice = documents && documents[0];
  if (!invoice) {
    throw new Error("Expected at least one invoice in the result.");
  }

  console.log(
    "Extracted invoice:",
    invoice.docType,
    `(confidence: ${invoice.confidence || "<undefined>"})`
  );
  console.log("Fields:", invoice.fields);
}

main().catch((error) => {
  console.error("An error occurred:", error);
  process.exit(1);
});

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムを実行します。

  1. ドキュメント インテリジェンス アプリケーション (doc-intel-app) があるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    node index.js
    

 const {
    AzureKeyCredential,
    DocumentAnalysisClient
} = require("@azure/ai-form-recognizer");

// set `<your-key>` and `<your-endpoint>` variables with the values from the Azure portal.
const key = "<your-key>";
const endpoint = "<your-endpoint>";
// sample document
invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

async function main() {
    const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(key));

    const poller = await client.beginAnalyzeDocumentFromUrl("prebuilt-invoice", invoiceUrl);

    const {
        pages,
        tables
    } = await poller.pollUntilDone();

    if (pages.length <= 0) {
        console.log("No pages were extracted from the document.");
    } else {
        console.log("Pages:");
        for (const page of pages) {
            console.log("- Page", page.pageNumber, `(unit: ${page.unit})`);
            console.log(`  ${page.width}x${page.height}, angle: ${page.angle}`);
            console.log(`  ${page.lines.length} lines, ${page.words.length} words`);

            if (page.lines && page.lines.length > 0) {
                console.log("  Lines:");

                for (const line of page.lines) {
                    console.log(`  - "${line.content}"`);

                    // The words of the line can also be iterated independently. The words are computed based on their
                    // corresponding spans.
                    for (const word of line.words()) {
                        console.log(`    - "${word.content}"`);
                    }
                }
            }
        }
    }

    if (tables.length <= 0) {
        console.log("No tables were extracted from the document.");
    } else {
        console.log("Tables:");
        for (const table of tables) {
            console.log(
                `- Extracted table: ${table.columnCount} columns, ${table.rowCount} rows (${table.cells.length} cells)`
            );
        }
    }
}

main().catch((error) => {
    console.error("An error occurred:", error);
    process.exit(1);
});

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムを実行します。

  1. ドキュメント インテリジェンス アプリケーション (doc-intel-app) があるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    node index.js
    

事前構築済みモデルの出力

予想される出力のスニペットを次に示します。

  Vendor Name: CONTOSO LTD.
  Customer Name: MICROSOFT CORPORATION
  Invoice Date: 2019-11-15T00:00:00.000Z
  Due Date: 2019-12-15T00:00:00.000Z
  Items:
  - <no product code>
    Description: Test for 23 fields
    Quantity: 1
    Date: undefined
    Unit: undefined
    Unit Price: 1
    Tax: undefined
    Amount: 100

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、事前構築済みの請求書モデルの出力を表示します。

const { AzureKeyCredential, DocumentAnalysisClient } = require("@azure/ai-form-recognizer");

  // set `<your-key>` and `<your-endpoint>` variables with the values from the Azure portal.
      const key = "<your-key>";
      const endpoint = "<your-endpoint>";
// sample document
    invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

async function main() {
    const client = new DocumentAnalysisClient(endpoint, new AzureKeyCredential(key));

    const poller = await client.beginAnalyzeDocument("prebuilt-invoice", invoiceUrl);

    const {
    documents: [document],
  } = await poller.pollUntilDone();


  if (document) {
    const {
      vendorName,
      customerName,
      invoiceDate,
      dueDate,
      items,
      subTotal,
      previousUnpaidBalance,
      totalTax,
      amountDue,
    } = document.fields;

    // The invoice model has many fields. For details, *see* [Invoice model field extraction](../../prebuilt/invoice.md#field-extraction)
    console.log("Vendor Name:", vendorName && vendorName.value);
    console.log("Customer Name:", customerName && customerName.value);
    console.log("Invoice Date:", invoiceDate && invoiceDate.value);
    console.log("Due Date:", dueDate && dueDate.value);

    console.log("Items:");
    for (const item of (items && items.values) || []) {
      const { productCode, description, quantity, date, unit, unitPrice, tax, amount } =
        item.properties;

      console.log("-", (productCode && productCode.value) || "<no product code>");
      console.log("  Description:", description && description.value);
      console.log("  Quantity:", quantity && quantity.value);
      console.log("  Date:", date && date.value);
      console.log("  Unit:", unit && unit.value);
      console.log("  Unit Price:", unitPrice && unitPrice.value);
      console.log("  Tax:", tax && tax.value);
      console.log("  Amount:", amount && amount.value);
    }

    console.log("Subtotal:", subTotal && subTotal.value);
    console.log("Previous Unpaid Balance:", previousUnpaidBalance && previousUnpaidBalance.value);
    console.log("Tax:", totalTax && totalTax.value);
    console.log("Amount Due:", amountDue && amountDue.value);
  } else {
    throw new Error("Expected at least one receipt in the result.");
  }
}


main().catch((error) => {
    console.error("An error occurred:", error);
    process.exit(1);
});

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムを実行します。

  1. ドキュメント インテリジェンス アプリケーション (doc-intel-app) があるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    node index.js
    

Client ライブラリREST API リファレンスパッケージ (PyPi)サンプルサポートされている REST API バージョン

Client ライブラリREST API リファレンスパッケージ (PyPi)サンプルサポートされている REST API バージョン

クライアント ライブラリREST API リファレンスパッケージ (PyPi)サンプルサポートされている REST API バージョン

このクイック スタートでは、次の機能を使用して、フォームとドキュメントからデータを分析および抽出します。

  • レイアウト - モデルをトレーニングする必要なく、ラジオ ボタンやチェック ボックスなどのテーブル、線、単語、選択マーク、キーと値のペアを分析して抽出します。

  • 事前構築済みの請求書 - 事前トレーニング済みモデルを使用して、特定のドキュメントの種類の共通フィールドを分析および抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • Python 3.7 以降

    • Pythonインストールには、pipが含まれている必要があります。 コマンド ラインで pip --version を実行することで、pip がインストールされているかどうかを確認できます。 最新バージョンのPythonをインストールして pip を取得します。
  • 最新バージョンの Visual Studio Code または任意の IDE。 詳細については、Visual Studio Code で始める Python」を参照してください。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または multi-service Document Intelligence リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

ヒント

1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

ローカル環境でターミナルウィンドウを開き、pipを使用してPython向けのFoundry Tools クライアントライブラリにAzure Document Intelligenceをインストールします。

pip install azure-ai-documentintelligence==1.0.2

pip install azure-ai-formrecognizer==3.3.0

pip install azure-ai-formrecognizer==3.2.0b6

Python アプリケーションを作成する

ドキュメント インテリジェンス サービスと対話するには、 DocumentIntelligenceClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentIntelligenceClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

  1. 任意のエディターまたは IDE で、doc_intel_quickstart.py という名前の新しいPython ファイルを作成します。

  2. doc_intel_quickstart.py ファイルを開き、次のコード サンプルのいずれかを選択して、アプリケーションにコピーして貼り付けます。

ドキュメント インテリジェンス サービスと対話するには、 DocumentAnalysisClient クラスのインスタンスを作成する必要があります。 これを行うには、Azure ポータルから AzureKeyCredential を使用して key を作成し、DocumentAnalysisClient とドキュメント インテリジェンス AzureKeyCredential を使用して endpoint インスタンスを作成します。

  1. 任意のエディターまたは IDE で、form_recognizer_quickstart.py という名前の新しいPython ファイルを作成します。

  2. form_recognizer_quickstart.py ファイルを開き、次のコード サンプルのいずれかを選択して、アプリケーションにコピーして貼り付けます。

重要

クラウドで実行されるアプリケーションに資格情報を格納しないように、 Azure リソースの管理された ID を使用して認証をMicrosoft Entra IDすることをお勧めします。

API キーは慎重に使用してください。 API キーをコードに直接含めず、パブリックに投稿しないでください。 API キーを使用する場合は、Azure Key Vaultに安全に格納し、キーを定期的にローテーションし、ロールベースのアクセス制御とネットワーク アクセス制限を使用してAzure Key Vaultへのアクセスを制限します。 アプリで API キーを安全に使用する方法の詳細については、「Azure Key Vault を使用した API キー」を参照してください。

AI サービスのセキュリティの詳細については、「Authenticate requests to Azure AI サービス」を参照してください。

レイアウト モデル

ドキュメントからテキスト、選択マーク、テキスト スタイル、テーブル構造、境界領域座標を抽出します。

  • この例では、 URL からのドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • formUrl関数のanalyze_layout変数にファイル URL 値を追加しました。

doc_intel_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


# import libraries
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.ai.documentintelligence.models import AnalyzeResult
from azure.ai.documentintelligence.models import AnalyzeDocumentRequest

# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"

# helper functions

def get_words(page, line):
    result = []
    for word in page.words:
        if _in_span(word, line.spans):
            result.append(word)
    return result


def _in_span(word, spans):
    for span in spans:
        if word.span.offset >= span.offset and (
            word.span.offset + word.span.length
        ) <= (span.offset + span.length):
            return True
    return False


def analyze_layout():
    # sample document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    document_intelligence_client = DocumentIntelligenceClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_intelligence_client.begin_analyze_document(
        "prebuilt-layout", AnalyzeDocumentRequest(url_source=formUrl
    ))

    result: AnalyzeResult = poller.result()

    if result.styles and any([style.is_handwritten for style in result.styles]):
        print("Document contains handwritten content")
    else:
        print("Document does not contain handwritten content")

    for page in result.pages:
        print(f"----Analyzing layout from page #{page.page_number}----")
        print(
            f"Page has width: {page.width} and height: {page.height}, measured with unit: {page.unit}"
        )

        if page.lines:
            for line_idx, line in enumerate(page.lines):
                words = get_words(page, line)
                print(
                    f"...Line # {line_idx} has word count {len(words)} and text '{line.content}' "
                    f"within bounding polygon '{line.polygon}'"
                )

                for word in words:
                    print(
                        f"......Word '{word.content}' has a confidence of {word.confidence}"
                    )

        if page.selection_marks:
            for selection_mark in page.selection_marks:
                print(
                    f"Selection mark is '{selection_mark.state}' within bounding polygon "
                    f"'{selection_mark.polygon}' and has a confidence of {selection_mark.confidence}"
                )

    if result.tables:
        for table_idx, table in enumerate(result.tables):
            print(
                f"Table # {table_idx} has {table.row_count} rows and "
                f"{table.column_count} columns"
            )
            if table.bounding_regions:
                for region in table.bounding_regions:
                    print(
                        f"Table # {table_idx} location on page: {region.page_number} is {region.polygon}"
                    )
            for cell in table.cells:
                print(
                    f"...Cell[{cell.row_index}][{cell.column_index}] has text '{cell.content}'"
                )
                if cell.bounding_regions:
                    for region in cell.bounding_regions:
                        print(
                            f"...content on page {region.page_number} is within bounding polygon '{region.polygon}'"
                        )

    print("----------------------------------------")


if __name__ == "__main__":
    analyze_layout()

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. doc_intel_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python doc_intel_quickstart.py
    

URL で特定のファイルを分析するには、 begin_analyze_document_from_url メソッドを使用し、モデル ID として prebuilt-layout 渡します。 返される値は、送信されたドキュメントに関するデータを含む result オブジェクトです。

form_recognizer_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


# import libraries
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"

def format_polygon(polygon):
    if not polygon:
        return "N/A"
    return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon])

def analyze_layout():
    # sample document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_analysis_client.begin_analyze_document_from_url(
            "prebuilt-layout", formUrl)
    result = poller.result()

    for idx, style in enumerate(result.styles):
        print(
            "Document contains {} content".format(
                "handwritten" if style.is_handwritten else "no handwritten"
            )
        )

    for page in result.pages:
        print("----Analyzing layout from page #{}----".format(page.page_number))
        print(
            "Page has width: {} and height: {}, measured with unit: {}".format(
                page.width, page.height, page.unit
            )
        )

        for line_idx, line in enumerate(page.lines):
            words = line.get_words()
            print(
                "...Line # {} has word count {} and text '{}' within bounding box '{}'".format(
                    line_idx,
                    len(words),
                    line.content,
                    format_polygon(line.polygon),
                )
            )

            for word in words:
                print(
                    "......Word '{}' has a confidence of {}".format(
                        word.content, word.confidence
                    )
                )

        for selection_mark in page.selection_marks:
            print(
                "...Selection mark is '{}' within bounding box '{}' and has a confidence of {}".format(
                    selection_mark.state,
                    format_polygon(selection_mark.polygon),
                    selection_mark.confidence,
                )
            )

    for table_idx, table in enumerate(result.tables):
        print(
            "Table # {} has {} rows and {} columns".format(
                table_idx, table.row_count, table.column_count
            )
        )
        for region in table.bounding_regions:
            print(
                "Table # {} location on page: {} is {}".format(
                    table_idx,
                    region.page_number,
                    format_polygon(region.polygon),
                )
            )
        for cell in table.cells:
            print(
                "...Cell[{}][{}] has content '{}'".format(
                    cell.row_index,
                    cell.column_index,
                    cell.content,
                )
            )
            for region in cell.bounding_regions:
                print(
                    "...content on page {} is within bounding box '{}'".format(
                        region.page_number,
                        format_polygon(region.polygon),
                    )
                )

    print("----------------------------------------")


if __name__ == "__main__":
    analyze_layout()

アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. form_recognizer_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python form_recognizer_quickstart.py
    

レイアウト モデルの出力

予想される出力のスニペットを次に示します。

  ----Analyzing layout from page #1----
  Page has width: 8.5 and height: 11.0, measured with unit: inch
  ...Line # 0 has word count 2 and text 'UNITED STATES' within bounding box '[3.4915, 0.6828], [5.0116, 0.6828], [5.0116, 0.8265], [3.4915, 0.8265]'
  ......Word 'UNITED' has a confidence of 1.0
  ......Word 'STATES' has a confidence of 1.0
  ...Line # 1 has word count 4 and text 'SECURITIES AND EXCHANGE COMMISSION' within bounding box '[2.1937, 0.9061], [6.297, 0.9061], [6.297, 1.0498], [2.1937, 1.0498]'
  ......Word 'SECURITIES' has a confidence of 1.0
  ......Word 'AND' has a confidence of 1.0
  ......Word 'EXCHANGE' has a confidence of 1.0
  ......Word 'COMMISSION' has a confidence of 1.0
  ...Line # 2 has word count 3 and text 'Washington, D.C. 20549' within bounding box '[3.4629, 1.1179], [5.031, 1.1179], [5.031, 1.2483], [3.4629, 1.2483]'
  ......Word 'Washington,' has a confidence of 1.0
  ......Word 'D.C.' has a confidence of 1.0

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、レイアウト モデルの出力を表示します。

form_recognizer_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


# import libraries
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"


def analyze_layout():
    # sample document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_analysis_client.begin_analyze_document_from_url(
        "prebuilt-layout", formUrl
    )
    result = poller.result()

    for idx, style in enumerate(result.styles):
        print(
            "Document contains {} content".format(
                "handwritten" if style.is_handwritten else "no handwritten"
            )
        )

    for page in result.pages:
        print("----Analyzing layout from page #{}----".format(page.page_number))
        print(
            "Page has width: {} and height: {}, measured with unit: {}".format(
                page.width, page.height, page.unit
            )
        )

        for line_idx, line in enumerate(page.lines):
            words = line.get_words()
            print(
                "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format(
                    line_idx,
                    len(words),
                    line.content,
                    format_polygon(line.polygon),
                )
            )

            for word in words:
                print(
                    "......Word '{}' has a confidence of {}".format(
                        word.content, word.confidence
                    )
                )

        for selection_mark in page.selection_marks:
            print(
                "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format(
                    selection_mark.state,
                    format_polygon(selection_mark.polygon),
                    selection_mark.confidence,
                )
            )

    for table_idx, table in enumerate(result.tables):
        print(
            "Table # {} has {} rows and {} columns".format(
                table_idx, table.row_count, table.column_count
            )
        )
        for region in table.bounding_regions:
            print(
                "Table # {} location on page: {} is {}".format(
                    table_idx,
                    region.page_number,
                    format_polygon(region.polygon),
                )
            )
        for cell in table.cells:
            print(
                "...Cell[{}][{}] has content '{}'".format(
                    cell.row_index,
                    cell.column_index,
                    cell.content,
                )
            )
            for region in cell.bounding_regions:
                print(
                    "...content on page {} is within bounding polygon '{}'".format(
                        region.page_number,
                        format_polygon(region.polygon),
                    )
                )

    print("----------------------------------------")


if __name__ == "__main__":
    analyze_layout()


アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. form_recognizer_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python form_recognizer_quickstart.py
    

事前構築済みモデル

事前構築済みのモデルを使用して、特定のドキュメントの種類の共通フィールドを分析して抽出します。 この例では、 事前構築済みの 請求書モデルを使用して請求書を分析します。

ヒント

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 モデル データの抽出を参照してください。

  • 事前構築済みの請求書モデルを使用して請求書を分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • ファイルの URL 値が、ファイルの先頭にある invoiceUrl 変数に追加されました。
  • わかりやすくするために、サービスから返されるすべてのキーと値のペアはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

doc_intel_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルのドキュメント インテリジェンス インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


# import libraries
import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.documentintelligence import DocumentIntelligenceClient
from azure.ai.documentintelligence.models import AnalyzeResult
from azure.ai.documentintelligence.models import AnalyzeDocumentRequest



# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"

def analyze_invoice():
    # sample document

    invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

    document_intelligence_client = DocumentIntelligenceClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_intelligence_client.begin_analyze_document(
        "prebuilt-invoice", AnalyzeDocumentRequest(url_source=invoiceUrl)
    )
    invoices = poller.result()

    if invoices.documents:
        for idx, invoice in enumerate(invoices.documents):
            print(f"--------Analyzing invoice #{idx + 1}--------")
            vendor_name = invoice.fields.get("VendorName")
            if vendor_name:
                print(
                    f"Vendor Name: {vendor_name.get('content')} has confidence: {vendor_name.get('confidence')}"
                )
            vendor_address = invoice.fields.get("VendorAddress")
            if vendor_address:
                print(
                    f"Vendor Address: {vendor_address.get('content')} has confidence: {vendor_address.get('confidence')}"
                )
            vendor_address_recipient = invoice.fields.get("VendorAddressRecipient")
            if vendor_address_recipient:
                print(
                    f"Vendor Address Recipient: {vendor_address_recipient.get('content')} has confidence: {vendor_address_recipient.get('confidence')}"
                )
            customer_name = invoice.fields.get("CustomerName")
            if customer_name:
                print(
                    f"Customer Name: {customer_name.get('content')} has confidence: {customer_name.get('confidence')}"
                )
            customer_id = invoice.fields.get("CustomerId")
            if customer_id:
                print(
                    f"Customer Id: {customer_id.get('content')} has confidence: {customer_id.get('confidence')}"
                )
            customer_address = invoice.fields.get("CustomerAddress")
            if customer_address:
                print(
                    f"Customer Address: {customer_address.get('content')} has confidence: {customer_address.get('confidence')}"
                )
            customer_address_recipient = invoice.fields.get("CustomerAddressRecipient")
            if customer_address_recipient:
                print(
                    f"Customer Address Recipient: {customer_address_recipient.get('content')} has confidence: {customer_address_recipient.get('confidence')}"
                )
            invoice_id = invoice.fields.get("InvoiceId")
            if invoice_id:
                print(
                    f"Invoice Id: {invoice_id.get('content')} has confidence: {invoice_id.get('confidence')}"
                )
            invoice_date = invoice.fields.get("InvoiceDate")
            if invoice_date:
                print(
                    f"Invoice Date: {invoice_date.get('content')} has confidence: {invoice_date.get('confidence')}"
                )
            invoice_total = invoice.fields.get("InvoiceTotal")
            if invoice_total:
                print(
                    f"Invoice Total: {invoice_total.get('content')} has confidence: {invoice_total.get('confidence')}"
                )
            due_date = invoice.fields.get("DueDate")
            if due_date:
                print(
                    f"Due Date: {due_date.get('content')} has confidence: {due_date.get('confidence')}"
                )
            purchase_order = invoice.fields.get("PurchaseOrder")
            if purchase_order:
                print(
                    f"Purchase Order: {purchase_order.get('content')} has confidence: {purchase_order.get('confidence')}"
                )
            billing_address = invoice.fields.get("BillingAddress")
            if billing_address:
                print(
                    f"Billing Address: {billing_address.get('content')} has confidence: {billing_address.get('confidence')}"
                )
            billing_address_recipient = invoice.fields.get("BillingAddressRecipient")
            if billing_address_recipient:
                print(
                    f"Billing Address Recipient: {billing_address_recipient.get('content')} has confidence: {billing_address_recipient.get('confidence')}"
                )
            shipping_address = invoice.fields.get("ShippingAddress")
            if shipping_address:
                print(
                    f"Shipping Address: {shipping_address.get('content')} has confidence: {shipping_address.get('confidence')}"
                )
            shipping_address_recipient = invoice.fields.get("ShippingAddressRecipient")
            if shipping_address_recipient:
                print(
                    f"Shipping Address Recipient: {shipping_address_recipient.get('content')} has confidence: {shipping_address_recipient.get('confidence')}"
                )
            print("Invoice items:")
            for idx, item in enumerate(invoice.fields.get("Items").get("valueArray")):
                print(f"...Item #{idx + 1}")
                item_description = item.get("valueObject").get("Description")
                if item_description:
                    print(
                        f"......Description: {item_description.get('content')} has confidence: {item_description.get('confidence')}"
                    )
                item_quantity = item.get("valueObject").get("Quantity")
                if item_quantity:
                    print(
                        f"......Quantity: {item_quantity.get('content')} has confidence: {item_quantity.get('confidence')}"
                    )
                unit = item.get("valueObject").get("Unit")
                if unit:
                    print(
                        f"......Unit: {unit.get('content')} has confidence: {unit.get('confidence')}"
                    )
                unit_price = item.get("valueObject").get("UnitPrice")
                if unit_price:
                    unit_price_code = (
                        unit_price.get("valueCurrency").get("currencyCode")
                        if unit_price.get("valueCurrency").get("currencyCode")
                        else ""
                    )
                    print(
                        f"......Unit Price: {unit_price.get('content')}{unit_price_code} has confidence: {unit_price.get('confidence')}"
                    )
                product_code = item.get("valueObject").get("ProductCode")
                if product_code:
                    print(
                        f"......Product Code: {product_code.get('content')} has confidence: {product_code.get('confidence')}"
                    )
                item_date = item.get("valueObject").get("Date")
                if item_date:
                    print(
                        f"......Date: {item_date.get('content')} has confidence: {item_date.get('confidence')}"
                    )
                tax = item.get("valueObject").get("Tax")
                if tax:
                    print(
                        f"......Tax: {tax.get('content')} has confidence: {tax.get('confidence')}"
                    )
                amount = item.get("valueObject").get("Amount")
                if amount:
                    print(
                        f"......Amount: {amount.get('content')} has confidence: {amount.get('confidence')}"
                    )
            subtotal = invoice.fields.get("SubTotal")
            if subtotal:
                print(
                    f"Subtotal: {subtotal.get('content')} has confidence: {subtotal.get('confidence')}"
                )
            total_tax = invoice.fields.get("TotalTax")
            if total_tax:
                print(
                    f"Total Tax: {total_tax.get('content')} has confidence: {total_tax.get('confidence')}"
                )
            previous_unpaid_balance = invoice.fields.get("PreviousUnpaidBalance")
            if previous_unpaid_balance:
                print(
                    f"Previous Unpaid Balance: {previous_unpaid_balance.get('content')} has confidence: {previous_unpaid_balance.get('confidence')}"
                )
            amount_due = invoice.fields.get("AmountDue")
            if amount_due:
                print(
                    f"Amount Due: {amount_due.get('content')} has confidence: {amount_due.get('confidence')}"
                )
            service_start_date = invoice.fields.get("ServiceStartDate")
            if service_start_date:
                print(
                    f"Service Start Date: {service_start_date.get('content')} has confidence: {service_start_date.get('confidence')}"
                )
            service_end_date = invoice.fields.get("ServiceEndDate")
            if service_end_date:
                print(
                    f"Service End Date: {service_end_date.get('content')} has confidence: {service_end_date.get('confidence')}"
                )
            service_address = invoice.fields.get("ServiceAddress")
            if service_address:
                print(
                    f"Service Address: {service_address.get('content')} has confidence: {service_address.get('confidence')}"
                )
            service_address_recipient = invoice.fields.get("ServiceAddressRecipient")
            if service_address_recipient:
                print(
                    f"Service Address Recipient: {service_address_recipient.get('content')} has confidence: {service_address_recipient.get('confidence')}"
                )
            remittance_address = invoice.fields.get("RemittanceAddress")
            if remittance_address:
                print(
                    f"Remittance Address: {remittance_address.get('content')} has confidence: {remittance_address.get('confidence')}"
                )
            remittance_address_recipient = invoice.fields.get(
                "RemittanceAddressRecipient"
            )
            if remittance_address_recipient:
                print(
                    f"Remittance Address Recipient: {remittance_address_recipient.get('content')} has confidence: {remittance_address_recipient.get('confidence')}"
                )

            print("----------------------------------------")


if __name__ == "__main__":
    analyze_invoice()


アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. doc_intel_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python doc_intel_quickstart.py
    

URI で特定のファイルを分析するには、 begin_analyze_document_from_url メソッドを使用し、モデル ID として prebuilt-invoice を渡します。 返される値は、送信されたドキュメントに関するデータを含む result オブジェクトです。

form_recognizer_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。

# import libraries
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"


def format_bounding_region(bounding_regions):
    if not bounding_regions:
        return "N/A"
    return ", ".join(
        "Page #{}: {}".format(region.page_number, format_polygon(region.polygon))
        for region in bounding_regions
    )


def format_polygon(polygon):
    if not polygon:
        return "N/A"
    return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon])


def analyze_invoice():

    invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_analysis_client.begin_analyze_document_from_url(
        "prebuilt-invoice", invoiceUrl
    )
    invoices = poller.result()

    for idx, invoice in enumerate(invoices.documents):
        print("--------Recognizing invoice #{}--------".format(idx + 1))
        vendor_name = invoice.fields.get("VendorName")
        if vendor_name:
            print(
                "Vendor Name: {} has confidence: {}".format(
                    vendor_name.value, vendor_name.confidence
                )
            )
        vendor_address = invoice.fields.get("VendorAddress")
        if vendor_address:
            print(
                "Vendor Address: {} has confidence: {}".format(
                    vendor_address.value, vendor_address.confidence
                )
            )
        vendor_address_recipient = invoice.fields.get("VendorAddressRecipient")
        if vendor_address_recipient:
            print(
                "Vendor Address Recipient: {} has confidence: {}".format(
                    vendor_address_recipient.value, vendor_address_recipient.confidence
                )
            )
        customer_name = invoice.fields.get("CustomerName")
        if customer_name:
            print(
                "Customer Name: {} has confidence: {}".format(
                    customer_name.value, customer_name.confidence
                )
            )
        customer_id = invoice.fields.get("CustomerId")
        if customer_id:
            print(
                "Customer Id: {} has confidence: {}".format(
                    customer_id.value, customer_id.confidence
                )
            )
        customer_address = invoice.fields.get("CustomerAddress")
        if customer_address:
            print(
                "Customer Address: {} has confidence: {}".format(
                    customer_address.value, customer_address.confidence
                )
            )
        customer_address_recipient = invoice.fields.get("CustomerAddressRecipient")
        if customer_address_recipient:
            print(
                "Customer Address Recipient: {} has confidence: {}".format(
                    customer_address_recipient.value,
                    customer_address_recipient.confidence,
                )
            )
        invoice_id = invoice.fields.get("InvoiceId")
        if invoice_id:
            print(
                "Invoice Id: {} has confidence: {}".format(
                    invoice_id.value, invoice_id.confidence
                )
            )
        invoice_date = invoice.fields.get("InvoiceDate")
        if invoice_date:
            print(
                "Invoice Date: {} has confidence: {}".format(
                    invoice_date.value, invoice_date.confidence
                )
            )
        invoice_total = invoice.fields.get("InvoiceTotal")
        if invoice_total:
            print(
                "Invoice Total: {} has confidence: {}".format(
                    invoice_total.value, invoice_total.confidence
                )
            )
        due_date = invoice.fields.get("DueDate")
        if due_date:
            print(
                "Due Date: {} has confidence: {}".format(
                    due_date.value, due_date.confidence
                )
            )
        purchase_order = invoice.fields.get("PurchaseOrder")
        if purchase_order:
            print(
                "Purchase Order: {} has confidence: {}".format(
                    purchase_order.value, purchase_order.confidence
                )
            )
        billing_address = invoice.fields.get("BillingAddress")
        if billing_address:
            print(
                "Billing Address: {} has confidence: {}".format(
                    billing_address.value, billing_address.confidence
                )
            )
        billing_address_recipient = invoice.fields.get("BillingAddressRecipient")
        if billing_address_recipient:
            print(
                "Billing Address Recipient: {} has confidence: {}".format(
                    billing_address_recipient.value,
                    billing_address_recipient.confidence,
                )
            )
        shipping_address = invoice.fields.get("ShippingAddress")
        if shipping_address:
            print(
                "Shipping Address: {} has confidence: {}".format(
                    shipping_address.value, shipping_address.confidence
                )
            )
        shipping_address_recipient = invoice.fields.get("ShippingAddressRecipient")
        if shipping_address_recipient:
            print(
                "Shipping Address Recipient: {} has confidence: {}".format(
                    shipping_address_recipient.value,
                    shipping_address_recipient.confidence,
                )
            )
        print("Invoice items:")
        for idx, item in enumerate(invoice.fields.get("Items").value):
            print("...Item #{}".format(idx + 1))
            item_description = item.value.get("Description")
            if item_description:
                print(
                    "......Description: {} has confidence: {}".format(
                        item_description.value, item_description.confidence
                    )
                )
            item_quantity = item.value.get("Quantity")
            if item_quantity:
                print(
                    "......Quantity: {} has confidence: {}".format(
                        item_quantity.value, item_quantity.confidence
                    )
                )
            unit = item.value.get("Unit")
            if unit:
                print(
                    "......Unit: {} has confidence: {}".format(
                        unit.value, unit.confidence
                    )
                )
            unit_price = item.value.get("UnitPrice")
            if unit_price:
                print(
                    "......Unit Price: {} has confidence: {}".format(
                        unit_price.value, unit_price.confidence
                    )
                )
            product_code = item.value.get("ProductCode")
            if product_code:
                print(
                    "......Product Code: {} has confidence: {}".format(
                        product_code.value, product_code.confidence
                    )
                )
            item_date = item.value.get("Date")
            if item_date:
                print(
                    "......Date: {} has confidence: {}".format(
                        item_date.value, item_date.confidence
                    )
                )
            tax = item.value.get("Tax")
            if tax:
                print(
                    "......Tax: {} has confidence: {}".format(tax.value, tax.confidence)
                )
            amount = item.value.get("Amount")
            if amount:
                print(
                    "......Amount: {} has confidence: {}".format(
                        amount.value, amount.confidence
                    )
                )
        subtotal = invoice.fields.get("SubTotal")
        if subtotal:
            print(
                "Subtotal: {} has confidence: {}".format(
                    subtotal.value, subtotal.confidence
                )
            )
        total_tax = invoice.fields.get("TotalTax")
        if total_tax:
            print(
                "Total Tax: {} has confidence: {}".format(
                    total_tax.value, total_tax.confidence
                )
            )
        previous_unpaid_balance = invoice.fields.get("PreviousUnpaidBalance")
        if previous_unpaid_balance:
            print(
                "Previous Unpaid Balance: {} has confidence: {}".format(
                    previous_unpaid_balance.value, previous_unpaid_balance.confidence
                )
            )
        amount_due = invoice.fields.get("AmountDue")
        if amount_due:
            print(
                "Amount Due: {} has confidence: {}".format(
                    amount_due.value, amount_due.confidence
                )
            )
        service_start_date = invoice.fields.get("ServiceStartDate")
        if service_start_date:
            print(
                "Service Start Date: {} has confidence: {}".format(
                    service_start_date.value, service_start_date.confidence
                )
            )
        service_end_date = invoice.fields.get("ServiceEndDate")
        if service_end_date:
            print(
                "Service End Date: {} has confidence: {}".format(
                    service_end_date.value, service_end_date.confidence
                )
            )
        service_address = invoice.fields.get("ServiceAddress")
        if service_address:
            print(
                "Service Address: {} has confidence: {}".format(
                    service_address.value, service_address.confidence
                )
            )
        service_address_recipient = invoice.fields.get("ServiceAddressRecipient")
        if service_address_recipient:
            print(
                "Service Address Recipient: {} has confidence: {}".format(
                    service_address_recipient.value,
                    service_address_recipient.confidence,
                )
            )
        remittance_address = invoice.fields.get("RemittanceAddress")
        if remittance_address:
            print(
                "Remittance Address: {} has confidence: {}".format(
                    remittance_address.value, remittance_address.confidence
                )
            )
        remittance_address_recipient = invoice.fields.get("RemittanceAddressRecipient")
        if remittance_address_recipient:
            print(
                "Remittance Address Recipient: {} has confidence: {}".format(
                    remittance_address_recipient.value,
                    remittance_address_recipient.confidence,
                )
            )

        print("----------------------------------------")

if __name__ == "__main__":
    analyze_invoice()


アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. form_recognizer_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python form_recognizer_quickstart.py
    

事前構築済みモデルの出力

予想される出力のスニペットを次に示します。

  --------Recognizing invoice #1--------
  Vendor Name: CONTOSO LTD. has confidence: 0.919
  Vendor Address: 123 456th St New York, NY, 10001 has confidence: 0.907
  Vendor Address Recipient: Contoso Headquarters has confidence: 0.919
  Customer Name: MICROSOFT CORPORATION has confidence: 0.84
  Customer Id: CID-12345 has confidence: 0.956
  Customer Address: 123 Other St, Redmond WA, 98052 has confidence: 0.909
  Customer Address Recipient: Microsoft Corp has confidence: 0.917
  Invoice Id: INV-100 has confidence: 0.972
  Invoice Date: 2019-11-15 has confidence: 0.971
  Invoice Total: CurrencyValue(amount=110.0, symbol=$) has confidence: 0.97
  Due Date: 2019-12-15 has confidence: 0.973

出力全体を表示するには、GitHubのAzureサンプル リポジトリにアクセスして、事前構築済みの請求書モデルの出力を表示します。

form_recognizer_quickstart.py アプリケーションに次のコード サンプルを追加します。 Azure ポータルの Form Recognizer インスタンスの値を使用して、キーとエンドポイントの変数を更新してください。


# import libraries
import os
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

# set `<your-endpoint>` and `<your-key>` variables with the values from the Azure portal
endpoint = "<your-endpoint>"
key = "<your-key>"


def format_polygon(polygon):
    if not polygon:
        return "N/A"
    return ", ".join(["[{}, {}]".format(p.x, p.y) for p in polygon])


def analyze_layout():
    # sample document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = document_analysis_client.begin_analyze_document_from_url(
        "prebuilt-layout", formUrl
    )
    result = poller.result()

    for idx, style in enumerate(result.styles):
        print(
            "Document contains {} content".format(
                "handwritten" if style.is_handwritten else "no handwritten"
            )
        )


for page in result.pages:
    print("----Analyzing layout from page #{}----".format(page.page_number))
    print(
        "Page has width: {} and height: {}, measured with unit: {}".format(
            page.width, page.height, page.unit
        )
    )

    for line_idx, line in enumerate(page.lines):
        words = line.get_words()
        print(
            "...Line # {} has word count {} and text '{}' within bounding polygon '{}'".format(
                line_idx,
                len(words),
                line.content,
                format_polygon(line.polygon),
            )
        )

        for word in words:
            print(
                "......Word '{}' has a confidence of {}".format(
                    word.content, word.confidence
                )
            )

    for selection_mark in page.selection_marks:
        print(
            "...Selection mark is '{}' within bounding polygon '{}' and has a confidence of {}".format(
                selection_mark.state,
                format_polygon(selection_mark.polygon),
                selection_mark.confidence,
            )
        )

for table_idx, table in enumerate(result.tables):
    print(
        "Table # {} has {} rows and {} columns".format(
            table_idx, table.row_count, table.column_count
        )
    )
    for region in table.bounding_regions:
        print(
            "Table # {} location on page: {} is {}".format(
                table_idx,
                region.page_number,
                format_polygon(region.polygon),
            )
        )
    for cell in table.cells:
        print(
            "...Cell[{}][{}] has content '{}'".format(
                cell.row_index,
                cell.column_index,
                cell.content,
            )
        )
        for region in cell.bounding_regions:
            print(
                "...content on page {} is within bounding polygon '{}'".format(
                    region.page_number,
                    format_polygon(region.polygon),
                )
            )

print("----------------------------------------")


if __name__ == "__main__":
    analyze_layout()


アプリケーションを実行する

アプリケーションにコード サンプルを追加したら、プログラムをビルドして実行します。

  1. form_recognizer_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

    python form_recognizer_quickstart.py
    

このクイック スタートでは、ドキュメント インテリジェンス REST API を使用して、ドキュメントのデータと値を分析および抽出する方法について説明します。

前提 条件

  • Azure サブスクリプション - 無料で作成します

  • cURL コマンド ライン ツールがインストールされています。

  • PowerShell バージョン 7.*+ (または同様のコマンド ライン アプリケーション)。

  • PowerShell のバージョンを確認するには、オペレーティング システムに対して次のコマンドを入力します。

    • Windows: Get-Host | Select-Object Version
    • macOS または Linux: $PSVersionTable
  • ドキュメント インテリジェンス (単一サービス) または Foundry Tools (マルチサービス) リソース。 Azure サブスクリプションを取得したら、Azure ポータルで single-service または multi-service Document Intelligence リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

ヒント

1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする予定の場合は、Microsoft Foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra 認証を使用する場合は、単一サービス リソースが必要です。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

ドキュメントを分析して結果を取得する

POST 要求は、事前構築済みモデルまたはカスタム モデルを使用してドキュメントを分析するために使用されます。 GET 要求は、ドキュメント分析呼び出しの結果を取得するために使用されます。 modelIdは POST と GET 操作でresultIdで使用されます。

ドキュメントを分析する (POST 要求)

cURL コマンドを実行する前に、 post 要求に次の変更を加えます。

  1. {endpoint} を、Azure ポータルのドキュメント インテリジェンス インスタンスのエンドポイント値に置き換えます。

  2. {key} を、Azure ポータルのドキュメント インテリジェンス インスタンスのキー値に置き換えます。

  3. 次の表を参照として使用して、 {modelID}{your-document-url} を目的の値に置き換えます。

  4. URL にドキュメント ファイルが必要です。 このクイック スタートでは、機能ごとに次の表に示すサンプル フォームを使用できます。

サンプル ドキュメント

機能 {modelID} {your-document-url}
読む prebuilt-read https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png
レイアウト prebuilt-layout https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/layout.png
健康保険証 prebuilt-healthInsuranceCard.us https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/insurance-card.png
W-2 prebuilt-tax.us.w2 https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/w2.png
請求 書 prebuilt-invoice https://github.com/Azure-Samples/cognitive-services-REST-api-samples/raw/master/curl/form-recognizer/rest-api/invoice.pdf
領収 書 prebuilt-receipt https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/receipt.png
ID文書 prebuilt-idDocument https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/identity_documents.png

サンプル ドキュメント

機能 {modelID} {your-document-url}
一般的なドキュメント prebuilt-document https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf
読む prebuilt-read https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/read.png
レイアウト prebuilt-layout https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/layout.png
健康保険証 prebuilt-healthInsuranceCard.us https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/insurance-card.png
W-2 prebuilt-tax.us.w2 https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/w2.png
請求 書 prebuilt-invoice https://github.com/Azure-Samples/cognitive-services-REST-api-samples/raw/master/curl/form-recognizer/rest-api/invoice.pdf
領収 書 prebuilt-receipt https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/receipt.png
ID文書 prebuilt-idDocument https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/rest-api/identity_documents.png
名刺 prebuilt-businessCard https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/de5e0d8982ab754823c54de47a47e8e499351523/curl/form-recognizer/rest-api/business_card.jpg

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、「Foundry Tools のセキュリティ」を参照してください

POST リクエスト要求

curl -v -i -X POST "{endpoint}/documentintelligence/documentModels/{modelId}:analyze?api-version=2024-11-30" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {key}" --data-ascii "{'urlSource': '{your-document-url}'}"
curl -v -i POST "{endpoint}/formrecognizer/documentModels/{modelID}:analyze?api-version=2023-07-31" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {key}" --data-ascii "{'urlSource': '{your-document-url}'}"
curl -v -i POST "{endpoint}/formrecognizer/documentModels/{modelId}:analyze?api-version=2022-08-31" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {key}" --data-ascii "{'urlSource': '{your-document-url}'}"

POST 応答 (resultID)

読み取り専用のOperation-Location ヘッダーを含む202 (Success)応答を受け取ります。 このヘッダーの値には、クエリを実行して非同期操作の状態を取得し、同じリソース サブスクリプション キーを持つ GET 要求を使用して結果を取得できる resultID が含まれています。

{alt-text}

分析結果を取得する (GET 要求)

Analyze document API を呼び出した後、Get analyze result API を呼び出して、操作の状態と抽出されたデータを取得します。 コマンドを実行する前に、次の変更を行います。

Analyze document API を呼び出した後、Get analyze result API を呼び出して、操作の状態と抽出されたデータを取得します。 コマンドを実行する前に、次の変更を行います。

Analyze document API を呼び出した後、Get analyze result API を呼び出して、操作の状態と抽出されたデータを取得します。 コマンドを実行する前に、次の変更を行います。

  1. {resultID} Operation-Locationヘッダーを置き換えます。

  2. {key} を、Azure ポータルのドキュメント インテリジェンス インスタンスのキー値に置き換えます。

GET リクエスト

curl -v -X GET "{endpoint}/documentintelligence/documentModels/{modelId}/analyzeResults/{resultId}?api-version=2024-11-30" -H "Ocp-Apim-Subscription-Key: {key}"
curl -v -X GET "{endpoint}/formrecognizer/documentModels/{modelId}/analyzeResults/{resultId}?api-version=2023-07-31" -H "Ocp-Apim-Subscription-Key: {key}"

curl -v -X GET "{endpoint}/formrecognizer/documentModels/{modelId}/analyzeResults/{resultId}?api-version=2022-08-31" -H "Ocp-Apim-Subscription-Key: {key}"

応答を調べる

JSON 出力で 200 (Success) 応答を受け取ります。 最初のフィールド "status"は、操作の状態を示します。 操作が完了していない場合、 "status" の値は "running" または "notStarted"され、手動またはスクリプトを使用して API を再度呼び出す必要があります。 呼び出しの間隔は 1 秒以上することをお勧めします。

事前構築済みの請求書の応答のサンプル

{
    "status": "succeeded",
    "createdDateTime": "2024-03-25T19:31:37Z",
    "lastUpdatedDateTime": "2024-03-25T19:31:43Z",
    "analyzeResult": {
        "apiVersion": "2024-11-30",
        "modelId": "prebuilt-invoice",
        "stringIndexType": "textElements"...
    ..."pages": [
            {
                "pageNumber": 1,
                "angle": 0,
                "width": 8.5,
                "height": 11,
                "unit": "inch",
                "words": [
                    {
                        "content": "CONTOSO",
                        "boundingBox": [
                            0.5911,
                            0.6857,
                            1.7451,
                            0.6857,
                            1.7451,
                            0.8664,
                            0.5911,
                            0.8664
                        ],
                        "confidence": 1,
                        "span": {
                            "offset": 0,
                            "length": 7
                                }
                      }],
              }]
      }
}
{
    "status": "succeeded",
    "createdDateTime": "2023-08-25T19:31:37Z",
    "lastUpdatedDateTime": "2023-08-25T19:31:43Z",
    "analyzeResult": {
        "apiVersion": "2023-07-31",
        "modelId": "prebuilt-invoice",
        "stringIndexType": "textElements"...
    ..."pages": [
            {
                "pageNumber": 1,
                "angle": 0,
                "width": 8.5,
                "height": 11,
                "unit": "inch",
                "words": [
                    {
                        "content": "CONTOSO",
                        "boundingBox": [
                            0.5911,
                            0.6857,
                            1.7451,
                            0.6857,
                            1.7451,
                            0.8664,
                            0.5911,
                            0.8664
                        ],
                        "confidence": 1,
                        "span": {
                            "offset": 0,
                            "length": 7
                                }
                      }],
              }]
      }
}
{
    "status": "succeeded",
    "createdDateTime": "2022-09-25T19:31:37Z",
    "lastUpdatedDateTime": "2022-09-25T19:31:43Z",
    "analyzeResult": {
        "apiVersion": "2022-08-31",
        "modelId": "prebuilt-invoice",
        "stringIndexType": "textElements"...
    ..."pages": [
            {
                "pageNumber": 1,
                "angle": 0,
                "width": 8.5,
                "height": 11,
                "unit": "inch",
                "words": [
                    {
                        "content": "CONTOSO",
                        "boundingBox": [
                            0.5911,
                            0.6857,
                            1.7451,
                            0.6857,
                            1.7451,
                            0.8664,
                            0.5911,
                            0.8664
                        ],
                        "confidence": 1,
                        "span": {
                            "offset": 0,
                            "length": 7
                                }
                      }],
              }]
      }
}

サポートされているドキュメント フィールド

事前構築済みモデルでは、ドキュメント フィールドの定義済みセットが抽出されます。 抽出されたフィールド名、型、説明、例については、「 モデル データの抽出 」を参照してください。

これで完了です。おめでとうございます。

このクイック スタートでは、ドキュメント インテリジェンス モデルを使用して、さまざまなフォームとドキュメントを分析しました。 次に、Document Intelligence Studio とリファレンス ドキュメントを調べて、ドキュメント インテリジェンス API について詳しく学習します。

次の手順

  • GitHubでさらにサンプルを見つけられます。
  • GitHubでさらにサンプルを見つけられます。

このコンテンツの適用対象:red-checkmarkv2.1 | Latest version:blue-checkmarkv4.0 (GA)

任意のプログラミング言語または REST API を使用して、Azureドキュメント インテリジェンスの使用を開始します。 ドキュメント インテリジェンスは、機械学習を使用してドキュメントからキーと値のペア、テキスト、テーブルを抽出するクラウドベースの Foundry Tools サービスです。 テクノロジを学習するときは、無料サービスを使用することをお勧めします。 無料ページの数は 1 か月あたり 500 ページに制限されていることに注意してください。

ドキュメント インテリジェンスの機能と開発オプションの詳細については、 概要 ページを参照してください。

Reference documentation | Library source code | Package (NuGet) | Samples

このクイック スタートでは、次の API を使用して、フォームとドキュメントから構造化データを抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • Visual Studio IDEの現在のバージョン。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを作成したら、Azure ポータルで single-service または multi-service ドキュメント インテリジェンス リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする場合は、foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra認証を使用する場合は、単一サービス リソースが必要であることに注意してください。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

  1. 2019 Visual Studio開始します。

  2. スタート ページで、[新しいプロジェクトの作成] を選択します。

    Visual Studio開始ウィンドウのスクリーンショット.

  3. [ 新しいプロジェクトの作成] ページで、検索ボックスに コンソール を入力します。 コンソール アプリケーション テンプレートを選択し、[次へ] を選択します。

    新しいプロジェクト ページの作成Visual Studioのスクリーンショット。

  4. 新しいプロジェクトの構成 ダイアログ ウィンドウで、「プロジェクト名」ボックスに「formRecognizer_quickstart」と入力します。 次に、[次へ] を選択します。

    Visual Studios の [新しいプロジェクトの構成] ダイアログ ウィンドウのスクリーンショット。

  5. 追加情報 ダイアログ ウィンドウで、.NET 5.0 (Current) を選択し、Create を選択します。

    Visual Studio追加情報ダイアログ ウィンドウのスクリーンショット.

NuGet を使用してクライアント ライブラリをインストールする

  1. formRecognizer_quickstart プロジェクトを右クリックし、[NuGet パッケージの管理...] を選択します。

    [NuGet パッケージの選択] ウィンドウを示すスクリーンショット。

  2. [ブラウズ] タブを選択し、Azure.AI.FormRecognizer と入力します。

    [ドキュメント インテリジェンス パッケージ] ドロップダウン メニューを示すスクリーンショット。

  3. ドロップダウン メニューからバージョン 3.1.1 を選択し、[ インストール] を選択します。

アプリケーションをビルドする

ドキュメント インテリジェンス サービスと対話するには、 FormRecognizerClient クラスのインスタンスを作成する必要があります。 これを行うには、キーを使用してAzureKeyCredentialを作成し、FormRecognizerClientとドキュメント インテリジェンス AzureKeyCredentialを使用してendpoint インスタンスを作成します。

メモ

  • .NET 6 以降では、console テンプレートを使用する新しいプロジェクトによって、以前のバージョンとは異なる新しいプログラム スタイルが生成されます。
  • 新しい出力では、記述する必要があるコードを簡略化する最近の C# 機能が使用されます。
  • 新しいバージョンを使用する場合は、 Main メソッドの本体を記述するだけで済みます。 最上位レベルのステートメント、グローバル using ディレクティブ、または暗黙的な using ディレクティブを含める必要はありません。
  • 詳細については、「新しい C# テンプレートで最上位レベルのステートメントを生成する」参照してください
  1. Program.cs ファイルを開きます。

  2. 次の using ディレクティブを含めてください。

using Azure;
using Azure.AI.FormRecognizer;
using Azure.AI.FormRecognizer.Models;
using System.Threading.Tasks;
  1. endpointkey環境変数を設定し、AzureKeyCredentialFormRecognizerClientインスタンスを作成します。
private static readonly string endpoint = "your-form-recognizer-endpoint";
private static readonly string key = "your-api-key";
private static readonly AzureKeyCredential credential = new AzureKeyCredential(key);
  1. Console.Writeline("Hello World!"); を削除し、Try It コード サンプルのいずれかを Program.cs ファイルに追加します。

    Main メソッドにサンプル コードを追加するスクリーンショット。

  2. コード サンプルを選択して、アプリケーションの Main メソッドにコピーして貼り付けます。

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、Foundry Tools の セキュリティ に関する記事を参照してください。

試してみる: レイアウト モデル

文書から境界領域座標と共に、テキスト、選択マーク、テキスト スタイル、およびテーブル構造を抽出します。

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • formUri変数にファイル URI 値を追加しました。
  • URI で特定のファイルからレイアウトを抽出するには、 StartRecognizeContentFromUriAsync メソッドを使用します。

レイアウト アプリケーションのProgram.cs ファイルに次のコードを追加します。


FormRecognizerClient recognizerClient = AuthenticateClient();

Task recognizeContent = RecognizeContent(recognizerClient);
Task.WaitAll(recognizeContent);

private static FormRecognizerClient AuthenticateClient()
            {
                var credential = new AzureKeyCredential(key);
                var client = new FormRecognizerClient(new Uri(endpoint), credential);
                return client;
            }

            private static async Task RecognizeContent(FormRecognizerClient recognizerClient)
        {
            string formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";
            FormPageCollection formPages = await recognizerClient
        .StartRecognizeContentFromUri(new Uri(formUrl))
        .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}'.");
                    }
                }
            }
        }
    }
}

試してみる: 事前構築済みモデル

このサンプルでは、請求書を例として使用して、事前トレーニング済みのモデルを使用して、特定の種類の一般的なドキュメントのデータを分析する方法を示します。

  • この例では、事前構築済みのモデルを使用して請求書ドキュメントを分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • Main メソッドの上部にある invoiceUri 変数にファイル URI 値を追加しました。
  • URI で特定のファイルを分析するには、 StartRecognizeInvoicesFromUriAsync メソッドを使用します。
  • わかりやすくするために、サービスから返されるすべてのフィールドはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

事前構築済みモデルを選択する

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 分析操作に使用するモデルは、分析するドキュメントの種類によって異なります。 ドキュメント インテリジェンス サービスで現在サポートされている事前構築済みモデルを次に示します。

  • 請求書: 請求書からテキスト、選択マーク、テーブル、フィールド、およびキー情報を抽出します。
  • レシート: レシートからテキストとキー情報を抽出します。
  • ID ドキュメント: 運転免許証と国際パスポートからテキストとキー情報を抽出します。
  • 名刺: 名刺からテキストとキー情報を抽出します。

事前構築済みの請求書アプリケーション Program.cs ファイルメソッドに次のコードを追加します

FormRecognizerClient recognizerClient = AuthenticateClient();

  Task analyzeinvoice = AnalyzeInvoice(recognizerClient, invoiceUrl);
  Task.WaitAll(analyzeinvoice);

   private static FormRecognizerClient AuthenticateClient() {
     var credential = new AzureKeyCredential(key);
     var client = new FormRecognizerClient(new Uri(endpoint), credential);
     return client;
   }

   static string invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

   private static async Task AnalyzeInvoice(FormRecognizerClient recognizerClient, string invoiceUrl) {
     var options = new RecognizeInvoicesOptions() {
       Locale = "en-US"
     };
     RecognizedFormCollection invoices = await recognizerClient.StartRecognizeInvoicesFromUriAsync(new Uri(invoiceUrl), options).WaitForCompletionAsync();

     RecognizedForm invoice = invoices[0];

     FormField invoiceIdField;
     if (invoice.Fields.TryGetValue("InvoiceId", out invoiceIdField)) {
       if (invoiceIdField.Value.ValueType == FieldValueType.String) {
         string invoiceId = invoiceIdField.Value.AsString();
         Console.WriteLine($"    Invoice Id: '{invoiceId}', with confidence {invoiceIdField.Confidence}");
       }
     }

     FormField invoiceDateField;
     if (invoice.Fields.TryGetValue("InvoiceDate", out invoiceDateField)) {
       if (invoiceDateField.Value.ValueType == FieldValueType.Date) {
         DateTime invoiceDate = invoiceDateField.Value.AsDate();
         Console.WriteLine($"    Invoice Date: '{invoiceDate}', with confidence {invoiceDateField.Confidence}");
       }
     }

     FormField dueDateField;
     if (invoice.Fields.TryGetValue("DueDate", out dueDateField)) {
       if (dueDateField.Value.ValueType == FieldValueType.Date) {
         DateTime dueDate = dueDateField.Value.AsDate();
         Console.WriteLine($"    Due Date: '{dueDate}', with confidence {dueDateField.Confidence}");
       }
     }

     FormField vendorNameField;
     if (invoice.Fields.TryGetValue("VendorName", out vendorNameField)) {
       if (vendorNameField.Value.ValueType == FieldValueType.String) {
         string vendorName = vendorNameField.Value.AsString();
         Console.WriteLine($"    Vendor Name: '{vendorName}', with confidence {vendorNameField.Confidence}");
       }
     }

     FormField vendorAddressField;
     if (invoice.Fields.TryGetValue("VendorAddress", out vendorAddressField)) {
       if (vendorAddressField.Value.ValueType == FieldValueType.String) {
         string vendorAddress = vendorAddressField.Value.AsString();
         Console.WriteLine($"    Vendor Address: '{vendorAddress}', with confidence {vendorAddressField.Confidence}");
       }
     }

     FormField customerNameField;
     if (invoice.Fields.TryGetValue("CustomerName", out customerNameField)) {
       if (customerNameField.Value.ValueType == FieldValueType.String) {
         string customerName = customerNameField.Value.AsString();
         Console.WriteLine($"    Customer Name: '{customerName}', with confidence {customerNameField.Confidence}");
       }
     }

     FormField customerAddressField;
     if (invoice.Fields.TryGetValue("CustomerAddress", out customerAddressField)) {
       if (customerAddressField.Value.ValueType == FieldValueType.String) {
         string customerAddress = customerAddressField.Value.AsString();
         Console.WriteLine($"    Customer Address: '{customerAddress}', with confidence {customerAddressField.Confidence}");
       }
     }

     FormField customerAddressRecipientField;
     if (invoice.Fields.TryGetValue("CustomerAddressRecipient", out customerAddressRecipientField)) {
       if (customerAddressRecipientField.Value.ValueType == FieldValueType.String) {
         string customerAddressRecipient = customerAddressRecipientField.Value.AsString();
         Console.WriteLine($"    Customer address recipient: '{customerAddressRecipient}', with confidence {customerAddressRecipientField.Confidence}");
       }
     }

     FormField invoiceTotalField;
     if (invoice.Fields.TryGetValue("InvoiceTotal", out invoiceTotalField)) {
       if (invoiceTotalField.Value.ValueType == FieldValueType.Float) {
         float invoiceTotal = invoiceTotalField.Value.AsFloat();
         Console.WriteLine($"    Invoice Total: '{invoiceTotal}', with confidence {invoiceTotalField.Confidence}");
       }
     }
   }
 }
}

アプリケーションを実行する

formRecognizer_quickstartの横にある緑色の [スタート] ボタンを選択してプログラムをビルドして実行するか、 F5 キーを押します。

Visual Studio プログラムを実行している画面のスクリーンショット。

Reference documentation | Library source code | Package (Maven) | Samples

このクイック スタートでは、次の API を使用して、フォームとドキュメントから構造化データを抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • Java Development Kit (JDK) バージョン 8 以降。 詳細については、seeサポートされているJavaバージョンと更新スケジュール

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを作成したら、Azure ポータルで single-service または multi-service ドキュメント インテリジェンス リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

新しい Gradle プロジェクトを作成する

コンソール ウィンドウ (cmd、PowerShell、Bash など) で、 form-recognizer-app という名前のアプリ用の新しいディレクトリを作成し、そこに移動します。

mkdir form-recognizer-app && form-recognizer-app
  1. 作業ディレクトリから gradle init コマンドを実行します。 このコマンドは、実行時にアプリケーションの作成と構成に使用される build.gradle.kts など、Gradle に不可欠なビルド ファイルを作成します。

    gradle init --type basic
    
  2. DSL の選択を求められたら、[Kotlin] を選択します。

  3. 既定のプロジェクト名をそのまま使用する (form-recognizer-app)

クライアント ライブラリをインストールする

このクイック スタートでは、Gradle 依存関係マネージャーを使用します。 Maven Central Repository では、クライアント ライブラリと他の依存関係マネージャーの情報を確認できます。

プロジェクトの build.gradle.kts ファイルに、必要なプラグインと設定と共に、 implementation ステートメントとしてクライアント ライブラリを含めます。

plugins {
    java
    application
}
application {
    mainClass.set("FormRecognizer")
}
repositories {
    mavenCentral()
}
dependencies {
    implementation(group = "com.azure", name = "azure-ai-formrecognizer", version = "3.1.1")
}

Java ファイルを作成する

作業ディレクトリから、次のコマンドを実行します。

mkdir -p src/main/java

次のディレクトリ構造を作成します。

アプリケーションのJavaディレクトリ構造のスクリーンショット。

Java ディレクトリに移動し、FormRecognizer.java という名前のファイルを作成します。。 任意のエディターまたは IDE で開き、次のパッケージ宣言と import ステートメントを追加します。

import com.azure.ai.formrecognizer.*;
import com.azure.ai.formrecognizer.models.*;

import java.util.concurrent.atomic.AtomicReference;
import java.util.List;
import java.util.Map;
import java.time.LocalDate;

import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.util.Context;
import com.azure.core.util.polling.SyncPoller;

コード サンプルを選択して、アプリケーションの main メソッドにコピーして貼り付けます。

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、「Foundry Tools のセキュリティ」を参照してください

試してみる: レイアウト モデル

文書から境界領域座標と共に、テキスト、選択マーク、テキスト スタイル、およびテーブル構造を抽出します。

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • URI で特定のファイルを分析するには、 beginRecognizeContentFromUrl メソッドを使用します。
  • main メソッドの formUrl 変数にファイル URI 値を追加しました。

アプリケーションの FormRecognizer クラスを次のコードで更新します (Azure ポータルのドキュメント インテリジェンス インスタンスの値でキーとエンドポイント変数を更新してください)。


static final String key = "PASTE_YOUR_FORM_RECOGNIZER_KEY_HERE";
static final String endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";

public static void main(String[] args) {FormRecognizerClient recognizerClient = new FormRecognizerClientBuilder()
                .credential(new AzureKeyCredential(key)).endpoint(endpoint).buildClient();

    String formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf";

    System.out.println("Get form content...");
        GetContent(recognizerClient, formUrl);
  }
    private static void GetContent(FormRecognizerClient recognizerClient, String invoiceUri) {
        String analyzeFilePath = invoiceUri;
        SyncPoller<FormRecognizerOperationResult, List<FormPage>> recognizeContentPoller = recognizerClient
                .beginRecognizeContentFromUrl(analyzeFilePath);

        List<FormPage> contentResult = recognizeContentPoller.getFinalResult();
        // </snippet_getcontent_call>
        // <snippet_getcontent_print>
        contentResult.forEach(formPage -> {
            // Table information
            System.out.println("----Recognizing content ----");
            System.out.printf("Has width: %f and height: %f, measured with unit: %s.%n", formPage.getWidth(),
                    formPage.getHeight(), formPage.getUnit());
            formPage.getTables().forEach(formTable -> {
                System.out.printf("Table has %d rows and %d columns.%n", formTable.getRowCount(),
                        formTable.getColumnCount());
                formTable.getCells().forEach(formTableCell -> {
                    System.out.printf("Cell has text %s.%n", formTableCell.getText());
                });
                System.out.println();
            });
        });
    }

試してみる: 事前構築済みモデル

このサンプルでは、請求書を例として使用して、事前トレーニング済みのモデルを使用して、特定の種類の一般的なドキュメントのデータを分析する方法を示します。

  • この例では、事前構築済みのモデルを使用して請求書ドキュメントを分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • URI で特定のファイルを分析するには、 beginRecognizeInvoicesFromUrl を使用します。
  • main メソッドの invoiceUrl 変数にファイル URI 値を追加しました。
  • わかりやすくするために、サービスから返されるすべてのフィールドはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

事前構築済みモデルを選択する

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 ドキュメント インテリジェンス サービスで現在サポートされている事前構築済みモデルを次に示します。

  • 請求書: 請求書からテキスト、選択マーク、テーブル、フィールド、およびキー情報を抽出します。
  • レシート: レシートからテキストとキー情報を抽出します。
  • ID ドキュメント: 運転免許証と国際パスポートからテキストとキー情報を抽出します。
  • 名刺: 名刺からテキストとキー情報を抽出します。

アプリケーションの FormRecognizer クラスを次のコードで更新します (Azure ポータルのドキュメント インテリジェンス インスタンスの値でキーとエンドポイント変数を更新してください)。


static final String key = "PASTE_YOUR_FORM_RECOGNIZER_KEY_HERE";
static final String endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";

public static void main(String[] args) {
    FormRecognizerClient recognizerClient = new FormRecognizerClientBuilder().credential(new AzureKeyCredential(key)).endpoint(endpoint).buildClient();

    String invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

    System.out.println("Analyze invoice...");
        AnalyzeInvoice(recognizerClient, invoiceUrl);
  }
    private static void AnalyzeInvoice(FormRecognizerClient recognizerClient, String invoiceUrl) {
      SyncPoller < FormRecognizerOperationResult,
        List < RecognizedForm >> recognizeInvoicesPoller = recognizerClient.beginRecognizeInvoicesFromUrl(invoiceUrl);
      List < RecognizedForm > recognizedInvoices = recognizeInvoicesPoller.getFinalResult();

      for (int i = 0; i < recognizedInvoices.size(); i++) {
        RecognizedForm recognizedInvoice = recognizedInvoices.get(i);
        Map < String,
        FormField > recognizedFields = recognizedInvoice.getFields();
        System.out.printf("----------- Recognized invoice info for page %d -----------%n", i);
        FormField vendorNameField = recognizedFields.get("VendorName");
        if (vendorNameField != null) {
            if (FieldValueType.STRING == vendorNameField.getValue().getValueType()) {
                String merchantName = vendorNameField.getValue().asString();
                System.out.printf("Vendor Name: %s, confidence: %.2f%n", merchantName, vendorNameField.getConfidence());
            }
        }

        FormField vendorAddressField = recognizedFields.get("VendorAddress");
        if (vendorAddressField != null) {
            if (FieldValueType.STRING == vendorAddressField.getValue().getValueType()) {
                String merchantAddress = vendorAddressField.getValue().asString();
                System.out.printf("Vendor address: %s, confidence: %.2f%n", merchantAddress, vendorAddressField.getConfidence());
            }
        }

        FormField customerNameField = recognizedFields.get("CustomerName");
        if (customerNameField != null) {
            if (FieldValueType.STRING == customerNameField.getValue().getValueType()) {
                String merchantAddress = customerNameField.getValue().asString();
                System.out.printf("Customer Name: %s, confidence: %.2f%n", merchantAddress, customerNameField.getConfidence());
            }
        }

        FormField customerAddressRecipientField = recognizedFields.get("CustomerAddressRecipient");
        if (customerAddressRecipientField != null) {
            if (FieldValueType.STRING == customerAddressRecipientField.getValue().getValueType()) {
                String customerAddr = customerAddressRecipientField.getValue().asString();
                System.out.printf("Customer Address Recipient: %s, confidence: %.2f%n", customerAddr, customerAddressRecipientField.getConfidence());
            }
        }

        FormField invoiceIdField = recognizedFields.get("InvoiceId");
        if (invoiceIdField != null) {
            if (FieldValueType.STRING == invoiceIdField.getValue().getValueType()) {
                String invoiceId = invoiceIdField.getValue().asString();
                System.out.printf("Invoice Id: %s, confidence: %.2f%n", invoiceId, invoiceIdField.getConfidence());
            }
        }

        FormField invoiceDateField = recognizedFields.get("InvoiceDate");
        if (customerNameField != null) {
            if (FieldValueType.DATE == invoiceDateField.getValue().getValueType()) {
                LocalDate invoiceDate = invoiceDateField.getValue().asDate();
                System.out.printf("Invoice Date: %s, confidence: %.2f%n", invoiceDate, invoiceDateField.getConfidence());
            }
        }

        FormField invoiceTotalField = recognizedFields.get("InvoiceTotal");
        if (customerAddressRecipientField != null) {
            if (FieldValueType.FLOAT == invoiceTotalField.getValue().getValueType()) {
                Float invoiceTotal = invoiceTotalField.getValue().asFloat();
                System.out.printf("Invoice Total: %.2f, confidence: %.2f%n", invoiceTotal, invoiceTotalField.getConfidence());
            }
        }
    }
}

アプリケーションをビルドして実行する

メイン プロジェクト ディレクトリ (form-recognizer-app) に戻ります。

  1. build コマンドを使用してアプリケーションをビルドします。
gradle build
  1. run コマンドを使用してアプリケーションを実行します。
gradle run

Reference documentation | Library source code | Package (npm) | Samples

このクイック スタートでは、次の API を使用して、フォームとドキュメントから構造化データを抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成

  • 最新バージョンの Visual Studio Code または任意の IDE。

  • Node.jsの最新のLTS バージョン

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを作成したら、Azure ポータルで single-service または multi-service ドキュメント インテリジェンス リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする場合は、foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra認証を使用する場合は、単一サービス リソースが必要であることに注意してください。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

  1. 新しい Node.js アプリケーションを作成します。 コンソール ウィンドウ (cmd、PowerShell、Bash など) で、アプリ用の新しいディレクトリを作成し、そこに移動します。

    mkdir form-recognizer-app && cd form-recognizer-app
    
  2. npm init コマンドを実行して、package.json ファイルを含むノード アプリケーションを作成します。

    npm init
    
  3. ai-form-recognizer クライアント ライブラリ npm パッケージをインストールします。

    npm install @azure/ai-form-recognizer
    

    アプリの package.json ファイルが依存関係で更新されます。

  4. index.jsという名前のファイルを作成して開き、次のライブラリをインポートします。

    const { FormRecognizerClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");
    
  5. リソースのAzure エンドポイントとキーの変数を作成します。

    const key = "PASTE_YOUR_FORM_RECOGNIZER_KEY_HERE";
    const endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";
    
  6. この時点で、JavaScript アプリケーションには次のコード行が含まれている必要があります。

    
    const { FormRecognizerClient, AzureKeyCredential } = require("@azure/ai-form-recognizer");
    
    const endpoint = "PASTE_YOUR_FORM_RECOGNIZER_ENDPOINT_HERE";
    const key = "PASTE_YOUR_FORM_RECOGNIZER_KEY_HERE";
    

アプリケーションにコピーして貼り付けるコード サンプルを選択します。

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、「Foundry Tools のセキュリティ」を参照してください

試してみる: レイアウト モデル

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • ファイルの URI 値を、ファイルの先頭付近の formUrl 変数に追加しました。
  • URI で特定のファイルを分析するには、 beginRecognizeContent メソッドを使用します。

key変数の下の行に、次のコードをレイアウト アプリケーションに追加します

const formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

const formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

async function recognizeContent() {
    const client = new FormRecognizerClient(endpoint, new AzureKeyCredential(key));
    const poller = await client.beginRecognizeContentFromUrl(formUrl);
    const pages = await poller.pollUntilDone();

    if (!pages || pages.length === 0) {
        throw new Error("Expecting non-empty list of pages!");
    }

    for (const page of pages) {
        console.log(
            `Page ${page.pageNumber}: width ${page.width} and height ${page.height} with unit ${page.unit}`
        );
        for (const table of page.tables) {
            for (const cell of table.cells) {
                console.log(`cell [${cell.rowIndex},${cell.columnIndex}] has text ${cell.text}`);
            }
        }
    }
}

recognizeContent().catch((err) => {
    console.error("The sample encountered an error:", err);
});

試してみる: 事前構築済みモデル

このサンプルでは、請求書を例として使用して、事前トレーニング済みのモデルを使用して、特定の種類の一般的なドキュメントのデータを分析する方法を示します。 請求書フィールドの完全な一覧については、事前構築済みの概念に関するページを参照してください

  • この例では、事前構築済みのモデルを使用して請求書ドキュメントを分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • ファイルの先頭にある invoiceUrl 変数にファイル URI 値を追加しました。
  • URI で特定のファイルを分析するには、 beginRecognizeInvoices メソッドを使用します。
  • わかりやすくするために、サービスから返されるすべてのフィールドはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

事前構築済みモデルを選択する

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 ドキュメント インテリジェンス サービスで現在サポートされている事前構築済みモデルを次に示します。

  • 請求書: 請求書からテキスト、選択マーク、テーブル、フィールド、およびキー情報を抽出します。
  • レシート: レシートからテキストとキー情報を抽出します。
  • ID ドキュメント: 運転免許証と国際パスポートからテキストとキー情報を抽出します。
  • 名刺: 名刺からテキストとキー情報を抽出します。

key変数の下に、事前構築済みの請求書アプリケーションに次のコードを追加します


const invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf";

async function recognizeInvoices() {

    const client = new FormRecognizerClient(endpoint, new AzureKeyCredential(key));

    const poller = await client.beginRecognizeInvoicesFromUrl(invoiceUrl);
    const [invoice] = await poller.pollUntilDone();

    if (invoice === undefined) {
        throw new Error("Failed to extract data from at least one invoice.");
    }

    /**
     * This is a helper function for printing a simple field with an elemental type.
     */
    function fieldToString(field) {
        const {
            name,
            valueType,
            value,
            confidence
        } = field;
        return `${name} (${valueType}): '${value}' with confidence ${confidence}'`;
    }

    console.log("Invoice fields:");

    /**
     * Invoices contain a lot of optional fields, but they are all of elemental types
     * such as strings, numbers, and dates, so we will just enumerate them all.
     */
    for (const [name, field] of Object.entries(invoice.fields)) {
        if (field.valueType !== "array" && field.valueType !== "object") {
            console.log(`- ${name} ${fieldToString(field)}`);
        }
    }

    // Invoices also support nested line items, so we can iterate over them.
    let idx = 0;

    console.log("- Items:");

    const items = invoice.fields["Items"]?.value;
    for (const item of items ?? []) {
        const value = item.value;

        // Each item has several subfields that are nested within the item. We'll
        // map over this list of the subfields and filter out any fields that
        // weren't found. Not all fields will be returned every time, only those
        // that the service identified for the particular document in question.

        const subFields = [
                "Description",
                "Quantity",
                "Unit",
                "UnitPrice",
                "ProductCode",
                "Date",
                "Tax",
                "Amount"
            ]
            .map((fieldName) => value[fieldName])
            .filter((field) => field !== undefined);

        console.log(
            [
                `  - Item #${idx}`,
                // Now we will convert those fields into strings to display
                ...subFields.map((field) => `    - ${fieldToString(field)}`)
            ].join("\n")
        );
    }
}

recognizeInvoices().catch((err) => {
    console.error("The sample encountered an error:", err);
});

Reference documentation | Library source code | Package (PyPi) | Samples

このクイック スタートでは、次の API を使用して、フォームとドキュメントから構造化データを抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成します

  • Python 3.x

    • Pythonインストールには、pipが含まれている必要があります。 コマンド ラインで pip --version を実行することで、pip がインストールされているかどうかを確認できます。 最新バージョンのPythonをインストールして pip を取得します。
  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを作成したら、Azure ポータルで single-service または multi-service ドキュメント インテリジェンス リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする場合は、foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra認証を使用する場合は、単一サービス リソースが必要であることに注意してください。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

セットアップ

ローカル環境でターミナルウィンドウを開き、pipを使用してPython向けのFoundry Tools クライアントライブラリにAzure Document Intelligenceをインストールします。

pip install azure-ai-formrecognizer

新しいPython アプリケーションを作成する

任意のエディターまたは IDE で、form_recognizer_quickstart.py という名前の新しいPython アプリケーションを作成します。 次に、次のライブラリをインポートします。

import os
from azure.ai.formrecognizer import FormRecognizerClient
from azure.core.credentials import AzureKeyCredential

Azure リソース エンドポイントとキーの変数を作成する

endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_KEY"

この時点で、Python アプリケーションには次のコード行が含まれている必要があります。

import os
from azure.core.exceptions import ResourceNotFoundError
from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential

endpoint = "YOUR_FORM_RECOGNIZER_ENDPOINT"
key = "YOUR_FORM_RECOGNIZER_KEY"

アプリケーションにコピーして貼り付けるコード サンプルを選択します。

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、「Foundry Tools のセキュリティ」を参照してください

試してみる: レイアウト モデル

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  • ファイルの URI 値を、ファイルの先頭付近の formUrl 変数に追加しました。
  • URI で特定のファイルを分析するには、 begin_recognize_content_from_url メソッドを使用します。

key変数の下の行に、次のコードをレイアウト アプリケーションに追加します


  def format_bounding_box(bounding_box):
    if not bounding_box:
        return "N/A"
    return ", ".join(["[{}, {}]".format(p.x, p.y) for p in bounding_box])

 def recognize_content():
    # sample document
    formUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf"

    form_recognizer_client = FormRecognizerClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = form_recognizer_client.begin_recognize_content_from_url(formUrl)
    form_pages = poller.result()

    for idx, content in enumerate(form_pages):
        print(
            "Page has width: {} and height: {}, measured with unit: {}".format(
                content.width, content.height, content.unit
            )
        )
        for table_idx, table in enumerate(content.tables):
            print(
                "Table # {} has {} rows and {} columns".format(
                    table_idx, table.row_count, table.column_count
                )
            )
            print(
                "Table # {} location on page: {}".format(
                    table_idx, format_bounding_box(table.bounding_box)
                )
            )
            for cell in table.cells:
                print(
                    "...Cell[{}][{}] has text '{}' within bounding box '{}'".format(
                        cell.row_index,
                        cell.column_index,
                        cell.text,
                        format_bounding_box(cell.bounding_box),
                    )
                )

        for line_idx, line in enumerate(content.lines):
            print(
                "Line # {} has word count '{}' and text '{}' within bounding box '{}'".format(
                    line_idx,
                    len(line.words),
                    line.text,
                    format_bounding_box(line.bounding_box),
                )
            )
            if line.appearance:
                if (
                    line.appearance.style_name == "handwriting"
                    and line.appearance.style_confidence > 0.8
                ):
                    print(
                        "Text line '{}' is handwritten and might be a signature.".format(
                            line.text
                        )
                    )
            for word in line.words:
                print(
                    "...Word '{}' has a confidence of {}".format(
                        word.text, word.confidence
                    )
                )

        for selection_mark in content.selection_marks:
            print(
                "Selection mark is '{}' within bounding box '{}' and has a confidence of {}".format(
                    selection_mark.state,
                    format_bounding_box(selection_mark.bounding_box),
                    selection_mark.confidence,
                )
            )
        print("----------------------------------------")


if __name__ == "__main__":
    recognize_content()

試してみる: 事前構築済みモデル

このサンプルでは、請求書を例として使用して、事前トレーニング済みのモデルを使用して、特定の種類の一般的なドキュメントのデータを分析する方法を示します。 請求書フィールドの完全な一覧については、事前構築済みの概念に関するページを参照してください

  • この例では、事前構築済みのモデルを使用して請求書ドキュメントを分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。
  • ファイルの先頭にある ''formUrl' 変数にファイル URI 値を追加しました。
  • URI で特定のファイルを分析するには、'begin_recognize_invoices_from_url' メソッドを使用します。
  • わかりやすくするために、サービスから返されるすべてのフィールドはここには表示されません。 サポートされているすべてのフィールドと対応する型の一覧については、 請求書 の概念に関するページを参照してください。

事前構築済みモデルを選択する

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 ドキュメント インテリジェンス サービスで現在サポートされている事前構築済みモデルを次に示します。

  • 請求書: 請求書からテキスト、選択マーク、テーブル、フィールド、およびキー情報を抽出します。
  • レシート: レシートからテキストとキー情報を抽出します。
  • ID ドキュメント: 運転免許証と国際パスポートからテキストとキー情報を抽出します。
  • 名刺: 名刺からテキストとキー情報を抽出します。

key変数の下に、事前構築済みの請求書アプリケーションに次のコードを追加します


def recognize_invoice():

    invoiceUrl = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf"

    form_recognizer_client = FormRecognizerClient(
        endpoint=endpoint, credential=AzureKeyCredential(key)
    )

    poller = form_recognizer_client.begin_recognize_invoices_from_url(
        invoiceUrl, locale="en-US"
    )
    invoices = poller.result()

    for idx, invoice in enumerate(invoices):
        vendor_name = invoice.fields.get("VendorName")
        if vendor_name:
            print(
                "Vendor Name: {} has confidence: {}".format(
                    vendor_name.value, vendor_name.confidence
                )
            )
        vendor_address = invoice.fields.get("VendorAddress")
        if vendor_address:
            print(
                "Vendor Address: {} has confidence: {}".format(
                    vendor_address.value, vendor_address.confidence
                )
            )
        vendor_address_recipient = invoice.fields.get("VendorAddressRecipient")
        if vendor_address_recipient:
            print(
                "Vendor Address Recipient: {} has confidence: {}".format(
                    vendor_address_recipient.value, vendor_address_recipient.confidence
                )
            )
        customer_name = invoice.fields.get("CustomerName")
        if customer_name:
            print(
                "Customer Name: {} has confidence: {}".format(
                    customer_name.value, customer_name.confidence
                )
            )
        customer_id = invoice.fields.get("CustomerId")
        if customer_id:
            print(
                "Customer Id: {} has confidence: {}".format(
                    customer_id.value, customer_id.confidence
                )
            )
        customer_address = invoice.fields.get("CustomerAddress")
        if customer_address:
            print(
                "Customer Address: {} has confidence: {}".format(
                    customer_address.value, customer_address.confidence
                )
            )
        customer_address_recipient = invoice.fields.get("CustomerAddressRecipient")
        if customer_address_recipient:
            print(
                "Customer Address Recipient: {} has confidence: {}".format(
                    customer_address_recipient.value,
                    customer_address_recipient.confidence,
                )
            )
        invoice_id = invoice.fields.get("InvoiceId")
        if invoice_id:
            print(
                "Invoice Id: {} has confidence: {}".format(
                    invoice_id.value, invoice_id.confidence
                )
            )
        invoice_date = invoice.fields.get("InvoiceDate")
        if invoice_date:
            print(
                "Invoice Date: {} has confidence: {}".format(
                    invoice_date.value, invoice_date.confidence
                )
            )
        invoice_total = invoice.fields.get("InvoiceTotal")
        if invoice_total:
            print(
                "Invoice Total: {} has confidence: {}".format(
                    invoice_total.value, invoice_total.confidence
                )
            )
        due_date = invoice.fields.get("DueDate")
        if due_date:
            print(
                "Due Date: {} has confidence: {}".format(
                    due_date.value, due_date.confidence
                )
            )
        purchase_order = invoice.fields.get("PurchaseOrder")
        if purchase_order:
            print(
                "Purchase Order: {} has confidence: {}".format(
                    purchase_order.value, purchase_order.confidence
                )
            )
        billing_address = invoice.fields.get("BillingAddress")
        if billing_address:
            print(
                "Billing Address: {} has confidence: {}".format(
                    billing_address.value, billing_address.confidence
                )
            )
        billing_address_recipient = invoice.fields.get("BillingAddressRecipient")
        if billing_address_recipient:
            print(
                "Billing Address Recipient: {} has confidence: {}".format(
                    billing_address_recipient.value,
                    billing_address_recipient.confidence,
                )
            )
        shipping_address = invoice.fields.get("ShippingAddress")
        if shipping_address:
            print(
                "Shipping Address: {} has confidence: {}".format(
                    shipping_address.value, shipping_address.confidence
                )
            )
        shipping_address_recipient = invoice.fields.get("ShippingAddressRecipient")
        if shipping_address_recipient:
            print(
                "Shipping Address Recipient: {} has confidence: {}".format(
                    shipping_address_recipient.value,
                    shipping_address_recipient.confidence,
                )
            )
        print("Invoice items:")
        for idx, item in enumerate(invoice.fields.get("Items").value):
            item_description = item.value.get("Description")
            if item_description:
                print(
                    "......Description: {} has confidence: {}".format(
                        item_description.value, item_description.confidence
                    )
                )
            item_quantity = item.value.get("Quantity")
            if item_quantity:
                print(
                    "......Quantity: {} has confidence: {}".format(
                        item_quantity.value, item_quantity.confidence
                    )
                )
            unit = item.value.get("Unit")
            if unit:
                print(
                    "......Unit: {} has confidence: {}".format(
                        unit.value, unit.confidence
                    )
                )
            unit_price = item.value.get("UnitPrice")
            if unit_price:
                print(
                    "......Unit Price: {} has confidence: {}".format(
                        unit_price.value, unit_price.confidence
                    )
                )
            product_code = item.value.get("ProductCode")
            if product_code:
                print(
                    "......Product Code: {} has confidence: {}".format(
                        product_code.value, product_code.confidence
                    )
                )
            item_date = item.value.get("Date")
            if item_date:
                print(
                    "......Date: {} has confidence: {}".format(
                        item_date.value, item_date.confidence
                    )
                )
            tax = item.value.get("Tax")
            if tax:
                print(
                    "......Tax: {} has confidence: {}".format(tax.value, tax.confidence)
                )
            amount = item.value.get("Amount")
            if amount:
                print(
                    "......Amount: {} has confidence: {}".format(
                        amount.value, amount.confidence
                    )
                )
        subtotal = invoice.fields.get("SubTotal")
        if subtotal:
            print(
                "Subtotal: {} has confidence: {}".format(
                    subtotal.value, subtotal.confidence
                )
            )
        total_tax = invoice.fields.get("TotalTax")
        if total_tax:
            print(
                "Total Tax: {} has confidence: {}".format(
                    total_tax.value, total_tax.confidence
                )
            )
        previous_unpaid_balance = invoice.fields.get("PreviousUnpaidBalance")
        if previous_unpaid_balance:
            print(
                "Previous Unpaid Balance: {} has confidence: {}".format(
                    previous_unpaid_balance.value, previous_unpaid_balance.confidence
                )
            )
        amount_due = invoice.fields.get("AmountDue")
        if amount_due:
            print(
                "Amount Due: {} has confidence: {}".format(
                    amount_due.value, amount_due.confidence
                )
            )
        service_start_date = invoice.fields.get("ServiceStartDate")
        if service_start_date:
            print(
                "Service Start Date: {} has confidence: {}".format(
                    service_start_date.value, service_start_date.confidence
                )
            )
        service_end_date = invoice.fields.get("ServiceEndDate")
        if service_end_date:
            print(
                "Service End Date: {} has confidence: {}".format(
                    service_end_date.value, service_end_date.confidence
                )
            )
        service_address = invoice.fields.get("ServiceAddress")
        if service_address:
            print(
                "Service Address: {} has confidence: {}".format(
                    service_address.value, service_address.confidence
                )
            )
        service_address_recipient = invoice.fields.get("ServiceAddressRecipient")
        if service_address_recipient:
            print(
                "Service Address Recipient: {} has confidence: {}".format(
                    service_address_recipient.value,
                    service_address_recipient.confidence,
                )
            )
        remittance_address = invoice.fields.get("RemittanceAddress")
        if remittance_address:
            print(
                "Remittance Address: {} has confidence: {}".format(
                    remittance_address.value, remittance_address.confidence
                )
            )
        remittance_address_recipient = invoice.fields.get("RemittanceAddressRecipient")
        if remittance_address_recipient:
            print(
                "Remittance Address Recipient: {} has confidence: {}".format(
                    remittance_address_recipient.value,
                    remittance_address_recipient.confidence,
                )
            )


if __name__ == "__main__":
    recognize_invoice()

アプリケーションを実行する

  1. form_recognizer_quickstart.py ファイルがあるフォルダーに移動します。

  2. ターミナルに次のコマンドを入力します。

python form_recognizer_quickstart.py

| Document Intelligence REST API | Azure REST API リファレンス |

このクイック スタートでは、次の API を使用して、フォームとドキュメントから構造化データを抽出します。

前提 条件

  • Azure サブスクリプション - 無料で作成します

  • cURL がインストールされています。

  • PowerShell バージョン 6.0 以降、または同様のコマンド ライン アプリケーション。

  • Foundry ToolsまたはDocument Intelligenceのリソース。 Azure サブスクリプションを作成したら、Azure ポータルで single-service または multi-service ドキュメント インテリジェンス リソースを作成して、キーとエンドポイントを取得します。 Free 価格レベル (F0) を使用してサービスを試し、後で運用環境用の有料レベルにアップグレードできます。

    ヒント

    1 つのエンドポイント/キーで複数の Foundry Tools にアクセスする場合は、foundry リソースを作成します。 ドキュメント インテリジェンス アクセスの場合のみ、ドキュメント インテリジェンス リソースを作成します。 Microsoft Entra認証を使用する場合は、単一サービス リソースが必要であることに注意してください。

  • リソースがデプロイされたら、[ リソースに移動] を選択します。 アプリケーションをドキュメント インテリジェンス API に接続するには、作成するリソースのキーとエンドポイントが必要です。 キーとエンドポイントは、クイックスタートの後半でコードに貼り付けます。

    Azure portal のキーとエンドポイントの場所のスクリーンショット。

アプリケーションにコピーして貼り付けるコード サンプルを選択します。

重要

完了したら、コードからキーを削除し、公開しないでください。 運用環境では、Azure Key Vault。 詳細については、「Foundry Tools のセキュリティ」を参照してください

試してみる: レイアウト モデル

  • この例では、 URI にドキュメント ファイルが必要です。 このクイック スタートでは、サンプル ドキュメントを使用できます。
  1. {endpoint}を、ドキュメント インテリジェンス サブスクリプションで取得したエンドポイントに置き換えます。
  2. {key}は、前の手順でコピーしたキーに置き換えます。
  3. \"{your-document-url}をサンプルドキュメントの URL に置き換えます。
https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-layout.pdf

リクエスト

curl -v -i POST "https://{endpoint}/formrecognizer/v2.1/layout/analyze" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key: {key}" --data-ascii "{​​​​​​​'urlSource': '{your-document-url}'}​​​​​​​​"

オペレーション・ロケーション

202 (Success) ヘッダーを含む応答を受け取ります。 このヘッダーの値には、非同期操作の状態を照会して結果を取得するために使用できる結果 ID が含まれています。

https://cognitiveservice/formrecognizer/v2.1/layout/analyzeResults/{resultId}

次の例では、URL の一部として、 analyzeResults/ 後の文字列が結果 ID です。

https://cognitiveservice/formrecognizer/v2/layout/analyzeResults/54f0b076-4e38-43e5-81bd-b85b8835fdfb

レイアウトの結果を取得する

Analyze Layout API を呼び出した後、Get Analyze Layout Result API を呼び出して、操作の状態と抽出されたデータを取得します。 コマンドを実行する前に、次の変更を行います。

  1. {endpoint}を、ドキュメント インテリジェンス サブスクリプションで取得したエンドポイントに置き換えます。
  2. {key}は、前の手順でコピーしたキーに置き換えます。
  3. {resultId}を前の手順の結果 ID に置き換えます。

要求

curl -v -X GET "https://{endpoint}/formrecognizer/v2.1/layout/analyzeResults/{resultId}" -H "Ocp-Apim-Subscription-Key: {key}"

結果を確認する

JSON コンテンツを含む 200 (success) 応答を受け取ります。

次の請求書イメージとそれに対応する JSON 出力を参照してください。

  • "readResults" ノードは、ページ上のテキストのそれぞれの行とその境界ボックスの配置を含みます。
  • selectionMarks ノードには、すべての選択マーク (チェックボックス、ラジオ マーク) と、その状態がselectedunselectedかが表示されます。
  • "pageResults" セクションには、抽出されたテーブルが含まれています。 テーブルごとに、テキスト、行、列のインデックス、行と列のスパン、境界ボックスなどが抽出されます。

テーブルを含む Contoso プロジェクト ステートメント ドキュメント。

応答本文

GitHubで完全なサンプル出力を表示できます。

試してみる: 事前構築済みモデル

  • この例では、事前構築済みのモデルを使用して請求書ドキュメントを分析します。 このクイック スタートでは、サンプル請求書ドキュメントを使用できます。

事前構築済みモデルを選択する

請求書に限定されるわけではありません。選択できる事前構築済みのモデルがいくつかあります。各モデルには、サポートされるフィールドの独自のセットがあります。 analyze操作に使用するモデルは、分析するドキュメントの種類によって異なります。 ドキュメント インテリジェンス サービスで現在サポートされている事前構築済みモデルを次に示します。

  • 請求書: 請求書からテキスト、選択マーク、テーブル、フィールド、およびキー情報を抽出します。
  • レシート: レシートからテキストとキー情報を抽出します。
  • ID ドキュメント: 運転免許証と国際パスポートからテキストとキー情報を抽出します。
  • 名刺: 名刺からテキストとキー情報を抽出します。

コマンドを実行する前に、次の変更を行います。

  1. {endpoint}を、ドキュメント インテリジェンス サブスクリプションで取得したエンドポイントに置き換えます。

  2. {key}は、前の手順でコピーしたキーに置き換えます。

  3. \"{your-document-url}をサンプルの請求書 URL に置き換えます。

    https://raw.githubusercontent.com/Azure-Samples/cognitive-services-REST-api-samples/master/curl/form-recognizer/sample-invoice.pdf
    

要求

curl -v -i POST https://{endpoint}/formrecognizer/v2.1/prebuilt/invoice/analyze" -H "Content-Type: application/json" -H "Ocp-Apim-Subscription-Key:  {key}" --data-ascii "{​​​​​​​'urlSource': '{your invoice URL}'}​​​​​​​​"

オペレーション・ロケーション

202 (Success) ヘッダーを含む応答を受け取ります。 このヘッダーの値には、非同期操作の状態を照会して結果を取得するために使用できる結果 ID が含まれています。

https://cognitiveservice/formrecognizer/v2.1/prebuilt/receipt/analyzeResults/{resultId}

次の例では、URL の一部として、 analyzeResults/ 後の文字列が結果 ID です。

https://cognitiveservice/formrecognizer/v2.1/prebuilt/invoice/analyzeResults/54f0b076-4e38-43e5-81bd-b85b8835fdfb

請求書の結果を取得する

Analyze Invoice API を呼び出した後、Get Analyze Invoice Result API を呼び出して、操作の状態と抽出されたデータを取得します。 コマンドを実行する前に、次の変更を行います。

  1. {endpoint}を、ドキュメント インテリジェンス キーで取得したエンドポイントに置き換えます。 ドキュメント インテリジェンス リソースの [概要 ] タブで確認できます。
  2. {resultId}を前の手順の結果 ID に置き換えます。
  3. {key}を自分のキーに置き換えてください。

要求

curl -v -X GET "https://{endpoint}/formrecognizer/v2.1/prebuilt/invoice/analyzeResults/{resultId}" -H "Ocp-Apim-Subscription-Key: {key}"

応答を調べる

JSON 出力で 200 (Success) 応答を受け取ります。

  • "readResults" フィールドには、請求書から抽出されたすべてのテキスト行が含まれます。
  • "pageResults"には、請求書から抽出されたテーブルと選択マークが含まれます。
  • "documentResults"フィールドには、請求書の最も関連性の高い部分のキー/値情報が含まれます。

サンプル請求書ドキュメントを参照してください。

応答本文

GitHubの完全なサンプル出力を参照してください。

これで完了です。

次の手順

  • エクスペリエンスの向上と高度なモデル品質を実現するには、 Document Intelligence Studio をお試しください。

    • Studio では、v2.1 ラベル付きデータでトレーニングされたすべてのモデルがサポートされます。

    • 変更ログでは、v3.1 から v4.0 への移行に関する詳細情報が提供されます。