Dokumente verwalten

In diesem Dokument wird beschrieben, wie Sie die Dokumente in Document AI Warehouse verwalten, einschließlich der Vorgänge zum Erstellen, Abrufen, Aktualisieren und Löschen.

Was sind Dokumente?

Ein Dokument ist das Datenmodell, das in Document AI Warehouse verwendet wird, um ein reales Dokument (z. B. PDF oder TXT) und die zugehörigen Eigenschaften zu organisieren. Sie interagieren mit Document AI Warehouse über Vorgänge für die Dokumente.

Unterstützte Dateitypen

Der Schwerpunkt von Document AI Warehouse liegt zwar auf Dokumenten, es wird aber auch zum Verwalten zugehöriger Bilder verwendet, z. B. in Branchen wie Versicherungen, Ingenieurwesen, Bauwesen und Forschung.

  • Die Ingest API unterstützt PDFs und TIFF-, JPEG- und PNG-Bilder sowie alle Eigenschaften oder vorab extrahierten Texte.
  • Die Upload-Benutzeroberfläche unterstützt die Extraktion von PDFs mit Document AI OCR und benutzerdefinierten Prozessoren.
  • Die Viewer-Benutzeroberfläche unterstützt das Rendern in PDF-, Text- und Microsoft Office-Dateien.

Hinweise

Bevor Sie beginnen, müssen Sie die Seite Schnellstart durcharbeiten.

Wenn sich Ihre Daten in Ihrem eigenen Cloud Storage-Bucket befinden, müssen Sie dem Document AI Warehouse-Dienstkonto die Berechtigung „Storage-Objekt-Betrachter“ erteilen, damit es Ihre Daten lesen kann.

Jedes Dokument wird durch ein Schema angegeben und gehört zu einem Dokumenttyp. Ein Dokumentschema definiert die Dokumentstruktur in Document AI Warehouse. Bevor Sie Dokumente erstellen können, müssen Sie ein Dokumentschema erstellen.

Dokument erstellen

Wenn Sie ein Dokument erstellen möchten, müssen Sie Document AI Warehouse Rohdokumentinhalte zur Verfügung stellen. Es gibt zwei Möglichkeiten, Rohdaten für Dokumente bereitzustellen: Sie können entweder Document.inline_raw_document oder Document.raw_document_path festlegen.

Es bestehen jedoch folgende Unterschiede:

  • Document.raw_document_path: Dies ist die bevorzugte Methode. Dazu wird der Cloud Storage-Pfad (gs://bucket/object) der aufzunehmenden Datei verwendet. Hinweis: Der Aufrufer muss Lesezugriff auf dieses Objekt haben, damit der Aufruf erfolgreich ist.
  • Document.inline_raw_document: Byte-/Textdarstellung der Datei, die direkt an den Endpunkt gesendet wird.

So erstellen Sie ein Dokument:

Dokument aus Cloud Storage hochladen

Sie müssen dem Document AI Warehouse-Dienstkonto Zugriff auf Ihren Cloud Storage-Bucket gewähren, wie im Abschnitt „Voraussetzungen“ beschrieben.

Sie müssen Ihre Datei in einen Cloud Storage-Bucket hochladen. Hier finden Sie eine Anleitung dazu.

REST

Anfrage:

curl --location --request POST --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents \
--header "Authorization: Bearer $(gcloud auth print-access-token)" \
--header "Content-Type: application/json; charset=utf-8" \
--data '{
"document": {
  "display_name": "TestDoc3",
  "document_schema_name": "projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/DOCUMENT_SCHEMA_ID",
  "raw_document_path": "gs://BUCKET_URI/FILE_URI",
  "properties": [
    {
      "name": "supplier_name",
      "text_values": {
        "values": "Stanford Plumbing & Heating"
      }
    },
    {
      "name": "total_amount",
      "float_values": {
        "values": "1091.81"
      }
    },
  ]
}, 
"requestMetadata":{
  "userInfo":{
    "id": "user:USER_EMAIL_ID"
  }
}
}'

Von einem lokalen Computer hochladen

REST

Anfrage:

curl --location --request POST --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents/ \
--header "Authorization: Bearer $(gcloud auth print-access-token)" \
--header "Content-Type: application/json; charset=utf-8" \
--data '{
"document": {
  "display_name": "TestDoc3",
  "document_schema_name": "projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/DOCUMENT_SCHEMA_ID",
  "inline_raw_document": "<bytes>",
  "properties": [
    {
      "name": "supplier_name",
      "text_values": {
        "values": "Stanford Plumbing & Heating"
      }
    },
    {
      "name": "total_amount",
      "float_values": {
        "values": "1091.81"
      }
    },
  ]
},
"requestMetadata": {
  "userInfo": {
    "id": "user:USER_EMAIL_ID"
  }
}
}'

Dokument abrufen

Von document_id:

REST

curl --request POST \
--header "Authorization: Bearer $(gcloud auth print-access-token)" \
--header "Content-Type: application/json; charset=UTF-8" -d '{
  "requestMetadata":{
    "userInfo":{
      "id": "user:USER_EMAIL"
    }
  }
}' \
"https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents/DOCUMENT_ID:get"

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Document AI Warehouse Python API.

Richten Sie zur Authentifizierung bei Document AI Warehouse die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


from google.cloud import contentwarehouse


def sample_get_document(document_name: str, user_id: str) -> contentwarehouse.Document:
    """Gets a document.

    Args:
        document_name: The resource name of the document.
                Format: 'projects/{project_number}/
                locations/{location}/documents/{document_id}'.
        user_id: user:YOUR_SERVICE_ACCOUNT_ID or user:USER_EMAIL.
    Returns:
        Response object
    """
    # Create a client
    client = contentwarehouse.DocumentServiceClient()

    request_metadata = contentwarehouse.RequestMetadata(
        user_info=contentwarehouse.UserInfo(id=user_id)
    )

    # Initialize request argument(s)
    request = contentwarehouse.GetDocumentRequest(
        name=document_name, request_metadata=request_metadata
    )

    # Make the request
    response = client.get_document(request=request)

    return response

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Document AI Warehouse Java API.

Richten Sie zur Authentifizierung bei Document AI Warehouse die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.contentwarehouse.v1.Document;
import com.google.cloud.contentwarehouse.v1.DocumentName;
import com.google.cloud.contentwarehouse.v1.DocumentServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentServiceSettings;
import com.google.cloud.contentwarehouse.v1.GetDocumentRequest;
import com.google.cloud.contentwarehouse.v1.RequestMetadata;
import com.google.cloud.contentwarehouse.v1.UserInfo;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class GetDocument {

  public static void getDocument() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException {
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String documentId = "your-document-id";
    String userId = "your-user-id"; // Format is user:<user-id>
    getDocument(projectId, location, documentId, userId);
  }

  // Retrieves details about existing Document using the document Id
  public static void getDocument(String projectId, String location, 
        String documentId, String userId) throws IOException, 
            InterruptedException, ExecutionException, TimeoutException {
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }
    DocumentServiceSettings documentServiceSettings = 
         DocumentServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    // Create a Document Service client
    try (DocumentServiceClient documentServiceClient =
        DocumentServiceClient.create(documentServiceSettings)) {
      /* The full resource name of the location, e.g.: 
       projects/{project_number}/location/{location}/documents/{document_id} */
      DocumentName documentName = 
          DocumentName.of(projectNumber, location, documentId);

      // Define Request Metadata for enforcing access control
      RequestMetadata requestMetadata = RequestMetadata.newBuilder()
            .setUserInfo(
            UserInfo.newBuilder()
              .setId(userId).build()).build();

      // Define request to get details of a specific Document Schema
      GetDocumentRequest getDocumentRequest = 
          GetDocumentRequest.newBuilder()
          .setName(documentName.toString())
          .setRequestMetadata(requestMetadata).build();

      // Get details of the Document 
      Document document = documentServiceClient.getDocument(getDocumentRequest);

      System.out.println(document.getName());
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Document AI Warehouse Node.js API.

Richten Sie zur Authentifizierung bei Document AI Warehouse die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


/**
 * TODO(developer): Uncomment these variables before running the sample.
 * const projectNumber = 'YOUR_PROJECT_NUMBER';
 * const location = 'YOUR_PROJECT_LOCATION'; // Format is 'us' or 'eu'
 * documentId = 'YOUR_DOCUMENT_ID';
 * const userId = 'user:xxx@example.com'; // Format is "user:xxx@example.com"
 */

// Import from google cloud
const {DocumentServiceClient} = require('@google-cloud/contentwarehouse').v1;

const apiEndpoint =
  location === 'us'
    ? 'contentwarehouse.googleapis.com'
    : `${location}-contentwarehouse.googleapis.com`;

// Create service client
const serviceClient = new DocumentServiceClient({
  apiEndpoint: apiEndpoint,
});

// Get Document Schema
async function getDocument() {
  // Initialize request argument(s)
  const documentRequest = {
    // The full resource name of the document, e.g.:
    // projects/{project_number}/locations/{location}/documents/{document_id}
    name: serviceClient.projectLocationDocumentPath(
      projectNumber,
      location,
      documentId
    ),
    requestMetadata: {userInfo: {id: userId}},
  };

  // Make Request
  const response = serviceClient.getDocument(documentRequest);

  // Print out response
  response.then(
    result => console.log(`Document Found: ${JSON.stringify(result)}`),
    error => console.log(`${error}`)
  );
}

Von reference_id:

  curl --request POST \
    --header "Authorization: Bearer $(gcloud auth print-access-token)" \
    --header "Content-Type: application/json; charset=UTF-8" -d '{
      "requestMetadata":{
        "userInfo":{
          "id": "user:USER_EMAIL"
        }
      }
    }' \
    "https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents/referenceId/REFERENCE_ID:get"

Dokument aktualisieren

Von document_id:

REST

posix-terminal curl --location --request POST --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents \ --header "Authorization: Bearer $(gcloud auth print-access-token)" \ --header "Content-Type: application/json; charset=utf-8" \ --data '{ "document": { "display_name": "TestDoc3", "document_schema_name": "projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/DOCUMENT_SCHEMA_ID", "raw_document_path": "gs://BUCKET_URI/FILE_URI", "properties": [ { "name": "supplier_name", "text_values": { "values": "Stanford Plumbing & Heating" } }, { "name": "total_amount", "float_values": { "values": "1091.81" } }, { "name": "invoice_id", "text_values": { "values": "invoiceid" } }, ] }, "requestMetadata": { "userInfo": { "id": "user:USER_EMAIL" } } }'

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Document AI Warehouse Python API.

Richten Sie zur Authentifizierung bei Document AI Warehouse die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


from google.cloud import contentwarehouse


def sample_update_document(
    document_name: str, document: contentwarehouse.Document, user_id: str
) -> contentwarehouse.CreateDocumentResponse:
    """Updates a document.

    Args:
        document_name: The resource name of the document.
                    Format: 'projects/{project_number}/
                    locations/{location}/documents/{document_id}'.
        document: Document AI Warehouse Document object..
        user_id: user_id: user:YOUR_SERVICE_ACCOUNT_ID or user:USER_EMAIL.
    Returns:
        Response object.
    """
    # Create a client
    client = contentwarehouse.DocumentServiceClient()

    # Update document fields
    # For fields which can be updated, refer
    # https://cloud.google.com/python/docs/reference/contentwarehouse/
    # latest/google.cloud.contentwarehouse_v1.types.Document
    document.display_name = "Updated Order Invoice"

    request_metadata = contentwarehouse.RequestMetadata(
        user_info=contentwarehouse.UserInfo(id=user_id)
    )

    request = contentwarehouse.UpdateDocumentRequest(
        name=document_name, document=document, request_metadata=request_metadata
    )

    # Make the request
    response = client.update_document(request=request)

    return response

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Document AI Warehouse Java API.

Richten Sie zur Authentifizierung bei Document AI Warehouse die Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import com.google.cloud.contentwarehouse.v1.Document;
import com.google.cloud.contentwarehouse.v1.DocumentName;
import com.google.cloud.contentwarehouse.v1.DocumentServiceClient;
import com.google.cloud.contentwarehouse.v1.DocumentServiceSettings;
import com.google.cloud.contentwarehouse.v1.GetDocumentRequest;
import com.google.cloud.contentwarehouse.v1.RequestMetadata;
import com.google.cloud.contentwarehouse.v1.UpdateDocumentRequest;
import com.google.cloud.contentwarehouse.v1.UpdateDocumentResponse;
import com.google.cloud.contentwarehouse.v1.UserInfo;
import com.google.cloud.resourcemanager.v3.Project;
import com.google.cloud.resourcemanager.v3.ProjectName;
import com.google.cloud.resourcemanager.v3.ProjectsClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class UpdateDocument {
  public static void updateDocument() throws IOException, 
        InterruptedException, ExecutionException, TimeoutException { 
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String location = "your-region"; // Format is "us" or "eu".
    String documentId = "your-document-id";
    String userId = "your-user-id"; // Format is user:<user-id>
    /* The below method call retrieves details about the document you are about to update.
    * It is important to note that some properties cannot be edited or removed. 
    * For more information on managing documents, please see the below documentation.
    * https://cloud.google.com/document-warehouse/docs/manage-documents */
    GetDocument.getDocument(projectId, location, documentId, userId);
    updateDocument(projectId, location, documentId, userId);
  }

  // Updates an existing Document
  public static void updateDocument(String projectId, String location,
        String documentId, String userId) throws IOException, InterruptedException,
          ExecutionException, TimeoutException { 
    String projectNumber = getProjectNumber(projectId);

    String endpoint = "contentwarehouse.googleapis.com:443";
    if (!"us".equals(location)) {
      endpoint = String.format("%s-%s", location, endpoint);
    }

    DocumentServiceSettings documentServiceSettings = 
             DocumentServiceSettings.newBuilder().setEndpoint(endpoint).build(); 

    /* Create the Document Service Client 
     * Initialize client that will be used to send requests. 
     * This client only needs to be created once, and can be reused for multiple requests. */
    try (DocumentServiceClient documentServiceClient = 
            DocumentServiceClient.create(documentServiceSettings)) {

      /* The full resource name of the location, e.g.: 
       projects/{project_number}/location/{location}/documentSchemas/{document_schema_id} */
      DocumentName documentName = 
          DocumentName.of(projectNumber, location, documentId);

      // Define RequestMetadata object for context of the user making the API call
      RequestMetadata requestMetadata = RequestMetadata.newBuilder()
          .setUserInfo(
          UserInfo.newBuilder()
            .setId(userId).build()).build();

      // Get the document to retreive the document schema associated with the object
      GetDocumentRequest getDocumentRequest = GetDocumentRequest.newBuilder()
          .setName(documentName.toString())
          .setRequestMetadata(requestMetadata)
          .build(); 

      // Execute the request and store response in a document object
      Document document = documentServiceClient.getDocument(getDocumentRequest);

      // Define the updates to the document that will be passed in the request
      Document updatedDocument = Document.newBuilder()
          .setDisplayName("Updated Document Display Name")
          .setDocumentSchemaName(document.getDocumentSchemaName()).build();

      // Create the request to Update the Document
      UpdateDocumentRequest updateDocumentRequest = 
            UpdateDocumentRequest.newBuilder()
              .setName(documentName.toString())
              .setDocument(updatedDocument)
              .setRequestMetadata(requestMetadata)
              .build();

      // Update Document and receive response
      UpdateDocumentResponse updateDocumentResponse = 
          documentServiceClient.updateDocument(updateDocumentRequest);

      // Read the output of Updated Document Name
      System.out.println(updateDocumentResponse.getDocument().getDisplayName());
    }
  }

  private static String getProjectNumber(String projectId) throws IOException { 
    /* Initialize client that will be used to send requests. 
    * This client only needs to be created once, and can be reused for multiple requests. */
    try (ProjectsClient projectsClient = ProjectsClient.create()) { 
      ProjectName projectName = ProjectName.of(projectId); 
      Project project = projectsClient.getProject(projectName);
      String projectNumber = project.getName(); // Format returned is projects/xxxxxx
      return projectNumber.substring(projectNumber.lastIndexOf("/") + 1);
    } 
  }
}

Von reference_id:

  curl --location --request POST --url https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents \
--header "Authorization: Bearer $(gcloud auth print-access-token)" \
--header "Content-Type: application/json; charset=utf-8" \
--data '{
  "document": {
    "display_name": "TestDoc3",
    "document_schema_name": "projects/PROJECT_NUMBER/locations/LOCATION/documentSchemas/referenceId/REFERENCE_ID",
    "raw_document_path": "gs://BUCKET_URI/FILE_URI",
    "properties": [
      {
        "name": "supplier_name",
        "text_values": {
          "values": "Stanford Plumbing & Heating"
        }
      },
      {
        "name": "total_amount",
        "float_values": {
          "values": "1091.81"
        }
      },
      {
        "name": "invoice_id",
        "text_values": {
          "values": "invoiceid"
        }
      },
    ]
  },
  "requestMetadata": {
    "userInfo": {
      "id": "user:USER_EMAIL"
    }
  }
}'

Dokument löschen

REST

Von document_id:

curl --request POST \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --header "Content-Type: application/json; charset=UTF-8" -d '{
    "requestMetadata":{
      "userInfo":{
        "id": "user:USER_EMAIL"
      }
    }
  }' \
  "https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents/DOCUMENT_ID:delete"

Von reference_id:

curl --request POST \
  --header "Authorization: Bearer $(gcloud auth print-access-token)" \
  --header "Content-Type: application/json; charset=UTF-8" -d '{
    "requestMetadata":{
      "userInfo":{
        "id": "user:USER_EMAIL"
      }
    }
  }' \
  "https://contentwarehouse.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/documents/referenceId/REFERENCE_ID":delete"

Nächste Schritte