1. סקירה כללית
מה זה Document AI?
Document AI הוא פתרון להבנת מסמכים שלוקח נתונים לא מובנים (למשל מסמכים, אימיילים, חשבוניות, טפסים וכו') ועוזר להבין, לנתח ולצרוך את הנתונים בקלות רבה יותר. ה-API מספק מבנה באמצעות סיווג תוכן, חילוץ ישויות, חיפוש מתקדם ועוד.
בשיעור ה-Lab הזה תלמדו איך לבצע זיהוי תווים אופטי (OCR) באמצעות Document AI API עם Python.
נשתמש בקובץ PDF של הרומן הקלאסי "פוף" מאת A.A. Milne, שהפך לאחרונה לנחלת הכלל בארצות הברית. הקובץ נסרק והפך לדיגיטלי על ידי Google Books.
מה תלמדו
- איך מפעילים את Document AI API
- איך לאמת בקשות API
- איך להתקין את ספריית הלקוח ל-Python
- איך להשתמש בממשקי ה-API לעיבוד אונליין ובעיבוד ברצף (batch processing)
- איך לנתח טקסט מקובץ PDF
מה צריך להכין
סקר
איך תשתמשו במדריך הזה?
איזה דירוג מגיע לדעתך לחוויה שלך עם Python?
איזה דירוג מגיע לדעתך לחוויית השימוש שלך בשירותי Google Cloud?
2. הגדרה ודרישות
הגדרת סביבה בקצב עצמאי
- נכנסים למסוף Cloud ויוצרים פרויקט חדש או עושים שימוש חוזר בפרויקט קיים. (אם אין לכם עדיין חשבון Gmail או חשבון Google Workspace, עליכם ליצור חשבון).
חשוב לזכור את מזהה הפרויקט – שם ייחודי בכל הפרויקטים ב-Google Cloud. (מזהה הפרויקט שלמעלה כבר תפוס ולא יעבוד, סליחה!). חובה לספק את המזהה הזה בהמשך בתור PROJECT_ID
.
- בשלב הבא צריך להפעיל את החיוב במסוף Cloud כדי להשתמש במשאבים של Google Cloud.
חשוב לבצע את כל ההוראות בקטע 'ניקוי' . הקטע מסביר איך להשבית את המשאבים כדי שלא תצברו חיובים מעבר למדריך הזה. משתמשים חדשים ב-Google Cloud זכאים להשתתף בתוכנית תקופת ניסיון בחינם בשווי 1,200 ש"ח.
הפעלת Cloud Shell
אפשר לתפעל את Google Cloud מרחוק מהמחשב הנייד ב-Google Cloud, אבל ה-Codelab הזה משתמש ב-Google Cloud Shell, סביבת שורת הפקודה שפועלת ב-Cloud.
הפעלת Cloud Shell
- במסוף Cloud, לוחצים על Activate Cloud Shell
.
אם לא השתמשתם ב-Cloud Shell בעבר, יוצג לכם מסך ביניים (בחלק הנגלל) שמתאר מהו. במקרה כזה, לוחצים על המשך (וזה לא יקרה שוב). כך נראה המסך החד-פעמי:
ההקצאה וההתחברות ל-Cloud Shell נמשכת כמה דקות.
פלטפורמת Cloud Shell נותנת לכם גישה למסוף למכונה וירטואלית שמתארחת בענן. המכונה הווירטואלית כוללת את כל כלי הפיתוח הדרושים לך. יש בה ספריית בית בנפח מתמיד של 5GB והיא פועלת ב-Google Cloud, מה שמשפר משמעותית את ביצועי הרשת והאימות. אם לא את כולן, ניתן לבצע חלק גדול מהעבודה ב-Codelab הזה באמצעות דפדפן בלבד.
אחרי ההתחברות ל-Cloud Shell, אתם אמורים לראות שכבר בוצע אימות ושהפרויקט כבר מוגדר לפי מזהה הפרויקט שלכם.
- מריצים את הפקודה הבאה ב-Cloud Shell כדי לוודא שהאימות בוצע:
gcloud auth list
פלט הפקודה
Credentialed Accounts ACTIVE ACCOUNT * <my_account>@<my_domain.com> To set the active account, run: $ gcloud config set account `ACCOUNT`
gcloud config list project
פלט הפקודה
[core] project = <PROJECT_ID>
אם היא לא נמצאת שם, תוכלו להגדיר אותה באמצעות הפקודה הבאה:
gcloud config set project <PROJECT_ID>
פלט הפקודה
Updated property [core/project].
3. הפעלת Document AI API
לפני שמתחילים להשתמש ב-Document AI, צריך להפעיל את ה-API. אפשר לבצע זאת באמצעות ממשק שורת הפקודה gcloud
או מסוף Cloud.
שימוש ב- CLI gcloud
- אם אתם לא משתמשים ב-Cloud Shell, עליכם לפעול לפי השלבים שבמאמר התקנת ה-CLI של
gcloud
במחשב המקומי. - אפשר להפעיל את ממשקי ה-API באמצעות פקודות
gcloud
הבאות.
gcloud services enable documentai.googleapis.com storage.googleapis.com
אתם אמורים לראות משהו כזה:
Operation "operations/..." finished successfully.
שימוש במסוף Cloud
פותחים את מסוף Cloud בדפדפן.
- בסרגל החיפוש שבחלק העליון של המסוף, מחפשים את Document AI API ולוחצים על Enable כדי להשתמש ב-API בפרויקט ב-Google Cloud.
- חוזרים על השלב הקודם עם Google Cloud Storage API.
עכשיו אפשר להשתמש ב-Document AI!
4. יצירה ובדיקה של מעבד
תחילה עליך ליצור מופע של מעבד המסמך OCR שיבצע את החילוץ. אפשר לעשות זאת באמצעות ה-Cloud Console או Processor Management API.
Cloud Console
- במסוף, עוברים אל Document AI Platform Overview
- לוחצים על חיפוש מעבדי מידע ובוחרים באפשרות OCR של מסמכים
- נותנים למרחב המשותף את השם
codelab-ocr
(או משהו אחר שתזכרו) ובוחרים את האזור הקרוב ביותר מהרשימה. - לוחצים על יצירה כדי ליצור את המעבד.
- מעתיקים את מזהה מעבד המידע. חובה להשתמש בה בקוד מאוחר יותר.
אפשר לבדוק את המעבד במסוף על ידי העלאת מסמך. לוחצים על Upload Test Document (העלאת מסמך הבדיקה) ובוחרים את המסמך שרוצים לנתח.
ניתן להוריד את קובץ ה-PDF שבהמשך, שמכיל את 3 העמודים הראשונים של הרומן שלנו.
הפלט שלכם אמור להיראות כך:
ספריית לקוח של Python
בסרטון הזה מוסבר איך לנהל מעבדי מסמכים ב-Document AI באמצעות ספריית הלקוח של Python:
5. אימות בקשות API
כדי לשלוח בקשות ל-Document AI API, עליך להשתמש בחשבון שירות. חשבון שירות שייך לפרויקט שלכם ומשמש את ספריית הלקוח של Python כדי לשלוח בקשות API. כמו כל חשבון משתמש אחר, חשבון שירות מיוצג על ידי כתובת אימייל. בקטע הזה משתמשים ב-Cloud SDK כדי ליצור חשבון שירות, ולאחר מכן יוצרים פרטי כניסה שנדרשים לאימות כחשבון השירות.
קודם כול פותחים את Cloud Shell ומגדירים משתנה סביבה עם PROJECT_ID
, שבו תשתמשו ב-Codelab הזה:
export GOOGLE_CLOUD_PROJECT=$(gcloud config get-value core/project)
בשלב הבא, יוצרים חשבון שירות חדש כדי לגשת ל-Document AI API באמצעות:
gcloud iam service-accounts create my-docai-sa \
--display-name "my-docai-service-account"
בשלב הבא, צריך לתת לחשבון השירות הרשאות גישה ל-Document AI ול-Cloud Storage בפרויקט.
gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
--member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
--role="roles/documentai.admin"
gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
--member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
--role="roles/storage.admin"
gcloud projects add-iam-policy-binding ${GOOGLE_CLOUD_PROJECT} \
--member="serviceAccount:my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com" \
--role="roles/serviceusage.serviceUsageConsumer"
בשלב הבא, יוצרים את פרטי הכניסה שבהם קוד Python משתמש כדי להתחבר בתור חשבון השירות החדש. יוצרים את פרטי הכניסה האלה ושומרים אותם כקובץ JSON ~/key.json
באמצעות הפקודה הבאה:
gcloud iam service-accounts keys create ~/key.json \
--iam-account my-docai-sa@${GOOGLE_CLOUD_PROJECT}.iam.gserviceaccount.com
לסיום, מגדירים את משתנה הסביבה GOOGLE_APPLICATION_CREDENTIALS, שבו הספרייה תשתמש כדי למצוא את פרטי הכניסה שלכם. למידע נוסף על אמצעי האימות הזה, ניתן לעיין במדריך. מגדירים את משתנה הסביבה לנתיב המלא של קובץ ה-JSON של פרטי הכניסה שיצרתם באמצעות:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/key.json"
6. התקנת ספריית הלקוח
מתקינים את ספריות הלקוח של Python ל-Document AI , Cloud Storage ו-Document AI Toolbox:
pip3 install --upgrade google-cloud-documentai
pip3 install --upgrade google-cloud-storage
pip3 install --upgrade google-cloud-documentai-toolbox
אתם אמורים לראות משהו כזה:
... Installing collected packages: google-cloud-documentai Successfully installed google-cloud-documentai-2.15.0 . . Installing collected packages: google-cloud-storage Successfully installed google-cloud-storage-2.9.0 . . Installing collected packages: google-cloud-documentai-toolbox Successfully installed google-cloud-documentai-toolbox-0.6.0a0
עכשיו אתם מוכנים להשתמש ב-Document AI API!
7. הורדת קובץ ה-PDF לדוגמה
יש לנו מסמך לדוגמה שמכיל את 3 הדפים הראשונים של הרומן.
אפשר להוריד את קובץ ה-PDF באמצעות הקישור הבא. לאחר מכן מעלים אותו למכונה של cloudshell.
אפשר גם להוריד אותו מהקטגוריה הציבורית של Google Cloud Storage באמצעות gsutil
.
gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh_3_Pages.pdf .
8. הגשת בקשה לעיבוד אונליין
בשלב הזה תעבדו את שלושת הדפים הראשונים של החדשנות באמצעות ה-API לעיבוד אונליין (סינכרוני). השיטה הזו מתאימה במיוחד למסמכים קטנים יותר שמאוחסנים באופן מקומי. ברשימת העיבוד המלאה מפורטים הדפים וגודל הקובץ המקסימליים של כל סוג מעבד.
משתמשים ב-Cloud Shell Editor או בכלי לעריכת טקסט במחשב המקומי כדי ליצור קובץ בשם online_processing.py
ולהשתמש בקוד הבא.
מחליפים את הערכים YOUR_PROJECT_ID
, YOUR_PROJECT_LOCATION
, YOUR_PROCESSOR_ID
ו-FILE_PATH
בערכים שמתאימים לסביבה שלכם.
online_processing.py
from google.api_core.client_options import ClientOptions
from google.cloud import documentai
PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "YOUR_PROJECT_LOCATION" # Format is 'us' or 'eu'
PROCESSOR_ID = "YOUR_PROCESSOR_ID" # Create processor in Cloud Console
# The local file in your current working directory
FILE_PATH = "Winnie_the_Pooh_3_Pages.pdf"
# Refer to https://cloud.google.com/document-ai/docs/file-types
# for supported file types
MIME_TYPE = "application/pdf"
# Instantiates a client
docai_client = documentai.DocumentProcessorServiceClient(
client_options=ClientOptions(api_endpoint=f"{LOCATION}-documentai.googleapis.com")
)
# 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
RESOURCE_NAME = docai_client.processor_path(PROJECT_ID, LOCATION, PROCESSOR_ID)
# Read the file into memory
with open(FILE_PATH, "rb") as image:
image_content = image.read()
# Load Binary Data into Document AI RawDocument Object
raw_document = documentai.RawDocument(content=image_content, mime_type=MIME_TYPE)
# Configure the process request
request = documentai.ProcessRequest(name=RESOURCE_NAME, raw_document=raw_document)
# Use the Document AI client to process the sample form
result = docai_client.process_document(request=request)
document_object = result.document
print("Document processing complete.")
print(f"Text: {document_object.text}")
מריצים את הקוד, כדי לחלץ את הטקסט ולהדפיס אותו במסוף.
אם אתם משתמשים במסמך לדוגמה שלנו, הפלט הבא אמור להופיע:
Document processing complete. Text: CHAPTER I IN WHICH We Are Introduced to Winnie-the-Pooh and Some Bees, and the Stories Begin Here is Edward Bear, coming downstairs now, bump, bump, bump, on the back of his head, behind Christopher Robin. It is, as far as he knows, the only way of coming downstairs, but sometimes he feels that there really is another way, if only he could stop bumping for a moment and think of it. And then he feels that perhaps there isn't. Anyhow, here he is at the bottom, and ready to be introduced to you. Winnie-the-Pooh. When I first heard his name, I said, just as you are going to say, "But I thought he was a boy?" "So did I," said Christopher Robin. "Then you can't call him Winnie?" "I don't." "But you said " ... Digitized by Google
9. שליחת בקשה לעיבוד באצווה
נניח שאתם רוצים לקרוא את הטקסט של כל הרומן.
- בעיבוד אונליין יש מגבלות על מספר הדפים וגודל הקובץ שניתן לשלוח, וניתן לשלוח רק קובץ מסמך אחד בכל קריאה ל-API.
- עיבוד באצווה מאפשר לעבד קבצים גדולים או מרובים בשיטה אסינכרונית.
בשלב הזה, נעבד את המודל המלא של "פוף" חדש ב-Document AI Batch Processing API ומפיק פלט של הטקסט לקטגוריה של Google Cloud Storage.
בעיבוד באצווה נעשה שימוש בפעולות ארוכות כדי לנהל בקשות באופן אסינכרוני, ולכן עלינו להגיש את הבקשה ולאחזר את הפלט בדרך שונה מעיבוד אונליין. עם זאת, הפלט יהיה באותו פורמט אובייקט Document
גם בעיבוד אונליין וגם בעיבוד באצווה.
בשלב הזה מוסבר איך לספק מסמכים ספציפיים לעיבוד ב-Document AI. בשלב מאוחר יותר יוצג לכם איך לעבד ספריית מסמכים שלמה.
העלאת קובץ PDF ל-Cloud Storage
השיטה batch_process_documents()
מקבלת כרגע קבצים מ-Google Cloud Storage. למידע נוסף על מבנה האובייקט, אפשר לעיין ב-documentai_v1.types.BatchProcessRequest
.
לצורך הדוגמה הזו, אפשר לקרוא את הקובץ ישירות מהקטגוריה לדוגמה שלנו.
אתם יכולים גם להעתיק את הקובץ לקטגוריה שלכם באמצעות gsutil
...
gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf gs://YOUR_BUCKET_NAME/
...או שתוכלו להוריד את הקובץ לדוגמה של הרומן מהקישור למטה ולהעלות אותו לקטגוריה שלכם.
צריך גם קטגוריה של GCS כדי לאחסן את הפלט של ה-API.
מסמכי העזרה של Cloud Storage כוללים מידע על יצירת קטגוריות אחסון.
באמצעות השיטה batch_process_documents()
יוצרים קובץ בשם batch_processing.py
ומשתמשים בקוד הבא.
מחליפים את YOUR_PROJECT_ID
, YOUR_PROCESSOR_LOCATION
, YOUR_PROCESSOR_ID
, YOUR_INPUT_URI
ו-YOUR_OUTPUT_URI
בערכים המתאימים לסביבה שלכם.
צריך לוודא ש-YOUR_INPUT_URI
מפנה ישירות לקובץ ה-PDF, לדוגמה: gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh.pdf
.
batch_processing.py
"""
Makes a Batch Processing Request to Document AI
"""
import re
from google.api_core.client_options import ClientOptions
from google.api_core.exceptions import InternalServerError
from google.api_core.exceptions import RetryError
from google.cloud import documentai
from google.cloud import storage
# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION" # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID" # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI" # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
"YOUR_PROCESSOR_VERSION_ID" # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)
# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI" # Format: `gs://bucket/directory/file.pdf` or `gs://bucket/directory/`
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber" # Optional. The fields to return in the Document object.
def batch_process_documents(
project_id: str,
location: str,
processor_id: str,
gcs_input_uri: str,
gcs_output_uri: str,
processor_version_id: str = None,
input_mime_type: str = None,
field_mask: str = None,
timeout: int = 400,
):
# 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)
if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
# Specify specific GCS URIs to process individual documents
gcs_document = documentai.GcsDocument(
gcs_uri=gcs_input_uri, mime_type=input_mime_type
)
# Load GCS Input URI into a List of document files
gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
else:
# Specify a GCS URI Prefix to process an entire directory
gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)
# Cloud Storage URI for the Output Directory
gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
gcs_uri=gcs_output_uri, field_mask=field_mask
)
# Where to write results
output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)
if processor_version_id:
# The full resource name of the processor version, e.g.:
# projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
name = client.processor_version_path(
project_id, location, processor_id, processor_version_id
)
else:
# The full resource name of the processor, e.g.:
# projects/{project_id}/locations/{location}/processors/{processor_id}
name = client.processor_path(project_id, location, processor_id)
request = documentai.BatchProcessRequest(
name=name,
input_documents=input_config,
document_output_config=output_config,
)
# BatchProcess returns a Long Running Operation (LRO)
operation = client.batch_process_documents(request)
# Continually polls the operation until it is complete.
# This could take some time for larger files
# Format: projects/{project_id}/locations/{location}/operations/{operation_id}
try:
print(f"Waiting for operation {operation.operation.name} to complete...")
operation.result(timeout=timeout)
# Catch exception when operation doesn"t finish before timeout
except (RetryError, InternalServerError) as e:
print(e.message)
# NOTE: Can also use callbacks for asynchronous processing
#
# def my_callback(future):
# result = future.result()
#
# operation.add_done_callback(my_callback)
# Once the operation is complete,
# get output document information from operation metadata
metadata = documentai.BatchProcessMetadata(operation.metadata)
if metadata.state != documentai.BatchProcessMetadata.State.SUCCEEDED:
raise ValueError(f"Batch Process Failed: {metadata.state_message}")
storage_client = storage.Client()
print("Output files:")
# One process per Input Document
for process in list(metadata.individual_process_statuses):
# output_gcs_destination format: gs://BUCKET/PREFIX/OPERATION_NUMBER/INPUT_FILE_NUMBER/
# The Cloud Storage API requires the bucket name and URI prefix separately
matches = re.match(r"gs://(.*?)/(.*)", process.output_gcs_destination)
if not matches:
print(
"Could not parse output GCS destination:",
process.output_gcs_destination,
)
continue
output_bucket, output_prefix = matches.groups()
# Get List of Document Objects from the Output Bucket
output_blobs = storage_client.list_blobs(output_bucket, prefix=output_prefix)
# Document AI may output multiple JSON files per source file
for blob in output_blobs:
# Document AI should only output JSON files to GCS
if blob.content_type != "application/json":
print(
f"Skipping non-supported file: {blob.name} - Mimetype: {blob.content_type}"
)
continue
# Download JSON File as bytes object and convert to Document Object
print(f"Fetching {blob.name}")
document = documentai.Document.from_json(
blob.download_as_bytes(), ignore_unknown_fields=True
)
# For a full list of Document object attributes, please reference this page:
# https://cloud.google.com/python/docs/reference/documentai/latest/google.cloud.documentai_v1.types.Document
# Read the text recognition output from the processor
print("The document contains the following text:")
print(document.text)
if __name__ == "__main__":
batch_process_documents(
project_id=project_id,
location=location,
processor_id=processor_id,
gcs_input_uri=gcs_input_uri,
gcs_output_uri=gcs_output_uri,
input_mime_type=input_mime_type,
field_mask=field_mask,
)
מריצים את הקוד. הטקסט החדש המלא אמור להיגמר ולהודפס במסוף.
יכול להיות שהשלמת הפעולה תימשך זמן מה כי הקובץ גדול בהרבה מהדוגמה הקודמת. (אוי, טרחה...)
עם זאת, באמצעות Batch Processing API, אחרי שהמשימה תושלם, תקבלו מזהה פעולה שיכול לשמש לקבלת הפלט מ-GCS.
הפלט שלכם אמור להיראות כך:
Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete... Document processing complete. Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-0.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-1.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-10.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-11.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-12.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-13.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-14.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-15.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-16.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-17.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-18.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-2.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-3.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-4.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-5.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-6.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-7.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-8.json Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh-9.json This is a reproduction of a library book that was digitized by Google as part of an ongoing effort to preserve the information in books and make it universally accessible. TM Google books https://books.google.com ..... He nodded and went out ... and in a moment I heard Winnie-the-Pooh -bump, bump, bump-go-ing up the stairs behind him. Digitized by Google
10. שליחת בקשה לעיבוד בכמות גדולה עבור ספרייה
לפעמים ייתכן שתרצו לעבד ספרייה שלמה של מסמכים, מבלי לרשום כל מסמך בנפרד. השיטה batch_process_documents()
תומכת בקלט של רשימה של מסמכים ספציפיים או נתיב ספרייה.
בשלב הזה נסביר איך לעבד ספרייה מלאה של קובצי מסמכים. רוב הקוד פועל כמו השלב הקודם. ההבדל היחיד הוא ה-URI של GCS שנשלח עם ה-BatchProcessRequest
.
יש לנו ספרייה בקטגוריה לדוגמה שלנו שמכילה דפים מרובים של הרומן בקבצים נפרדים.
gs://cloud-samples-data/documentai/codelabs/ocr/multi-document/
אתם יכולים לקרוא את הקבצים ישירות או להעתיק אותם לקטגוריה משלכם של Cloud Storage.
מריצים מחדש את הקוד מהשלב הקודם ומחליפים את YOUR_INPUT_URI
בספרייה ב-Cloud Storage.
מריצים את הקוד. הטקסט שחולץ מכל קובצי המסמכים אמור להופיע בספרייה של Cloud Storage.
הפלט שלכם אמור להיראות כך:
Waiting for operation projects/PROJECT_NUMBER/locations/LOCATION/operations/OPERATION_NUMBER to complete... Document processing complete. Fetching docai-output/OPERATION_NUMBER/0/Winnie_the_Pooh_Page_0-0.json Fetching docai-output/OPERATION_NUMBER/1/Winnie_the_Pooh_Page_1-0.json Fetching docai-output/OPERATION_NUMBER/2/Winnie_the_Pooh_Page_10-0.json Fetching docai-output/OPERATION_NUMBER/3/Winnie_the_Pooh_Page_12-0.json Fetching docai-output/OPERATION_NUMBER/4/Winnie_the_Pooh_Page_16-0.json Fetching docai-output/OPERATION_NUMBER/5/Winnie_the_Pooh_Page_7-0.json Introduction (I₂ F YOU happen to have read another book about Christopher Robin, you may remember th CHAPTER I IN WHICH We Are Introduced to Winnie-the-Pooh and Some Bees, and the Stories Begin HERE is 10 WINNIE-THE-POOH "I wonder if you've got such a thing as a balloon about you?" "A balloon?" "Yes, 12 WINNIE-THE-POOH and you took your gun with you, just in case, as you always did, and Winnie-the-P 16 WINNIE-THE-POOH this song, and one bee sat down on the nose of the cloud for a moment, and then g WE ARE INTRODUCED 7 "Oh, help!" said Pooh, as he dropped ten feet on the branch below him. "If only
11. טיפול בתגובה לעיבוד בכמות גדולה באמצעות ארגז הכלים של Document AI
כדי לבצע עיבוד ברצף (batch processing), יש הרבה שלבים שצריך לבצע בגלל השילוב עם Cloud Storage. גם הפלט של Document
עשוי להיות "מפוצל" במספר קובצי .json
, בהתאם לגודל של מסמך הקלט.
Python SDK של Document AI Toolbox נוצר כדי לפשט את העיבוד לאחר העיבוד ולבצע משימות נפוצות אחרות באמצעות Document AI. הספרייה הזו נועדה לשמש כתוספת לספריית הלקוח של Document AI, ולא כתחליף לספריית הלקוח. המפרט המלא מופיע במאמרי העזרה.
בשלב הזה מוסבר איך לשלוח בקשת עיבוד באצווה ולאחזר את הפלט באמצעות ארגז הכלים של Document AI.
batch_processing_toolbox.py
"""
Makes a Batch Processing Request to Document AI using Document AI Toolbox
"""
from google.api_core.client_options import ClientOptions
from google.cloud import documentai
from google.cloud import documentai_toolbox
# TODO(developer): Fill these variables before running the sample.
project_id = "YOUR_PROJECT_ID"
location = "YOUR_PROCESSOR_LOCATION" # Format is "us" or "eu"
processor_id = "YOUR_PROCESSOR_ID" # Create processor before running sample
gcs_output_uri = "YOUR_OUTPUT_URI" # Must end with a trailing slash `/`. Format: gs://bucket/directory/subdirectory/
processor_version_id = (
"YOUR_PROCESSOR_VERSION_ID" # Optional. Example: pretrained-ocr-v1.0-2020-09-23
)
# TODO(developer): If `gcs_input_uri` is a single file, `mime_type` must be specified.
gcs_input_uri = "YOUR_INPUT_URI" # Format: `gs://bucket/directory/file.pdf`` or `gs://bucket/directory/``
input_mime_type = "application/pdf"
field_mask = "text,entities,pages.pageNumber" # Optional. The fields to return in the Document object.
def batch_process_toolbox(
project_id: str,
location: str,
processor_id: str,
gcs_input_uri: str,
gcs_output_uri: str,
processor_version_id: str = None,
input_mime_type: str = None,
field_mask: 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)
if not gcs_input_uri.endswith("/") and "." in gcs_input_uri:
# Specify specific GCS URIs to process individual documents
gcs_document = documentai.GcsDocument(
gcs_uri=gcs_input_uri, mime_type=input_mime_type
)
# Load GCS Input URI into a List of document files
gcs_documents = documentai.GcsDocuments(documents=[gcs_document])
input_config = documentai.BatchDocumentsInputConfig(gcs_documents=gcs_documents)
else:
# Specify a GCS URI Prefix to process an entire directory
gcs_prefix = documentai.GcsPrefix(gcs_uri_prefix=gcs_input_uri)
input_config = documentai.BatchDocumentsInputConfig(gcs_prefix=gcs_prefix)
# Cloud Storage URI for the Output Directory
gcs_output_config = documentai.DocumentOutputConfig.GcsOutputConfig(
gcs_uri=gcs_output_uri, field_mask=field_mask
)
# Where to write results
output_config = documentai.DocumentOutputConfig(gcs_output_config=gcs_output_config)
if processor_version_id:
# The full resource name of the processor version, e.g.:
# projects/{project_id}/locations/{location}/processors/{processor_id}/processorVersions/{processor_version_id}
name = client.processor_version_path(
project_id, location, processor_id, processor_version_id
)
else:
# The full resource name of the processor, e.g.:
# projects/{project_id}/locations/{location}/processors/{processor_id}
name = client.processor_path(project_id, location, processor_id)
request = documentai.BatchProcessRequest(
name=name,
input_documents=input_config,
document_output_config=output_config,
)
# BatchProcess returns a Long Running Operation (LRO)
operation = client.batch_process_documents(request)
# Operation Name Format: projects/{project_id}/locations/{location}/operations/{operation_id}
documents = documentai_toolbox.document.Document.from_batch_process_operation(
location=location, operation_name=operation.operation.name
)
for document in documents:
# Read the text recognition output from the processor
print("The document contains the following text:")
# Truncated at 100 characters for brevity
print(document.text[:100])
if __name__ == "__main__":
batch_process_toolbox(
project_id=project_id,
location=location,
processor_id=processor_id,
gcs_input_uri=gcs_input_uri,
gcs_output_uri=gcs_output_uri,
input_mime_type=input_mime_type,
field_mask=field_mask,
)
12. מזל טוב
השתמשת בהצלחה ב-Document AI כדי לחלץ טקסט מספר חדש באמצעות עיבוד אונליין, עיבוד באצווה וארגז הכלים של Document AI.
מומלץ להתנסות במסמכים אחרים ולבדוק את המעבדים האחרים שזמינים בפלטפורמה.
הסרת המשאבים
כדי להימנע מצבירת חיובים בחשבון Google Cloud על המשאבים שבהם השתמשתם במדריך הזה:
- במסוף Cloud, עוברים לדף Manage resources.
- ברשימת הפרויקטים, בוחרים את הפרויקט הרלוונטי ולוחצים על 'מחיקה'.
- כדי למחוק את הפרויקט, כותבים את מזהה הפרויקט בתיבת הדו-שיח ולוחצים על Shut down.
מידע נוסף
ב-Codelabs הבאים תוכלו להמשיך ללמוד על Document AI.
- ניתוח טפסים באמצעות Document AI (Python)
- מעבדים מומחים עם Document AI (Python)
- ניהול מעבדים של Document AI באמצעות Python
- Document AI: אדם במרכז
מקורות מידע
- עתיד המסמכים – פלייליסט ב-YouTube
- מסמכי תיעוד מבוססי-AI של מסמכים
- ספריית הלקוח של Document AI Python
- מאגר דגימות של Document AI
רישיון
היצירה הזו בשימוש ברישיון Creative Commons Attribution 2.0 גנרי.