การรู้จำอักขระด้วยภาพ (OCR) ด้วย Document AI (Python)

1. ภาพรวม

Document AI คืออะไร

Document AI เป็นโซลูชันความเข้าใจเอกสารที่ใช้ Unstructured Data (เช่น เอกสาร อีเมล ใบแจ้งหนี้ แบบฟอร์ม ฯลฯ) และทำให้ข้อมูลเข้าใจ วิเคราะห์ และนำไปใช้ได้ง่ายขึ้น API มีโครงสร้างผ่านการจัดประเภทเนื้อหา การแยกเอนทิตี การค้นหาขั้นสูง และอื่นๆ

ในแล็บนี้ คุณจะได้เรียนรู้วิธีใช้ Optical Character Recognition โดยใช้ Document AI API กับ Python

เราจะใช้ไฟล์ PDF ของนวนิยายคลาสสิกเรื่อง "วินนี เดอะ พูห์" ของ A.A. Milne ซึ่งเพิ่งกลายเป็นส่วนหนึ่งของโดเมนสาธารณะในสหรัฐอเมริกา Google Books สแกนและแปลงไฟล์นี้เป็นดิจิทัล

สิ่งที่คุณจะได้เรียนรู้

  • วิธีเปิดใช้ Document AI API
  • วิธีตรวจสอบสิทธิ์คำขอ API
  • วิธีติดตั้งไลบรารีของไคลเอ็นต์สำหรับ Python
  • วิธีใช้ API การประมวลผลแบบออนไลน์และแบบเป็นกลุ่ม
  • วิธีแยกวิเคราะห์ข้อความจากไฟล์ PDF

สิ่งที่คุณต้องมี

  • โปรเจ็กต์ Google Cloud
  • เบราว์เซอร์ เช่น Chrome หรือ Firefox
  • คุ้นเคยกับการใช้ Python (3.9 ขึ้นไป)

แบบสำรวจ

คุณจะใช้บทแนะนำนี้อย่างไร

อ่านอย่างเดียว อ่านและทำแบบฝึกหัด

คุณจะให้คะแนนประสบการณ์การใช้งาน Python เท่าใด

ผู้ฝึกหัด ขั้นกลาง ผู้ชำนาญ

คุณจะให้คะแนนประสบการณ์การใช้บริการ Google Cloud เท่าใด

ผู้ฝึกหัด ขั้นกลาง ผู้ชำนาญ

2. การตั้งค่าและข้อกำหนด

การตั้งค่าสภาพแวดล้อมแบบเรียนรู้ด้วยตนเอง

  1. ลงชื่อเข้าใช้ Cloud Console แล้วสร้างโปรเจ็กต์ใหม่หรือใช้โปรเจ็กต์ที่มีอยู่ซ้ำ (หากยังไม่มีบัญชี Gmail หรือ Google Workspace คุณต้องสร้างบัญชี)

เลือกโปรเจ็กต์

โปรเจ็กต์ใหม่

รับรหัสโปรเจ็กต์

โปรดจดจำรหัสโปรเจ็กต์ ซึ่งเป็นชื่อที่ไม่ซ้ำกันในโปรเจ็กต์ Google Cloud ทั้งหมด (มีผู้ใช้รหัสโปรเจ็กต์ข้างต้นไปแล้วและจะใช้ไม่ได้ ขออภัย) คุณต้องระบุรหัสนี้ในภายหลังเป็น PROJECT_ID

  1. จากนั้นคุณต้องเปิดใช้การเรียกเก็บเงินใน Cloud Console เพื่อใช้ทรัพยากร Google Cloud

โปรดทำตามวิธีการในส่วน "การล้างข้อมูล" ส่วนนี้จะแนะนำวิธีปิดแหล่งข้อมูลเพื่อไม่ให้มีการเรียกเก็บเงินนอกเหนือจากบทแนะนำนี้ ผู้ใช้ Google Cloud รายใหม่มีสิทธิ์เข้าร่วมโปรแกรมช่วงทดลองใช้ฟรีมูลค่า$300 USD

เริ่มต้น Cloud Shell

แม้ว่าคุณจะใช้งาน Google Cloud จากแล็ปท็อประยะไกลได้ แต่โค้ดแล็บนี้จะใช้ Google Cloud Shell ซึ่งเป็นสภาพแวดล้อมบรรทัดคำสั่งที่ทำงานในระบบคลาวด์

เปิดใช้งาน Cloud Shell

  1. จาก Cloud Console ให้คลิกเปิดใช้งาน Cloud Shell เปิดใช้งาน Cloud Shell

เปิดใช้งาน Cloud Shell

หากไม่เคยเริ่มใช้ Cloud Shell มาก่อน คุณจะเห็นหน้าจอระดับกลาง (ด้านล่าง) ที่อธิบายว่า Cloud Shell คืออะไร ในกรณีนี้ ให้คลิกต่อไป (และคุณจะไม่เห็นหน้าจอนี้อีก) หน้าจอแบบครั้งเดียวจะมีลักษณะดังนี้

ข้อมูลเบื้องต้นเกี่ยวกับ Cloud Shell

การจัดสรรและเชื่อมต่อกับ Cloud Shell จะใช้เวลาเพียงไม่กี่นาที Cloud Shell

Cloud Shell ให้สิทธิ์เข้าถึงเทอร์มินัลแก่เครื่องเสมือนที่โฮสต์ในระบบคลาวด์ เครื่องเสมือนมีเครื่องมือพัฒนาทั้งหมดที่คุณต้องการ โดยมีไดเรกทอรีหลักแบบถาวรขนาด 5 GB และทำงานใน Google Cloud ซึ่งช่วยเพิ่มประสิทธิภาพเครือข่ายและการตรวจสอบสิทธิ์ได้อย่างมาก คุณสามารถทำงานใน Codelab นี้ได้โดยใช้เพียงเบราว์เซอร์

เมื่อเชื่อมต่อกับ Cloud Shell แล้ว คุณควรเห็นว่าคุณได้รับการตรวจสอบสิทธิ์แล้วและโปรเจ็กต์ได้รับการตั้งค่าเป็นรหัสโปรเจ็กต์ของคุณแล้ว

  1. เรียกใช้คำสั่งต่อไปนี้ใน 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

คุณต้องเปิดใช้ API ก่อนจึงจะเริ่มใช้ Document AI ได้ คุณทำได้โดยใช้gcloudอินเทอร์เฟซบรรทัดคำสั่งหรือ Cloud Console

ใช้ gcloud CLI

  1. หากไม่ได้ใช้ Cloud Shell ให้ทำตามขั้นตอนในติดตั้ง gcloud CLI ในเครื่องของคุณ
  2. คุณเปิดใช้ API ได้โดยใช้คำสั่ง gcloud ต่อไปนี้
gcloud services enable documentai.googleapis.com storage.googleapis.com

คุณควรเห็นข้อความคล้ายกับข้อความต่อไปนี้

Operation "operations/..." finished successfully.

ใช้ Cloud Console

เปิด Cloud Console ในเบราว์เซอร์

  1. ใช้แถบค้นหาที่ด้านบนของคอนโซลเพื่อค้นหา "Document AI API" จากนั้นคลิกเปิดใช้เพื่อใช้ API ในโปรเจ็กต์ Google Cloud

Search API

  1. ทำขั้นตอนก่อนหน้าซ้ำสำหรับ Google Cloud Storage API

ตอนนี้คุณใช้ Document AI ได้แล้ว

4. สร้างและทดสอบโปรเซสเซอร์

คุณต้องสร้างอินสแตนซ์ของโปรเซสเซอร์ OCR ของเอกสารที่จะทำการแยกข้อมูลก่อน โดยสามารถดำเนินการนี้ให้เสร็จสมบูรณ์ได้โดยใช้ Cloud Console หรือ Processor Management API

Cloud Console

  1. ในคอนโซล ให้ไปที่ภาพรวมแพลตฟอร์ม Document AIคอนโซลภาพรวมของ Document AI
  2. คลิกสำรวจโปรเซสเซอร์ แล้วเลือก OCR ของเอกสารโปรเซสเซอร์
  3. ตั้งชื่อว่า codelab-ocr (หรือชื่ออื่นที่คุณจะจำได้) แล้วเลือกภูมิภาคที่ใกล้ที่สุดในรายการ
  4. คลิกสร้างเพื่อสร้างโปรเซสเซอร์
  5. คัดลอกรหัสโปรเซสเซอร์ คุณต้องใช้รหัสนี้ในโค้ดในภายหลัง รหัสโปรเซสเซอร์

คุณสามารถทดสอบโปรเซสเซอร์ในคอนโซลได้โดยการอัปโหลดเอกสาร คลิกอัปโหลดเอกสารทดสอบ แล้วเลือกเอกสารที่จะแยกวิเคราะห์

คุณสามารถดาวน์โหลดไฟล์ PDF ด้านล่างซึ่งมี 3 หน้าแรกของนวนิยายของเรา

หน้าชื่อเรื่อง

เอาต์พุตควรมีลักษณะดังนี้ หนังสือที่แยกวิเคราะห์

ไลบรารีของไคลเอ็นต์ Python

ทำตาม Codelab นี้เพื่อดูวิธีจัดการโปรเซสเซอร์ Document AI ด้วยไลบรารีของไคลเอ็นต์ Python

การจัดการโปรเซสเซอร์ Document AI ด้วย Python - Codelab

5. ตรวจสอบสิทธิ์คำขอ API

หากต้องการส่งคำขอไปยัง Document AI API คุณต้องใช้บัญชีบริการ บัญชีบริการเป็นของโปรเจ็กต์ของคุณ และไลบรารีของไคลเอ็นต์ Python จะใช้บัญชีนี้เพื่อส่งคำขอ API บัญชีบริการจะแสดงด้วยอีเมลเช่นเดียวกับบัญชีผู้ใช้อื่นๆ ในส่วนนี้ คุณจะใช้ Cloud SDK เพื่อสร้างบัญชีบริการ จากนั้นสร้างข้อมูลเข้าสู่ระบบที่ต้องใช้เพื่อตรวจสอบสิทธิ์ในฐานะบัญชีบริการ

ก่อนอื่น ให้เปิด Cloud Shell แล้วตั้งค่าตัวแปรสภาพแวดล้อมด้วย PROJECT_ID ซึ่งคุณจะใช้ตลอดทั้งโค้ดแล็บนี้

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 ได้โดยใช้ลิงก์ต่อไปนี้ จากนั้นอัปโหลดไปยังอินสแตนซ์ Cloud Shell

นอกจากนี้ คุณยังดาวน์โหลดได้จาก Bucket ของ Google Cloud Storage แบบสาธารณะของเราโดยใช้ gsutil

gsutil cp gs://cloud-samples-data/documentai/codelabs/ocr/Winnie_the_Pooh_3_Pages.pdf .

8. ส่งคำขอการประมวลผลทางออนไลน์

ในขั้นตอนนี้ คุณจะประมวลผล 3 หน้าแรกของนิยายโดยใช้ 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. ส่งคำขอการประมวลผลแบบกลุ่ม

สมมติว่าคุณต้องการอ่านข้อความจากทั้งนวนิยาย

  • การประมวลผลออนไลน์มีข้อจำกัดเกี่ยวกับจำนวนหน้าและขนาดไฟล์ที่ส่งได้ และอนุญาตให้ส่งไฟล์เอกสารได้เพียง 1 ไฟล์ต่อการเรียกใช้ API 1 ครั้ง
  • การประมวลผลเป็นกลุ่มช่วยให้ประมวลผลไฟล์ขนาดใหญ่ขึ้น/หลายไฟล์ได้ด้วยวิธีแบบอะซิงโครนัส

ในขั้นตอนนี้ เราจะประมวลผลนวนิยาย "วินนี เดอะ พูห์" ทั้งหมดด้วย Document AI Batch Processing API และส่งออกข้อความไปยัง Bucket ของ 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 Bucket เพื่อจัดเก็บเอาต์พุตของ 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

เรามีไดเรกทอรีใน Bucket ตัวอย่างที่มีนวนิยายหลายหน้าในไฟล์แยกกัน

  • 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 Toolbox

การประมวลผลแบบกลุ่มต้องมีหลายขั้นตอนจึงจะดำเนินการให้เสร็จสมบูรณ์ได้เนื่องจากการผสานรวมกับ Cloud Storage Document เอาต์พุตอาจ "แยก" เป็นไฟล์ .json หลายไฟล์ด้วย ทั้งนี้ขึ้นอยู่กับขนาดของเอกสารอินพุต

Python SDK ของ Document AI Toolbox สร้างขึ้นเพื่อลดความซับซ้อนของการประมวลผลภายหลังและงานทั่วไปอื่นๆ ด้วย Document AI ไลบรารีนี้มีไว้เพื่อเสริมไลบรารีของไคลเอ็นต์ Document AI ไม่ใช่เพื่อใช้แทน ดูข้อกำหนดทั้งหมดได้ที่เอกสารอ้างอิง

ขั้นตอนนี้แสดงวิธีส่งคำขอประมวลผลเป็นกลุ่มและดึงข้อมูลเอาต์พุตโดยใช้ Document AI Toolbox

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 Console ให้ไปที่หน้าจัดการทรัพยากร
  • เลือกโปรเจ็กต์ในรายการโปรเจ็กต์ แล้วคลิกลบ
  • ในกล่องโต้ตอบ ให้พิมพ์รหัสโปรเจ็กต์ แล้วคลิกปิดเพื่อลบโปรเจ็กต์

ดูข้อมูลเพิ่มเติม

เรียนรู้เพิ่มเติมเกี่ยวกับ Document AI ด้วย Codelab ที่เกี่ยวข้องต่อไปนี้

แหล่งข้อมูล

ใบอนุญาต

ผลงานนี้ได้รับอนุญาตภายใต้สัญญาอนุญาตครีเอทีฟคอมมอนส์สำหรับยอมรับสิทธิของผู้สร้าง (Creative Commons Attribution License) 2.0 แบบทั่วไป