ניהול פעולות ממושכות (LRO)

פעולות ממושכות מוחזרות על ידי קריאות לשיטות של עיבוד באצווה, כי משך הפעולה שלהן ארוך יותר מהזמן המתאים לתגובת API. כך, השרשור של השיחה לא נשאר פתוח בזמן העיבוד של הרבה מסמכים. ממשק Document AI API יוצר LRO בכל פעם שמבצעים קריאה ל-projects.locations.processors.batchProcess דרך ה-API או ספריות הלקוח. ה-LRO עוקב אחרי הסטטוס של משימת העיבוד.

אתם יכולים להשתמש בשיטות הפעולות ש-Document AI API מספק כדי לבדוק את הסטטוס של פעולות ממושכות. אפשר גם לרשום, לשאול או לבטל פעולות LRO. ספריות לקוח שקוראות לשיטה אסינכרונית מבצעות סקר באופן פנימי, וכך מאפשרות קריאה חוזרת. (ב-Python, ‏ await מופעל). הן כוללות גם פרמטר של פסק זמן. בתוך ה-LRO הראשי שמוחזר על ידי ‎ .batchProcess, נוצר LRO לכל מסמך (כי מגבלות ספירת הדפים של אצווה גבוהות בהרבה מאלה של קריאת ה-sync‏ process, והעיבוד יכול להימשך זמן רב). כש-LRO הראשי מסתיים, מוצג הסטטוס המפורט של כל מסמך LRO.

הפעולות ארוכות הטווח מנוהלות ברמת Google Cloud הפרויקט והמיקום. כששולחים בקשה ל-API, צריך לכלול את Google Cloud הפרויקט ואת המיקום שבו פועל ה-LRO.

רשומה של פעולה ארוכת טווח נשמרת למשך כ-30 יום אחרי שהפעולה מסתיימת, כלומר אחרי התקופה הזו אי אפשר לראות או לרשום פעולה ארוכת טווח.

קבלת פרטים על פעולה ממושכת

בדוגמאות הבאות אפשר לראות איך מקבלים פרטים על פעולת LRO.

REST

כדי לקבל את הסטטוס של LRO ולהציג פרטים לגביו, קוראים לשיטה projects.locations.operations.get.

נניח שקיבלתם את התגובה הבאה אחרי שקראתם ל-projects.locations.processors.batchProcess:

{
  "name": "projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID"
}

הערך name בתגובה מציין ש-Document AI API יצר LRO בשם projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_ID.

אפשר גם לאחזר את שם ה-LRO על ידי רישום פעולות ממושכות.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION: המיקום שבו פועל ה-LRO, לדוגמה:
    • us – ארצות הברית
    • eu - האיחוד האירופי
  • OPERATION_ID: מזהה הפעולה. המזהה הוא הרכיב האחרון בשם של הפעולה. לדוגמה:
    • שם הפעולה: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • מזהה הפעולה: bc4e1d412863e626

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessMetadata",
    "state": "SUCCEEDED",
    "stateMessage": "Processed 1 document(s) successfully",
    "createTime": "TIMESTAMP",
    "updateTime": "TIMESTAMP",
    "individualProcessStatuses": [
      {
        "inputGcsSource": "INPUT_BUCKET_FOLDER/DOCUMENT1.ext",
        "status": {},
        "outputGcsDestination": "OUTPUT_BUCKET_FOLDER/OPERATION_ID/0",
        "humanReviewStatus": {
          "state": "ERROR",
          "stateMessage": "Sharded document protos are not supported for human review."
        }
      }
    ]
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessResponse"
  }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Document AI Go API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


//go:build examples

package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.GetOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#GetOperationRequest.
	}
	resp, err := c.GetOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Python

למידע נוסף, קראו את מאמרי העזרה של Document AI Python API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import GetOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def get_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = GetOperationRequest(name=operation_name)

    # Make GetOperation request
    operation = client.get_operation(request=request)
    # Print the Operation Information
    print(operation)

הצגת רשימה של פעולות ממושכות

בדוגמאות הבאות אפשר לראות איך מציגים את הפעולות הממושכות בפרויקט ובמיקום מסוימים. Google Cloud

REST

כדי להציג רשימה של פעולות LRO ב Google Cloud פרויקט ובמיקום, צריך לבצע קריאה ל-method‏ projects.locations.operations.list.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION: המיקום שבו פועלות פעולות LRO אחת או יותר, לדוגמה:
    • us – ארצות הברית
    • eu - האיחוד האירופי
  • FILTER: (חובה) שאילתה ל-LRO להחזרה. אפשרויות:
    • TYPE: (חובה) סוג ה-LRO שרוצים להציג. אפשרויות:
      • BATCH_PROCESS_DOCUMENTS
      • CREATE_PROCESSOR_VERSION
      • DELETE_PROCESSOR
      • ENABLE_PROCESSOR
      • DISABLE_PROCESSOR
      • UPDATE_HUMAN_REVIEW_CONFIG
      • HUMAN_REVIEW_EVENT
      • CREATE_LABELER_POOL
      • UPDATE_LABELER_POOL
      • DELETE_LABELER_POOL
      • DEPLOY_PROCESSOR_VERSION
      • UNDEPLOY_PROCESSOR_VERSION
      • DELETE_PROCESSOR_VERSION
      • SET_DEFAULT_PROCESSOR_VERSION
      • EVALUATE_PROCESSOR_VERSION
      • EXPORT_PROCESSOR_VERSION
      • UPDATE_DATASET
      • IMPORT_DOCUMENTS
      • ANALYZE_HITL_DATA
      • BATCH_MOVE_DOCUMENTS
      • RESYNC_DATASET
      • BATCH_DELETE_DOCUMENTS
      • DELETE_DATA_LABELING_JOB
      • EXPORT_DOCUMENTS

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations?filter=TYPE=TYPE" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{
  "operations": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID",
      "metadata": {
        "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessMetadata",
        "state": "SUCCEEDED",
        "stateMessage": "Processed 1 document(s) successfully",
        "createTime": "TIMESTAMP",
        "updateTime": "TIMESTAMP",
        "individualProcessStatuses": [
          {
            "inputGcsSource": "INPUT_BUCKET_FOLDER/DOCUMENT1.ext",
            "status": {},
            "outputGcsDestination": "OUTPUT_BUCKET_FOLDER/OPERATION_ID/0",
            "humanReviewStatus": {
              "state": "ERROR",
              "stateMessage": "Sharded document protos are not supported for human review."
            }
          }
        ]
      },
      "done": true,
      "response": {
        "@type": "type.googleapis.com/google.cloud.documentai.v1.BatchProcessResponse"
      }
    },
    ...
  ]
}

Go

למידע נוסף, קראו את מאמרי העזרה של Document AI Go API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


//go:build examples

package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.ListOperationsRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#ListOperationsRequest.
	}
	it := c.ListOperations(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp

		// If you need to access the underlying RPC response,
		// you can do so by casting the `Response` as below.
		// Otherwise, remove this line. Only populated after
		// first call to Next(). Not safe for concurrent access.
		_ = it.Response.(*longrunningpb.ListOperationsResponse)
	}
}

Python

למידע נוסף, קראו את מאמרי העזרה של Document AI Python API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import ListOperationsRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# project_id = "YOUR_PROJECT_ID"
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"

# Create filter in https://google.aip.dev/160 syntax
# For full options, refer to:
# https://cloud.google.com/document-ai/docs/long-running-operations#listing_long-running_operations
# operations_filter = 'YOUR_FILTER'

# Example:
# operations_filter = "TYPE=BATCH_PROCESS_DOCUMENTS AND STATE=RUNNING"


def list_operations_sample(
    project_id: str, location: str, operations_filter: str
) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    # Format: `projects/{project_id}/locations/{location}`
    name = client.common_location_path(project=project_id, location=location)
    request = ListOperationsRequest(
        name=f"{name}/operations",
        filter=operations_filter,
    )

    # Make ListOperations request
    operations = client.list_operations(request=request)

    # Print the Operation Information
    print(operations)

דגימה של פעולה ממושכת

בדוגמאות הבאות אפשר לראות איך לשלוח שאילתה כדי לבדוק את הסטטוס של פעולה ארוכת טווח.

REST

כדי לבצע שאילתה לגבי LRO, צריך להפעיל שוב ושוב את השיטה projects.locations.operations.get עד שהפעולה מסתיימת. צריך להשתמש בהשהיה לפני ניסיון חוזר בין כל בקשת בדיקה, למשל 10 שניות.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud
  • LOCATION: המיקום שבו פועל ה-LRO
  • OPERATION_ID: המזהה של ה-LRO

ה-method של ה-HTTP וכתובת ה-URL:

GET https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID
  

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה כדי לבדוק את הסטטוס של פעולת LRO כל 10 שניות:

while true; \
    do curl -X GET \
    -H "Authorization: Bearer "$(gcloud auth print-access-token) \
    "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID"; \
    sleep 10; \
    done

אתם אמורים לקבל תגובת JSON כל 10 שניות. בזמן שהפעולה פועלת, התגובה תכיל את הערך "state": "RUNNING". כשהפעולה מסתיימת, התגובה מכילה את הערכים "state": "SUCCEEDED" ו-"done": true.

PowerShell

מריצים את הפקודה הבאה כדי לבדוק את הסטטוס של פעולת LRO כל עשר שניות:

$cred = gcloud auth print-access-token
$headers = @{ Authorization = "Bearer $cred" }

Do {
  Invoke-WebRequest `
    -Method Get `
    -Headers $headers `
    -Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID" | Select-Object -Expand Content
sleep 10
}

while ($true)

אתם אמורים לקבל תגובת JSON כל 10 שניות. בזמן שהפעולה פועלת, התגובה תכיל את הערך "state": "RUNNING". כשהפעולה מסתיימת, התגובה מכילה את הערכים "state": "SUCCEEDED" ו-"done": true.

Python

למידע נוסף, קראו את מאמרי העזרה של Document AI Python API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


from time import sleep

from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import GetOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def poll_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = GetOperationRequest(name=operation_name)

    while True:
        # Make GetOperation request
        operation = client.get_operation(request=request)
        # Print the Operation Information
        print(operation)

        # Stop polling when Operation is no longer running
        if operation.done:
            break

        # Wait 10 seconds before polling again
        sleep(10)

ביטול פעולה ממושכת

בדוגמאות הבאות מוצגות דרכים לביטול פעולת LRO בזמן שהיא פועלת.

REST

כדי לבטל LRO, מבצעים קריאה ל-method‏ projects.locations.operations.cancel.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • LOCATION: המיקום שבו פועל ה-LRO, לדוגמה:
    • us – ארצות הברית
    • eu - האיחוד האירופי
  • OPERATION_ID: מזהה הפעולה. המזהה הוא הרכיב האחרון בשם של הפעולה. לדוגמה:
    • שם הפעולה: projects/PROJECT_ID/locations/LOCATION/operations/bc4e1d412863e626
    • מזהה הפעולה: bc4e1d412863e626

ה-method של ה-HTTP וכתובת ה-URL:

POST https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://LOCATION-documentai.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/operations/OPERATION_ID:cancel" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}
אם מנסים לבטל פעולה שכבר הושלמה, אמורה להופיע הודעת השגיאה הבאה:
  "error": {
      "code": 400,
      "message": "Operation has completed and cannot be cancelled: 'PROJECT_ID/locations/LOCATION/operations/OPERATION_ID'.",
      "status": "FAILED_PRECONDITION"
  }

Go

למידע נוסף, קראו את מאמרי העזרה של Document AI Go API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


//go:build examples

package main

import (
	"context"

	documentai "cloud.google.com/go/documentai/apiv1"
	longrunningpb "cloud.google.com/go/longrunning/autogen/longrunningpb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := documentai.NewDocumentProcessorClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &longrunningpb.CancelOperationRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/longrunning/autogen/longrunningpb#CancelOperationRequest.
	}
	err = c.CancelOperation(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
}

Python

למידע נוסף, קראו את מאמרי העזרה של Document AI Python API.

כדי לבצע אימות ב-Document AI, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore
from google.longrunning.operations_pb2 import CancelOperationRequest  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# location = "YOUR_PROCESSOR_LOCATION"  # Format is "us" or "eu"
# operation_name = "YOUR_OPERATION_NAME"  # Format is "projects/{project_id}/locations/{location}/operations/{operation_id}"


def cancel_operation_sample(location: str, operation_name: str) -> None:
    # You must set the `api_endpoint` if you use a location other than "us".
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    request = CancelOperationRequest(name=operation_name)

    # Make CancelOperation request
    client.cancel_operation(request=request)
    print(f"Operation {operation_name} cancelled")