本页面介绍了如何开始使用 Document AI API 的 Cloud 客户端库。通过客户端库,您可以更轻松地使用支持的语言访问Google Cloud API。虽然您可以通过向服务器发出原始请求来直接使用Google Cloud API,但客户端库可实现简化,从而显著减少您需要编写的代码量。
请参阅客户端库说明,详细了解 Cloud 客户端库和旧版 Google API 客户端库。
安装客户端库
C++
如需详细了解此客户端库的要求和安装依赖项,请参阅设置 C++ 开发环境。
C#
Install-Package Google.Cloud.DocumentAI.V1 -Pre
如需了解详情,请参阅设置 C# 开发环境。
Go
go get cloud.google.com/go/documentai
如需了解详情,请参阅设置 Go 开发环境。
Java
如果您使用的是 Maven,请将以下代码添加到您的 pom.xml 文件中。如需详细了解 BOM,请参阅 Google Cloud Platform 库 BOM。
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>libraries-bom</artifactId>
<version>26.83.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-document-ai</artifactId>
</dependency>
</dependencies>如果您使用的是 Gradle,请将以下代码添加到您的依赖项中:
implementation platform('com.google.cloud:libraries-bom:26.83.0')
implementation 'com.google.cloud:google-cloud-document-ai'如果您使用的是 sbt,请将以下代码添加到您的依赖项中:
libraryDependencies += "com.google.cloud" % "google-cloud-document-ai" % "2.98.0"如果您使用的是 Visual Studio Code 或 IntelliJ,可以通过以下 IDE 插件将客户端库添加到您的项目中:
上述插件还提供其他功能,例如服务账号密钥管理。如需了解详情,请参阅各个插件相应的文档。
如需了解详情,请参阅设置 Java 开发环境。
Node.js
npm install @google-cloud/documentai
如需了解详情,请参阅设置 Node.js 开发环境。
PHP
composer require google/cloud-document-ai
如需了解详情,请参阅在 Google Cloud 上使用 PHP。
Python
pip install --upgrade google-cloud-documentai
如需了解详情,请参阅设置 Python 开发环境。
Ruby
gem install google-cloud-document_ai
如需了解详情,请参阅设置 Ruby 开发环境。
设置身份验证
为了对 Google Cloud API 的调用进行身份验证,客户端库支持应用默认凭证 (ADC);这些库会在一组指定的位置查找凭证,并使用这些凭证对发送到 API 的请求进行身份验证。借助 ADC,您可以在各种环境(例如本地开发或生产环境)中为您的应用提供凭据,而无需修改应用代码。对于生产环境,设置 ADC 的方式取决于服务和上下文。如需了解详情,请参阅设置应用默认凭证。
对于本地开发环境,您可以使用与您的 Google 账号关联的凭据设置 ADC:
-
安装 Google Cloud CLI,然后 使用联合身份登录 gcloud CLI。 登录后,运行以下命令来初始化 Google Cloud CLI:
gcloud init -
为您的用户账号创建本地身份验证凭证:
gcloud auth application-default login
如果系统返回身份验证错误,并且您使用的是外部身份提供方 (IdP),请确认您已 使用联合身份登录 gcloud CLI。
登录屏幕随即出现。在您登录后,您的凭据会存储在 ADC 使用的本地凭据文件中。
使用客户端库
以下示例展示了如何使用客户端库。
C++
#include "google/cloud/documentai/v1/document_processor_client.h"
#include "google/cloud/location.h"
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char* argv[]) try {
if (argc != 5) {
std::cerr << "Usage: " << argv[0]
<< " project-id location-id processor-id filename (PDF only)\n";
return 1;
}
std::string const location_id = argv[2];
if (location_id != "us" && location_id != "eu") {
std::cerr << "location-id must be either 'us' or 'eu'\n";
return 1;
}
auto const location = google::cloud::Location(argv[1], location_id);
namespace documentai = ::google::cloud::documentai_v1;
auto client = documentai::DocumentProcessorServiceClient(
documentai::MakeDocumentProcessorServiceConnection(
location.location_id()));
google::cloud::documentai::v1::ProcessRequest req;
req.set_name(location.FullName() + "/processors/" + argv[3]);
req.set_skip_human_review(true);
auto& doc = *req.mutable_raw_document();
doc.set_mime_type("application/pdf");
std::ifstream is(argv[4]);
doc.set_content(std::string{std::istreambuf_iterator<char>(is), {}});
auto resp = client.ProcessDocument(std::move(req));
if (!resp) throw std::move(resp).status();
std::cout << resp->document().text() << "\n";
return 0;
} catch (google::cloud::Status const& status) {
std::cerr << "google::cloud::Status thrown: " << status << "\n";
return 1;
}C#
using Google.Cloud.DocumentAI.V1;
using Google.Protobuf;
using System;
using System.IO;
public class QuickstartSample
{
public Document Quickstart(
string projectId = "your-project-id",
string locationId = "your-processor-location",
string processorId = "your-processor-id",
string localPath = "my-local-path/my-file-name",
string mimeType = "application/pdf"
)
{
// Create client
var client = new DocumentProcessorServiceClientBuilder
{
Endpoint = $"{locationId}-documentai.googleapis.com"
}.Build();
// Read in local file
using var fileStream = File.OpenRead(localPath);
var rawDocument = new RawDocument
{
Content = ByteString.FromStream(fileStream),
MimeType = mimeType
};
// Initialize request argument(s)
var request = new ProcessRequest
{
Name = ProcessorName.FromProjectLocationProcessor(projectId, locationId, processorId).ToString(),
RawDocument = rawDocument
};
// Make the request
var response = client.ProcessDocument(request);
var document = response.Document;
Console.WriteLine(document.Text);
return document;
}
}
Go
import (
"context"
"flag"
"fmt"
"os"
documentai "cloud.google.com/go/documentai/apiv1"
"cloud.google.com/go/documentai/apiv1/documentaipb"
"google.golang.org/api/option"
)
func main() {
projectID := flag.String("project_id", "PROJECT_ID", "Cloud Project ID")
location := flag.String("location", "us", "The Processor location")
// Create a Processor before running sample
processorID := flag.String("processor_id", "aaaaaaaa", "The Processor ID")
filePath := flag.String("file_path", "invoice.pdf", "The path to the file to parse")
mimeType := flag.String("mime_type", "application/pdf", "The mimeType of the file")
flag.Parse()
ctx := context.Background()
endpoint := fmt.Sprintf("%s-documentai.googleapis.com:443", *location)
client, err := documentai.NewDocumentProcessorClient(ctx, option.WithEndpoint(endpoint))
if err != nil {
fmt.Println(fmt.Errorf("error creating Document AI client: %w", err))
}
defer client.Close()
// Open local file.
data, err := os.ReadFile(*filePath)
if err != nil {
fmt.Println(fmt.Errorf("os.ReadFile: %w", err))
}
req := &documentaipb.ProcessRequest{
Name: fmt.Sprintf("projects/%s/locations/%s/processors/%s", *projectID, *location, *processorID),
Source: &documentaipb.ProcessRequest_RawDocument{
RawDocument: &documentaipb.RawDocument{
Content: data,
MimeType: *mimeType,
},
},
}
resp, err := client.ProcessDocument(ctx, req)
if err != nil {
fmt.Println(fmt.Errorf("processDocument: %w", err))
}
// Handle the results.
document := resp.GetDocument()
fmt.Printf("Document Text: %s", document.GetText())
}
Java
import com.google.cloud.documentai.v1.Document;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.ProcessRequest;
import com.google.cloud.documentai.v1.ProcessResponse;
import com.google.cloud.documentai.v1.RawDocument;
import com.google.protobuf.ByteString;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
public class QuickStart {
public static void main(String[] args)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String location = "your-project-location"; // Format is "us" or "eu".
String processorId = "your-processor-id";
String filePath = "path/to/input/file.pdf";
quickStart(projectId, location, processorId, filePath);
}
public static void quickStart(
String projectId, String location, String processorId, String filePath)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// Initialize client that will be used to send requests. This client only needs
// to be created
// once, and can be reused for multiple requests. After completing all of your
// requests, call
// the "close" method on the client to safely clean up any remaining background
// resources.
String endpoint = String.format("%s-documentai.googleapis.com:443", location);
DocumentProcessorServiceSettings settings =
DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();
try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
// The full resource name of the processor, e.g.:
// projects/project-id/locations/location/processor/processor-id
// You must create new processors in the Cloud Console first
String name =
String.format("projects/%s/locations/%s/processors/%s", projectId, location, processorId);
// Read the file.
byte[] imageFileData = Files.readAllBytes(Paths.get(filePath));
// Convert the image data to a Buffer and base64 encode it.
ByteString content = ByteString.copyFrom(imageFileData);
RawDocument document =
RawDocument.newBuilder().setContent(content).setMimeType("application/pdf").build();
// Configure the process request.
ProcessRequest request =
ProcessRequest.newBuilder().setName(name).setRawDocument(document).build();
// Recognizes text entities in the PDF document
ProcessResponse result = client.processDocument(request);
Document documentResponse = result.getDocument();
// Get all of the document text as one big string
String text = documentResponse.getText();
// Read the text recognition output from the processor
System.out.println("The document contains the following paragraphs:");
Document.Page firstPage = documentResponse.getPages(0);
List<Document.Page.Paragraph> paragraphs = firstPage.getParagraphsList();
for (Document.Page.Paragraph paragraph : paragraphs) {
String paragraphText = getText(paragraph.getLayout().getTextAnchor(), text);
System.out.printf("Paragraph text:\n%s\n", paragraphText);
}
}
}
// Extract shards from the text field
private static String getText(Document.TextAnchor textAnchor, String text) {
if (textAnchor.getTextSegmentsList().size() > 0) {
int startIdx = (int) textAnchor.getTextSegments(0).getStartIndex();
int endIdx = (int) textAnchor.getTextSegments(0).getEndIndex();
return text.substring(startIdx, endIdx);
}
return "[NO TEXT]";
}
}Node.js
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
// const processorId = 'YOUR_PROCESSOR_ID'; // Create processor in Cloud Console
// const filePath = '/path/to/local/pdf';
const {DocumentProcessorServiceClient} =
require('@google-cloud/documentai').v1;
// Instantiates a client
// apiEndpoint regions available: eu-documentai.googleapis.com, us-documentai.googleapis.com (Required if using eu based processor)
// const client = new DocumentProcessorServiceClient({apiEndpoint: 'eu-documentai.googleapis.com'});
const client = new DocumentProcessorServiceClient();
async function quickstart() {
// The full resource name of the processor, e.g.:
// projects/project-id/locations/location/processor/processor-id
// You must create new processors in the Cloud Console first
const name = `projects/${projectId}/locations/${location}/processors/${processorId}`;
// Read the file into memory.
const fs = require('fs').promises;
const imageFile = await fs.readFile(filePath);
// Convert the image data to a Buffer and base64 encode it.
const encodedImage = Buffer.from(imageFile).toString('base64');
const request = {
name,
rawDocument: {
content: encodedImage,
mimeType: 'application/pdf',
},
};
// Recognizes text entities in the PDF document
const [result] = await client.processDocument(request);
const {document} = result;
// Get all of the document text as one big string
const {text} = document;
// Extract shards from the text field
const getText = textAnchor => {
if (!textAnchor.textSegments || textAnchor.textSegments.length === 0) {
return '';
}
// First shard in document doesn't have startIndex property
const startIndex = textAnchor.textSegments[0].startIndex || 0;
const endIndex = textAnchor.textSegments[0].endIndex;
return text.substring(startIndex, endIndex);
};
// Read the text recognition output from the processor
console.log('The document contains the following paragraphs:');
const [page1] = document.pages;
const {paragraphs} = page1;
for (const paragraph of paragraphs) {
const paragraphText = getText(paragraph.layout.textAnchor);
console.log(`Paragraph text:\n${paragraphText}`);
}
}PHP
# Include the autoloader for libraries installed with Composer.
require __DIR__ . '/vendor/autoload.php';
# Import the Google Cloud client library.
use Google\Cloud\DocumentAI\V1\Client\DocumentProcessorServiceClient;
use Google\Cloud\DocumentAI\V1\RawDocument;
use Google\Cloud\DocumentAI\V1\ProcessRequest;
# TODO(developer): Update the following lines before running the sample.
# Your Google Cloud Platform project ID.
$projectId = 'YOUR_PROJECT_ID';
# Your Processor Location.
$location = 'us';
# Your Processor ID as hexadecimal characters.
# Not to be confused with the Processor Display Name.
$processorId = 'YOUR_PROCESSOR_ID';
# Path for the file to read.
$documentPath = 'resources/invoice.pdf';
# Create Client.
$client = new DocumentProcessorServiceClient();
# Read in file.
$handle = fopen($documentPath, 'rb');
$contents = fread($handle, filesize($documentPath));
fclose($handle);
# Load file contents into a RawDocument.
$rawDocument = (new RawDocument())
->setContent($contents)
->SetMimeType('application/pdf');
# Get the Fully-qualified Processor Name.
$fullProcessorName = $client->processorName($projectId, $location, $processorId);
# Send a ProcessRequest and get a ProcessResponse.
$request = (new ProcessRequest())
->setName($fullProcessorName)
->setRawDocument($rawDocument);
$response = $client->processDocument($request);
# Show the text found in the document.
printf('Document Text: %s', $response->getDocument()->getText());Python
from google.api_core.client_options import ClientOptions
from google.cloud import documentai_v1
# TODO(developer): Create a processor of type "OCR_PROCESSOR".
# TODO(developer): Update and uncomment these variables before running the sample.
# project_id = "MY_PROJECT_ID"
# Processor ID as hexadecimal characters.
# Not to be confused with the Processor Display Name.
# processor_id = "MY_PROCESSOR_ID"
# Processor location. For example: "us" or "eu".
# location = "MY_PROCESSOR_LOCATION"
# Path for file to process.
# file_path = "/path/to/local/pdf"
# Set `api_endpoint` if you use a location other than "us".
opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
# Initialize Document AI client.
client = documentai_v1.DocumentProcessorServiceClient(client_options=opts)
# Get the Fully-qualified Processor path.
full_processor_name = client.processor_path(project_id, location, processor_id)
# Get a Processor reference.
request = documentai_v1.GetProcessorRequest(name=full_processor_name)
processor = client.get_processor(request=request)
# `processor.name` is the full resource name of the processor.
# For example: `projects/{project_id}/locations/{location}/processors/{processor_id}`
print(f"Processor Name: {processor.name}")
# Read the file into memory.
with open(file_path, "rb") as image:
image_content = image.read()
# Load binary data.
# For supported MIME types, refer to https://cloud.google.com/document-ai/docs/file-types
raw_document = documentai_v1.RawDocument(
content=image_content,
mime_type="application/pdf",
)
# Send a request and get the processed document.
request = documentai_v1.ProcessRequest(name=processor.name, raw_document=raw_document)
result = client.process_document(request=request)
document = result.document
# Read the text recognition output from the processor.
# For a full list of `Document` object attributes, reference this page:
# https://cloud.google.com/document-ai/docs/reference/rest/v1/Document
print("The document contains the following text:")
print(document.text)Ruby
require "google/cloud/document_ai/v1"
##
# Document AI quickstart
#
# @param project_id [String] Your Google Cloud project (e.g. "my-project")
# @param location_id [String] Your Processor Location (e.g. "us")
# @param processor_id [String] Your Processor ID (e.g. "a14dae8f043b60bd")
# @param file_path [String] Path to Local File (e.g. "invoice.pdf")
# @param mime_type [String] Refer to https://cloud.google.com/document-ai/docs/file-types (e.g. "application/pdf")
#
def quickstart project_id:, location_id:, processor_id:, file_path:, mime_type:
# Create the Document AI client.
client = ::Google::Cloud::DocumentAI::V1::DocumentProcessorService::Client.new do |config|
config.endpoint = "#{location_id}-documentai.googleapis.com"
end
# Build the resource name from the project.
name = client.processor_path(
project: project_id,
location: location_id,
processor: processor_id
)
# Read the bytes into memory
content = File.binread file_path
# Create request
request = Google::Cloud::DocumentAI::V1::ProcessRequest.new(
skip_human_review: true,
name: name,
raw_document: {
content: content,
mime_type: mime_type
}
)
# Process document
response = client.process_document request
# Handle response
puts response.document.text
end其他资源
C++
以下列表包含与 C++ 版客户端库相关的更多资源的链接:
C#
以下列表包含与 C# 版客户端库相关的更多资源的链接:
Go
以下列表包含与 Go 版客户端库相关的更多资源的链接:
Java
以下列表包含与 Java 版客户端库相关的更多资源的链接:
Node.js
以下列表包含与 Node.js 版客户端库相关的更多资源的链接:
PHP
以下列表包含与 PHP 版客户端库相关的更多资源的链接:
Python
以下列表包含与 Python 版客户端库相关的更多资源的链接:
Ruby
以下列表包含与 Ruby 版客户端库相关的更多资源的链接: