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

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

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

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

הרשומה של LRO נשמרת למשך כ-30 יום אחרי שה-LRO מסתיים, כלומר אי אפשר להציג או לרשום LRO אחרי פרק הזמן הזה.

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

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

REST

כדי לקבל את הסטטוס של LRO ולראות פרטים עליו, מפעילים את ה-method‏ 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)

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

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

REST

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

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

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION: המיקום שבו פועלת פעולה אחת או יותר לטווח ארוך, לדוגמה:
    • us – ארצות הברית
    • eu – האיחוד האירופי
  • ‫FILTER: (חובה) שאילתה להחזרת פעולות לטווח ארוך. אפשרויות:
    • ‫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)

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

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

REST

כדי לדגום LRO, צריך להפעיל שוב ושוב את השיטה projects.locations.operations.get עד שהפעולה מסתיימת. צריך להשתמש בהשהיה לפני ניסיון חוזר (backoff) בין כל בקשת סקר, למשל 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")