בדף הזה מוסבר איך להעתיק גרסאות של מעבד מאומן של Document AI מפרויקט אחד לפרויקט אחר, יחד עם סכימת מערך הנתונים ודוגמאות ממקור למעבד היעד. השלבים האלה מאפשרים לייבא את גרסת המעבד, לפרוס אותה ולהגדיר אותה כגרסת ברירת המחדל בפרויקט היעד באופן אוטומטי.
לפני שמתחילים
- מקבלים מזהה פרויקט ב- Google Cloud .
- יש לכם את מזהה המעבד של Document AI.
- יש לכם Cloud Storage.
- שימוש ב-Python: מחברת Jupyter (Vertex AI).
- צריך הרשאות כדי לתת גישה לחשבון השירות בפרויקטים של המקור והיעד.
הליך מפורט
התהליך מפורט בשלבים הבאים.
שלב 1: זיהוי חשבון השירות שמשויך ל-Vertex AI Notebook
!gcloud config list account
פלט:
[core]
account = example@automl-project.iam.gserviceaccount.com
Your active configuration is: [default]
שלב 2: מעניקים את ההרשאות הנדרשות לחשבון השירות
בפרויקט Google Cloud שהוא היעד המיועד להעברה, מוסיפים את חשבון השירות שהתקבל בשלב הקודם כחשבון משתמש ומקצים את שני התפקידים הבאים:
- אדמין של Document AI
- ניהול נפח האחסון
מידע נוסף זמין במאמרים הענקת תפקידים לחשבונות שירות ומפתחות הצפנה בניהול הלקוח (CMEK).

כדי שההעברה תפעל, לחשבון השירות שמשמש להפעלת ה-notebook הזה צריכות להיות ההרשאות הבאות:
- תפקידים בפרויקטים של המקור ושל היעד כדי ליצור את קטגוריית מערך הנתונים, או ליצור אותה אם היא לא קיימת, וגם הרשאות קריאה וכתיבה לכל האובייקטים.
- תפקיד עורך ב-Document AI בפרויקט המקור, כפי שמתואר במאמר בנושא ייבוא גרסת מעבד.
מורידים מפתח JSON לחשבון השירות, כדי שתוכלו לבצע אימות ולקבל הרשאה כחשבון שירות. מידע נוסף מופיע במאמר מפתחות של חשבונות שירות.
השלב הבא:
- עוברים לחשבון השירות.
- בוחרים את חשבון השירות שמיועד לבצע את המשימה הזו.
- עוברים לכרטיסייה Keys, לוחצים על
Add Keyובוחרים באפשרות Create new key. - בוחרים את סוג המפתח (מומלץ JSON).
לוחצים על
Createומורידים לנתיב ספציפי.
מעדכנים את הנתיב במשתנה
service_account_keyבקטע הקוד הבא.
service_account_key='path_to_sa_key.json'
from google.oauth2 import service_account
from google.cloud import storage
# Authenticate the service account
credentials = service_account.Credentials.from_service_account_file(
service_account_key
)
# pass this credentials variable to all client initializations
# storage_client = storage.Client(credentials=credentials)
# docai_client = documentai.DocumentProcessorServiceClient(credentials=credentials)
שלב 3: ייבוא ספריות
import time
from pathlib import Path
from typing import Optional, Tuple
from google.cloud.documentai_v1beta3.services.document_service import pagers
from google.api_core.client_options import ClientOptions
from google.api_core.operation import Operation
from google.cloud import documentai_v1beta3 as documentai
from google.cloud import storage
from tqdm import tqdm
שלב 4: מזינים את הפרטים
- source_project_id: מציינים את מזהה פרויקט המקור.
- source_location: מציינים את המיקום של מעבד המקור (
usאוeu). - source_processor_id: צריך לספק את Google Cloud מזהה המעבד של Document AI.
- source_processor_version_to_import: מזינים את מזהה גרסת המעבד של Document AI של הגרסה שאומנה. Google Cloud
- migrate_dataset: אם רוצים להעביר מערך נתונים ממעבד המקור למעבד היעד, צריך לספק את הערך
True. אחרת, צריך לספק את הערךFalse.TrueFalseערך ברירת המחדל הואFalse. - source_exported_gcs_path: מציינים את הנתיב ב-Cloud Storage לאחסון קובצי JSON.
- destination_project_id: מציינים את מזהה פרויקט היעד.
- destination_processor_id: מזינים את מזהה המעבד של Document AI,
""אוprocessor_idמפרויקט היעד. Google Cloud
source_project_id = "source-project-id"
source_location = "processor-location"
source_processor_id = "source-processor-id"
source_processor_version_to_import = "source-processor-version-id"
migrate_dataset = False # Either True or False
source_exported_gcs_path = (
"gs://bucket/path/to/export_dataset/"
)
destination_project_id = "< destination-project-id >"
# Give an empty string if you wish to create a new processor
destination_processor_id = ""
שלב 5: מריצים את הקוד
import time
from pathlib import Path
from typing import Optional, Tuple
from google.cloud.documentai_v1beta3.services.document_service import pagers
from google.api_core.client_options import ClientOptions
from google.api_core.operation import Operation
from google.cloud import documentai_v1beta3 as documentai
from google.cloud import storage
from tqdm import tqdm
source_project_id = "source-project-id"
source_location = "processor-location"
source_processor_id = "source-processor-id"
source_processor_version_to_import = "source-processor-version-id"
migrate_dataset = False # Either True or False
source_exported_gcs_path = (
"gs://bucket/path/to/export_dataset/"
)
destination_project_id = "< destination-project-id >"
# Give empty string if you wish to create a new processor
destination_processor_id = ""
exported_bucket_name = source_exported_gcs_path.split("/")[2]
exported_bucket_path_prefix = "/".join(source_exported_gcs_path.split("/")[3:])
destination_location = source_location
def sample_get_processor(project_id: str, processor_id: str, location: str)->Tuple[str, str]:
"""
This function returns Processor Display Name and Type of Processor from source project
Args:
project_id (str): Project ID
processor_id (str): Document AI Processor ID
location (str): Processor Location
Returns:
Tuple[str, str]: Returns Processor Display name and type
"""
client = documentai.DocumentProcessorServiceClient()
print(
f"Fetching processor({processor_id}) details from source project ({project_id})"
)
name = f"projects/{project_id}/locations/{location}/processors/{processor_id}"
request = documentai.GetProcessorRequest(
name=name,
)
response = client.get_processor(request=request)
print(f"Processor Name: {response.name}")
print(f"Processor Display Name: {response.display_name}")
print(f"Processor Type: {response.type_}")
return response.display_name, response.type_
def sample_create_processor(project_id: str, location: str, display_name: str, processor_type: str)->documentai.Processor:
"""It will create Processor in Destination project
Args:
project_id (str): Project ID
location (str): Location fo processor
display_name (str): Processor Display Name
processor_type (str): Google Cloud Document AI Processor type
Returns:
documentai.Processor: Returns details abouts newly created processor
"""
client = documentai.DocumentProcessorServiceClient()
request = documentai.CreateProcessorRequest(
parent=f"projects/{project_id}/locations/{location}",
processor={
"type_": processor_type,
"display_name": display_name,
},
)
print(f"Creating Processor in project: {project_id} in location: {location}")
print(f"Display Name: {display_name} & Processor Type: {processor_type}")
res = client.create_processor(request=request)
return res
def initialize_dataset(project_id: str, processor_id: str, location: str)-> Operation:
"""It will configure dataset for target processor in destination project
Args:
project_id (str): Project ID
processor_id (str): DocuemntAI Processor ID
location (str): Processor Location
Returns:
Operation: An object representing a long-running operation
"""
# opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")
client = documentai.DocumentServiceClient() # client_options=opts
dataset = documentai.types.Dataset(
name=f"projects/{project_id}/locations/{location}/processors/{processor_id}/dataset",
state=3,
unmanaged_dataset_config={},
spanner_indexing_config={},
)
request = documentai.types.UpdateDatasetRequest(dataset=dataset)
print(
f"Configuring Dataset in project: {project_id} for processor: {processor_id}"
)
response = client.update_dataset(request=request)
return response
def get_dataset_schema(project_id: str, processor_id: str, location: str)->documentai.DatasetSchema:
"""It helps to fetch processor schema
Args:
project_id (str): Project ID
processor_id (str): DocumentAI Processor ID
location (str): Processor Location
Returns:
documentai.DatasetSchema: Return deails about Processor Dataset Schema
"""
# Create a client
processor_name = (
f"projects/{project_id}/locations/{location}/processors/{processor_id}"
)
client = documentai.DocumentServiceClient()
request = documentai.GetDatasetSchemaRequest(
name=processor_name + "/dataset/datasetSchema"
)
# Make the request
print(f"Fetching schema from source processor: {processor_id}")
response = client.get_dataset_schema(request=request)
return response
def upload_dataset_schema(schema: documentai.DatasetSchema)->documentai.DatasetSchema:
"""It helps to update the schema in destination processor
Args:
schema (documentai.DatasetSchema): Document AI Processor Schema details & Metadata
Returns:
documentai.DatasetSchema: Returns Dataset Schema object
"""
client = documentai.DocumentServiceClient()
request = documentai.UpdateDatasetSchemaRequest(dataset_schema=schema)
print("Updating Schema in destination processor")
res = client.update_dataset_schema(request=request)
return res
def store_document_as_json(document: str, bucket_name: str, file_name: str)->None:
"""It helps to upload data to Cloud Storage and stores as a blob
Args:
document (str): Processor response in json string format
bucket_name (str): Cloud Storage bucket name
file_name (str): Cloud Storage blob uri
"""
print(f"\tUploading file to Cloud Storage gs://{bucket_name}/{file_name}")
storage_client = storage.Client()
process_result_bucket = storage_client.get_bucket(bucket_name)
document_blob = storage.Blob(
name=str(Path(file_name)), bucket=process_result_bucket
)
document_blob.upload_from_string(document, content_type="application/json")
def list_documents(project_id: str, location: str, processor: str, page_size: Optional[int]=100, page_token: Optional[str]="")->pagers.ListDocumentsPager:
"""This function helps to list the samples present in processor dataset
Args:
project_id (str): Project ID
location (str): Processor Location
processor (str): DocumentAI Processor ID
page_size (Optional[int], optional): The maximum number of documents to return. Defaults to 100.
page_token (Optional[str], optional): A page token, received from a previous ListDocuments call. Defaults to "".
Returns:
pagers.ListDocumentsPager: Returns all details about documents present in Processor Dataset
"""
client = documentai.DocumentServiceClient()
dataset = (
f"projects/{project_id}/locations/{location}/processors/{processor}/dataset"
)
request = documentai.types.ListDocumentsRequest(
dataset=dataset,
page_token=page_token,
page_size=page_size,
return_total_size=True,
)
print(f"Listingll documents/Samples present in processor: {processor}")
operation = client.list_documents(request)
return operation
def get_document(project_id: str, location: str, processor: str, doc_id: documentai.DocumentId)->documentai.