Azure.AI.DocumentIntelligence (.NET)
使用預建模型和自訂模型從文件中提取文字、表格和結構化資料。
安裝
dotnet add package Azure.AI.DocumentIntelligence
dotnet add package Azure.Identity
目前版本:v1.0.0 (GA)
環境變數
DOCUMENT_INTELLIGENCE_ENDPOINT=https://<resource-name>.cognitiveservices.azure.com/
DOCUMENT_INTELLIGENCE_API_KEY=<your-api-key>
BLOB_CONTAINER_SAS_URL=https://<storage>.blob.core.windows.net/<container>?<sas-token>
AZURE_TOKEN_CREDENTIALS=prod
驗證
Microsoft Entra 權杖憑證
using Azure.Identity;
using Azure.AI.DocumentIntelligence;
string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
var client = new DocumentIntelligenceClient(new Uri(endpoint), credential);
注意:Entra ID 需要自訂子網域(例如 https://<resource-name>.cognitiveservices.azure.com/),而非區域端點。
API 金鑰
string endpoint = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_ENDPOINT");
string apiKey = Environment.GetEnvironmentVariable("DOCUMENT_INTELLIGENCE_API_KEY");
var client = new DocumentIntelligenceClient(new Uri(endpoint), new AzureKeyCredential(apiKey));
用戶端類型
| 用戶端 | 用途 |
|---|
DocumentIntelligenceClient | 分析文件、分類文件 |
DocumentIntelligenceAdministrationClient | 建立/管理自訂模型和分類器 |
預建模型
| 模型 ID | 說明 |
|---|
prebuilt-read | 提取文字、語言、手寫內容 |
prebuilt-layout | 提取文字、表格、選取標記、結構 |
prebuilt-invoice | 提取發票欄位(供應商、項目、總計) |
prebuilt-receipt | 提取收據欄位(商家、項目、總計) |
prebuilt-idDocument | 提取身分證件欄位(姓名、出生日期、地址) |
prebuilt-businessCard | 提取名片欄位 |
prebuilt-tax.us.w2 | 提取 W-2 稅表欄位 |
prebuilt-healthInsuranceCard.us | 提取健康保險卡欄位 |
核心工作流程
1. 分析發票
using Azure.AI.DocumentIntelligence;
Uri invoiceUri = new Uri("https://example.com/invoice.pdf");
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-invoice",
invoiceUri);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
if (document.Fields.TryGetValue("VendorName", out DocumentField vendorNameField)
&& vendorNameField.FieldType == DocumentFieldType.String)
{
string vendorName = vendorNameField.ValueString;
Console.WriteLine($"供應商名稱:'{vendorName}',信心度:{vendorNameField.Confidence}");
}
if (document.Fields.TryGetValue("InvoiceTotal", out DocumentField invoiceTotalField)
&& invoiceTotalField.FieldType == DocumentFieldType.Currency)
{
CurrencyValue invoiceTotal = invoiceTotalField.ValueCurrency;
Console.WriteLine($"發票總計:'{invoiceTotal.CurrencySymbol}{invoiceTotal.Amount}'");
}
if (document.Fields.TryGetValue("Items", out DocumentField itemsField)
&& itemsField.FieldType == DocumentFieldType.List)
{
foreach (DocumentField item in itemsField.ValueList)
{
var itemFields = item.ValueDictionary;
if (itemFields.TryGetValue("Description", out DocumentField descField))
Console.WriteLine($" 項目:{descField.ValueString}");
}
}
}
2. 提取版面配置(文字、表格、結構)
Uri fileUri = new Uri("https://example.com/document.pdf");
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-layout",
fileUri);
AnalyzeResult result = operation.Value;
foreach (DocumentPage page in result.Pages)
{
Console.WriteLine($"第 {page.PageNumber} 頁:{page.Lines.Count} 行,{page.Words.Count} 個字");
foreach (DocumentLine line in page.Lines)
{
Console.WriteLine($" 行:'{line.Content}'");
}
}
foreach (DocumentTable table in result.Tables)
{
Console.WriteLine($"表格:{table.RowCount} 行 x {table.ColumnCount} 列");
foreach (DocumentTableCell cell in table.Cells)
{
Console.WriteLine($" 儲存格 ({cell.RowIndex}, {cell.ColumnIndex}):{cell.Content}");
}
}
3. 分析收據
Operation<AnalyzeResult> operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-receipt",
receiptUri);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
if (document.Fields.TryGetValue("MerchantName", out DocumentField merchantField))
Console.WriteLine($"商家:{merchantField.ValueString}");
if (document.Fields.TryGetValue("Total", out DocumentField totalField))
Console.WriteLine($"總計:{totalField.ValueCurrency.Amount}");
if (document.Fields.TryGetValue("TransactionDate", out DocumentField dateField))
Console.WriteLine($"日期:{dateField.ValueDate}");
}
4. 建立自訂模型
var adminClient = new DocumentIntelligenceAdministrationClient(
new Uri(endpoint),
new AzureKeyCredential(apiKey));
string modelId = "my-custom-model";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");
var blobSource = new BlobContentSource(blobContainerUri);
var options = new BuildDocumentModelOptions(modelId, DocumentBuildMode.Template, blobSource);
Operation<DocumentModelDetails> operation = await adminClient.BuildDocumentModelAsync(
WaitUntil.Completed,
options);
DocumentModelDetails model = operation.Value;
Console.WriteLine($"模型 ID:{model.ModelId}");
Console.WriteLine($"建立時間:{model.CreatedOn}");
foreach (var docType in model.DocumentTypes)
{
Console.WriteLine($"文件類型:{docType.Key}");
foreach (var field in docType.Value.FieldSchema)
{
Console.WriteLine($" 欄位:{field.Key},信心度:{docType.Value.FieldConfidence[field.Key]}");
}
}
5. 建立文件分類器
string classifierId = "my-classifier";
Uri blobContainerUri = new Uri("<blob-container-sas-url>");
var sourceA = new BlobContentSource(blobContainerUri) { Prefix = "TypeA/train" };
var sourceB = new BlobContentSource(blobContainerUri) { Prefix = "TypeB/train" };
var docTypes = new Dictionary<string, ClassifierDocumentTypeDetails>()
{
{ "TypeA", new ClassifierDocumentTypeDetails(sourceA) },
{ "TypeB", new ClassifierDocumentTypeDetails(sourceB) }
};
var options = new BuildClassifierOptions(classifierId, docTypes);
Operation<DocumentClassifierDetails> operation = await adminClient.BuildClassifierAsync(
WaitUntil.Completed,
options);
DocumentClassifierDetails classifier = operation.Value;
Console.WriteLine($"分類器 ID:{classifier.ClassifierId}");
6. 分類文件
string classifierId = "my-classifier";
Uri documentUri = new Uri("https://example.com/document.pdf");
var options = new ClassifyDocumentOptions(classifierId, documentUri);
Operation<AnalyzeResult> operation = await client.ClassifyDocumentAsync(
WaitUntil.Completed,
options);
AnalyzeResult result = operation.Value;
foreach (AnalyzedDocument document in result.Documents)
{
Console.WriteLine($"文件類型:{document.DocumentType},信心度:{document.Confidence}");
}
7. 管理模型
DocumentIntelligenceResourceDetails resourceDetails = await adminClient.GetResourceDetailsAsync();
Console.WriteLine($"自訂模型:{resourceDetails.CustomDocumentModels.Count}/{resourceDetails.CustomDocumentModels.Limit}");
DocumentModelDetails model = await adminClient.GetModelAsync("my-model-id");
Console.WriteLine($"模型:{model.ModelId},建立時間:{model.CreatedOn}");
await foreach (DocumentModelDetails modelItem in adminClient.GetModelsAsync())
{
Console.WriteLine($"模型:{modelItem.ModelId}");
}
await adminClient.DeleteModelAsync("my-model-id");
主要類型參考
| 類型 | 說明 |
|---|
DocumentIntelligenceClient | 用於分析的主要用戶端 |
DocumentIntelligenceAdministrationClient | 模型管理 |
AnalyzeResult | 文件分析的結果 |
AnalyzedDocument | 結果中的單一文件 |
DocumentField | 提取的欄位,包含數值和信心度 |
DocumentFieldType | 字串、日期、數字、貨幣等 |
DocumentPage | 頁面資訊(行、字、選取標記) |
DocumentTable | 提取的表格,包含儲存格 |
DocumentModelDetails | 自訂模型元資料 |
BlobContentSource | 訓練資料來源 |
建置模式
| 模式 | 使用案例 |
|---|
DocumentBuildMode.Template | 固定版面的文件(表單) |
DocumentBuildMode.Neural | 可變版面的文件 |
最佳實踐
- 在生產環境使用 DefaultAzureCredential
- 重複使用用戶端實例 — 用戶端是執行緒安全的
- 處理長時間執行的操作 — 為求簡潔,使用
WaitUntil.Completed
- 檢查欄位信心度 — 務必驗證
Confidence 屬性
- 使用適當的模型 — 常見文件使用預建模型,特殊文件使用自訂模型
- 使用自訂子網域 — Entra ID 驗證所需
錯誤處理
using Azure;
try
{
var operation = await client.AnalyzeDocumentAsync(
WaitUntil.Completed,
"prebuilt-invoice",
documentUri);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"錯誤:{ex.Status} - {ex.Message}");
}
相關 SDK
| SDK | 用途 | 安裝 |
|---|
Azure.AI.DocumentIntelligence | 文件分析(此 SDK) | dotnet add package Azure.AI.DocumentIntelligence |
Azure.AI.FormRecognizer | 舊版 SDK(已淘汰) | 請改用 DocumentIntelligence |
參考連結